Events.php 58 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645
  1. <?php
  2. /**
  3. * This file is part of workerman.
  4. *
  5. * Licensed under The MIT License
  6. * For full copyright and license information, please see the MIT-LICENSE.txt
  7. * Redistributions of files must retain the above copyright notice.
  8. *
  9. * @author walkor<walkor@workerman.net>
  10. * @copyright walkor<walkor@workerman.net>
  11. * @link http://www.workerman.net/
  12. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  13. */
  14. /**
  15. * 用于检测业务代码死循环或者长时间阻塞等问题
  16. * 如果发现业务卡死,可以将下面declare打开(去掉//注释),并执行php start.php reload
  17. * 然后观察一段时间workerman.log看是否有process_timeout异常
  18. */
  19. //declare(ticks=1);
  20. use \GatewayWorker\Lib\Gateway;
  21. use Workerman\Lib\Timer;
  22. /**
  23. * 主逻辑
  24. * 主要是处理 onConnect onMessage onClose 三个方法
  25. * onConnect 和 onClose 如果不需要可以不用实现并删除
  26. */
  27. class Events
  28. {
  29. /**
  30. * 新建一个类的静态成员,用来保存数据库实例
  31. */
  32. public static $db = null;
  33. public static $global = null;
  34. public static $redis = null;
  35. public static $logic = null;
  36. const KFINFOKEY = 'KFINFO'; //客服信息hash表
  37. const USERINFOKEY = 'USERINFO'; //用户信息hash表
  38. const USERLIST = 'USERLIST'; //用户排队表
  39. const SERVICELOG = 'SERVICELOG'; //工单信息
  40. /**
  41. * 进程启动后初始化数据库连接
  42. */
  43. public static function onWorkerStart($worker)
  44. {
  45. include_once(__DIR__ . DIRECTORY_SEPARATOR . "Mlogic.php");
  46. self::$logic = Mlogic::GetInstance();
  47. self::$db = self::$logic->getDb();
  48. self::$redis = self::$logic->getRedis();
  49. self::$global = self::$logic->getGlbData();
  50. self::TimerThing($worker);
  51. // 管理员实时监控.
  52. /*Timer::add(6, function () {
  53. // 获取在线管理员总数.
  54. $adminListCount = self::$redis->lLen('adminList');
  55. // 获取在线管理员
  56. $adminList = self::$redis->lrange('adminList', 0, $adminListCount);
  57. if ($adminList) {
  58. self::systemMonitoring($adminList);
  59. }
  60. });*/
  61. // 检查对话时效给出.
  62. Timer::add(6, function () {
  63. self::overTime();
  64. });
  65. }
  66. /**
  67. * 每分钟定时向客服发送一次排队情况
  68. */
  69. public static function lineup()
  70. {
  71. $group = self::$global->groupmap;
  72. foreach ($group as $groupid => $gname) {
  73. $users = self::getUselistData($groupid);
  74. if (!empty($users)) {
  75. Gateway::sendToGroup('group_' . $groupid, json_encode(['type' => 'lineupCount', coung($users)], 256));
  76. }
  77. }
  78. }
  79. /**
  80. * 当客户端连接时触发
  81. * 如果业务不需此回调可以删除onConnect
  82. *
  83. * @param int $client_id 连接id
  84. */
  85. public static function onConnect($client_id)
  86. {
  87. // 检测是否开启自动应答
  88. $sayHello = self::$global->replay['1'];
  89. if (!empty($sayHello) && 1 == $sayHello['status']) {
  90. $hello = [
  91. 'message_type' => 'helloMessage',
  92. 'data' => [
  93. 'name' => '智能助手',
  94. 'time' => date('H:i'),
  95. 'content' => $sayHello['word']
  96. ]
  97. ];
  98. Gateway::sendToClient($client_id, json_encode($hello, 256));
  99. unset($hello);
  100. }
  101. unset($sayHello);
  102. // 检测是否开启广告
  103. $advertisement = self::$db->query('select * from `ws_advertisement` where `advertisement_status` = 1');
  104. if (!empty($advertisement)) {
  105. $chat_message = [
  106. 'message_type' => 'advertisement',
  107. 'data' => $advertisement
  108. ];
  109. Gateway::sendToClient($client_id, json_encode($chat_message, 256));
  110. unset($chat_message);
  111. }
  112. unset($advertisement);
  113. }
  114. /**
  115. * 当客户端发来消息时触发
  116. * @param int $client_id 连接id
  117. * @param mixed $message 具体消息
  118. */
  119. public static function onMessage($client_id, $message)
  120. {
  121. if ($message == '{"type":"ping"}') {
  122. Gateway::sendToCurrentClient('{"type":"pong"}');
  123. return;
  124. } else {
  125. self::DebugOut($message, "OnMessage");
  126. }
  127. $message = json_decode($message, true);
  128. if (isset($message['type'])) {
  129. switch ($message['type']) {
  130. case 'mydebug':
  131. self::mydebug($client_id, $message['data']);
  132. break;
  133. // 管理员初始化
  134. case 'adminInit':
  135. $token = $message['token'];
  136. self::adminInit($client_id, $token);
  137. break;
  138. // 客服初始化
  139. case 'init':
  140. $data = $message['data'];
  141. self::Kfinit($client_id, $data);
  142. break;
  143. // 顾客初始化
  144. case 'userInit';
  145. $data = $message['data'];
  146. self::userInitEnt($client_id, $data);
  147. break;
  148. //在线客服信息
  149. case 'getkfonlines':
  150. Gateway::sendToCurrentClient(json_encode(self::getkfonlines(), 256));
  151. break;
  152. case 'kfgetuserinfo':
  153. $tmp_id = isset($message['data']['id']) ? $message['data']['id'] : 0;
  154. self::kfgetuserinfo($client_id, intval($tmp_id));
  155. break;
  156. // 客服聊天
  157. case 'chatMessage':
  158. self::chatMessage($message['data']);
  159. break;
  160. // 转接
  161. case 'changeGroup':
  162. break;
  163. case 'closeUser':
  164. break;
  165. // 机器人问答.
  166. case 'toRobot':
  167. self::toRobot($client_id, $message);
  168. break;
  169. // 评价.
  170. case 'evaluate':
  171. self::evaluate($client_id, $message);
  172. break;
  173. // 客服关闭会话.
  174. case 'kfCloseUser':
  175. self::serverClose($message['data']['conversationId'], 3);
  176. break;
  177. // 客服更改状态.
  178. case 'kfOnline':
  179. self::KFStatusCg($client_id, $message);
  180. break;
  181. case 'changeOtherhKeFu';
  182. self::changeOtherhKeFu($client_id, $message);
  183. break;
  184. // 弹出评价.
  185. case 'getEvaluate';
  186. break;
  187. }
  188. }
  189. }
  190. //客服聊天
  191. public static function chatMessage($message)
  192. {
  193. // 获取当前会话工单.
  194. $data = json_decode(self::$redis->HGET('SERVICELOG', $message['conversationId']), true);
  195. if (empty($data)) {
  196. return;
  197. }
  198. $chat_message = [
  199. 'message_type' => 'chatMessage',
  200. 'data' => [
  201. 'name' => $message['from_name'],
  202. 'id' => $message['from_id'],
  203. 'time' => date('H:i'),
  204. 'content' => $message['content'],
  205. ]
  206. ];
  207. if (isset($message['isFirst']) && $message['isFirst']) {
  208. $data['alarm_corresponding'] = time() - $data['start_time'];
  209. $data['alarm_respond'] = 2;
  210. }
  211. // 发送消息.
  212. if (substr($message['from_id'], 0, 2) === 'KF') {
  213. $data['userLastTime'] = time();
  214. Gateway::sendToClient($data['client_id'], json_encode($chat_message, 256));
  215. } else {
  216. $data['serverLastTime'] = time();
  217. Gateway::sendToClient($data['kf_client_id'], json_encode($chat_message, 256));
  218. }
  219. // 保存修改后的工单信息.
  220. self::$redis->HSET('SERVICELOG', $message['conversationId'], json_encode($data, 256));
  221. // 聊天信息入库
  222. $insertChatData = [
  223. 'from_id' => $message['from_id'],
  224. 'from_name' => $message['from_name'],
  225. 'to_id' => $message['to_id'],
  226. 'to_name' => $message['to_name'],
  227. 'content' => $message['content'],
  228. 'servicelog_id' => $message['conversationId'],
  229. 'time_line' => time()
  230. ];
  231. self::$db->insert('ws_chat_log')->cols($insertChatData)->query();
  232. }
  233. //得到一个用户详细信息
  234. public static function kfgetuserinfo($clientid, $id)
  235. {
  236. $ret = self::$db->select('*')->from('ws_account')->where('id=:id')->bindValues(['id' => $id])->row();
  237. Gateway::sendToClient($clientid, json_encode(['message_type' => 'userdetailinfo', 'data' => $ret]));
  238. return;
  239. }
  240. //获取在线客服列表
  241. public static function getkfonlines()
  242. {
  243. $return = [
  244. 'message_type' => 'onlinekfs',
  245. 'data' => [],
  246. ];
  247. $nowkfid = isset($_SESSION['uid']) ? $_SESSION['uid'] : 0;
  248. $fromgrouupid = isset($_SESSION['group']) ? $_SESSION['group'] : 0;
  249. if (empty($fromgrouupid) || empty($nowkfid)) {
  250. return $return;
  251. }
  252. $online = self::getOnlineKfData(0, 1);
  253. if (empty($online)) {
  254. return $return;
  255. }
  256. $groupnamemap = self::$global->groupmap;
  257. $ret = [];
  258. foreach ($online as $uinfo) {
  259. if ($nowkfid == $uinfo['id']) {
  260. continue;
  261. }
  262. $ret[] = ['groupid' => $uinfo['group'], 'groupname' => $groupnamemap[$uinfo['group']], 'kfuid' => $uinfo['id'], 'kfname' => $uinfo['name'], 'kfjobname' => $uinfo['job_name']];
  263. }
  264. $return['data'] = $ret;
  265. return $return;
  266. }
  267. public static function KFStatusCg($client_id, $message)
  268. {
  269. if (!isset($_SESSION['iskefu']) || $_SESSION['iskefu'] != 1) {
  270. return;
  271. }
  272. $userId = $message['data']['uid'];
  273. $status = intval($message['data']['status']);
  274. if (!in_array($status, [1, 2, 3])) {
  275. return false;
  276. }
  277. $oldstatus = '';
  278. $kfinfo = self::$redis->hget(self::KFINFOKEY, $userId);
  279. if (empty($kfinfo)) {
  280. return false;
  281. }
  282. $kfinfo = json_decode($kfinfo, true);
  283. if (!$kfinfo) {
  284. return false;
  285. }
  286. if ($kfinfo['status'] != $status) {
  287. $oldstatus = $kfinfo['status'];
  288. $kfinfo['status'] = $status;
  289. self::$redis->hset(self::KFINFOKEY, $userId, json_encode($kfinfo, 256));
  290. }
  291. self::writeLogKfStatus($userId, $status);
  292. Gateway::sendToCurrentClient(json_encode(['message_type' => 'cgstatus', 'data' => ['new_status' => $status, 'old_status' => $oldstatus]]));
  293. return;
  294. }
  295. //获取某个用户全部信息
  296. public static function getClientIndo($id)
  297. {
  298. $ret = self::$db->from('ws_accounts')->select("*")->where(['id' => $id])->row();
  299. return $ret;
  300. }
  301. //客服接入sock,及初始化
  302. public static function Kfinit($client_id, $message)
  303. {
  304. $uid = self::getPars($message, 'uid');
  305. $group = intval(self::getPars($message, 'group', 0));
  306. if (empty($uid) || empty($group) || !isset(self::$global->groupmap[$group])) {
  307. self::MySendMsg($client_id, json_encode(["message_type" => 'checkfalse', 'data' => "客服登陆参数错误"], 256));
  308. Gateway::closeCurrentClient();
  309. return;
  310. }
  311. $loginstate = self::$logic->userIsLogin($client_id, $uid, $group);
  312. if ($loginstate == 1) {
  313. self::MySendMsg($oldcontid, (json_encode(['message_type' => 'reLoginErr', 'msg' => '正在登陆中,请稍后...'], 256)));
  314. Gateway::closeClient($oldcontid);
  315. return;
  316. }
  317. //客服登陆验证 不符合的直接断掉
  318. $kfinfo = self::KfloginCheck($client_id, $message);
  319. if (empty($kfinfo)) {
  320. self::MySendMsg($client_id, json_encode(["message_type" => 'checkfalse', 'data' => "验证失败"], 256));
  321. Gateway::closeCurrentClient();
  322. return true;
  323. } elseif ($kfinfo['status'] != 1) {
  324. self::MySendMsg($client_id, json_encode(["message_type" => 'checkfalse', 'data' => "禁用中..."], 256));
  325. Gateway::closeCurrentClient();
  326. return true;
  327. }
  328. if ($loginstate == 2) {
  329. $oldcontids = Gateway::getClientIdByUid($uid);
  330. Gateway::sendToClient($oldcontids['0'], (json_encode(['message_type' => 'reLoginErr', 'msg' => '你的账号在其它登陆,本次下线'], 256)));
  331. Gateway::closeClient($oldcontids['0']);
  332. sleep(2);
  333. }
  334. self::$redis->hset('loginTmp:' . $uid, 'uid', time());
  335. self::$redis->expire('loginTmp:' . $uid, 5);
  336. $newinfo =
  337. [
  338. 'id' => 'KF' . $kfinfo['id'],
  339. 'name' => $kfinfo['user_name'],
  340. 'job_name' => $kfinfo['user_job_number'],
  341. 'avatar' => $kfinfo['user_avatar'],
  342. 'group' => $group,
  343. 'client_id' => $client_id,
  344. 'task' => 0,
  345. 'intime' => time(),
  346. 'signature' => $kfinfo['signature'],
  347. 'status' => 2, // 1为在线(接收分配、接收消息)2为隐身(不接收分配、只接收消息)3、休息
  348. 'user_info' => [], //在会话的用户cid key为clientid ,值为工单号
  349. ];
  350. self::$redis->hset(self::KFINFOKEY, $uid, json_encode($newinfo, 256));
  351. $_SESSION['info'] = $newinfo;
  352. // 绑定 client_id 和 uid
  353. Gateway::bindUid($client_id, $message['uid']);
  354. $_SESSION['group'] = $message['group'];
  355. $_SESSION['iskefu'] = 1;
  356. $_SESSION['uid'] = $message['uid'];
  357. $_SESSION['name'] = $message['name'];
  358. Gateway::joinGroup($client_id, 'group_' . $message['group']);
  359. $chat_message = [
  360. 'message_type' => 'loginSuccess',
  361. ];
  362. self::MySendMsg($client_id, json_encode($chat_message, 256));
  363. unset($chat_message);
  364. self::writeLogKfStatus($message['uid'], 2);
  365. return;
  366. }
  367. /**
  368. * 管理员
  369. * @param $client_id 服务ID
  370. * @param $message 数据
  371. */
  372. public static function adminInit($client_id, $token)
  373. {
  374. // 查询token是否存在.
  375. $systemConfigData = self::$db->query("SELECT `id` FROM `ws_admins` where `token`= '$token'");
  376. if ($systemConfigData) {
  377. $adminList = self::$redis->lpush('adminList', $client_id);
  378. self::systemMonitoring([$client_id]);
  379. } else {
  380. $chat_message = [
  381. 'message_type' => 'tips',
  382. 'data' => '管理员不存在'
  383. ];
  384. Gateway::sendToClient($client_id, json_encode($chat_message, 256));
  385. Gateway::closeClient($client_id);
  386. }
  387. }
  388. //客服登陆验证
  389. public static function KfloginCheck($client, $messageArray)
  390. {
  391. $uid = isset($messageArray['uid']) ? $messageArray['uid'] : '';
  392. $token = isset($messageArray['token']) ? $messageArray['token'] : '';
  393. if (empty($uid) || empty($token)) {
  394. return false;
  395. }
  396. $expire_time_vali = time() - 60 * 60 * 24;
  397. $kfid = intval(substr($uid, 2));
  398. $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();
  399. if ($ret) {
  400. self::$db->update('ws_users')->cols(array('online_status' => 1, 'online_connectid' => $client))->where('id=' . $kfid)->query();
  401. return $ret;
  402. }
  403. return false;
  404. }
  405. //用户发送邦定用户事件
  406. public static function userInitEnt($client_id, $message)
  407. {
  408. $uid = intval($message['uid']);
  409. $group = intval($message['group']);
  410. if (!isset(self::$global->groupmap[$group])) {
  411. self::MySendMsg($client_id, (json_encode(['message_type' => 'reLoginErr', 'msg' => '不存在客服组....'], 256)));
  412. Gateway::closeCurrentClient();
  413. }
  414. $loginstate = self::$logic->userIsLogin($client_id, $uid, $group);
  415. if ($loginstate == 1) {
  416. self::MySendMsg($oldcontid, (json_encode(['message_type' => 'reLoginErr', 'msg' => '正在登陆中,请稍后...'], 256)));
  417. Gateway::closeCurrentClient();
  418. return;
  419. }
  420. $hisdata = self::$redis->hget(self::USERINFOKEY, $uid);
  421. if ($hisdata) {
  422. $hisdata = json_decode($hisdata, true);
  423. $oldclientid = $hisdata['client_id'];
  424. self::MySendMsg($oldclientid, json_encode(['type' => 'reLoginErr', 'msg' => '相同账号登陆,本次退出'], 256));
  425. Gateway::closeClient($oldclientid);
  426. sleep(1);
  427. }
  428. $onlinekf = self::getOnlineKfData($group, 1);
  429. if (empty($onlinekf)) {
  430. Gateway::sendToClient($client_id, json_encode(['message_type' => 'notice', 'content' => '暂时没有客服上班,请稍后再咨询。'], 256));
  431. Gateway::closeClient($client_id);
  432. return;
  433. }
  434. self::$redis->hset('loginTmp:' . $uid, 'uid', time());
  435. self::$redis->expire('loginTmp:' . $uid, 5);
  436. $data = [
  437. 'id' => $uid,
  438. 'name' => $message['name'],
  439. 'avatar' => $message['avatar'],
  440. 'website' => $_SESSION['origin'],//$_SERVER['HTTP_ORIGIN'],
  441. 'browse' => Gateway::browse_info(),
  442. 'system' => Gateway::get_os(),
  443. 'ip' => isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '',
  444. 'group' => $message['group'],
  445. 'intime' => time(),
  446. 'kfuid' => '',
  447. 'ip' => $_SESSION['remotip'],
  448. 'serverid' => 0,
  449. 'client_id' => $client_id
  450. ];
  451. self::$redis->hset(self::USERLIST, $uid, json_encode($data, 256));
  452. self::$redis->hset(self::USERINFOKEY, $uid, json_encode($data, 256));
  453. // 写入接入值
  454. $key = date('Ymd') . 'total_in';
  455. self::$global->increment($key);
  456. // 绑定 client_id 和 uid
  457. Gateway::bindUid($client_id, $uid);
  458. $_SESSION['iskefu'] = 0;
  459. $_SESSION['uid'] = $message['uid'];
  460. // 尝试分配新会员进入服务
  461. self::userOnlineTask($group, $uid);
  462. }
  463. /**
  464. * 当用户断开连接时触发
  465. * @param int $client_id 连接id
  466. *
  467. * tips: 当服务端主动退出的时候,会出现 exit status 9.原因是:服务端主动断开之后,连接的客户端会走这个方法,而短时间内进程
  468. * 需要处理这多的逻辑,又有cas操作,导致进程退出会超时,然后会被内核杀死,从而报出错误 9.实际对真正的业务没有任何的影响。
  469. */
  470. public static function onClose($client_id)
  471. {
  472. $isKefuoff = isset($_SESSION['iskefu']) ? $_SESSION['iskefu'] : 0;
  473. $uid = isset($_SESSION['uid']) ? $_SESSION['uid'] : false;
  474. echo "下线:uid: $uid - cid: $client_id - iskf: $isKefuoff \n";
  475. $adminList = self::$global->adminList ?? [];
  476. $key = array_search($client_id, $adminList);
  477. if (strlen($key)) {
  478. array_splice($adminList, $key, 1);
  479. self::$global->adminList = $adminList;
  480. }
  481. if (empty($uid)) {
  482. return;
  483. }
  484. if ($isKefuoff) {
  485. self::serviceOffline($client_id, $uid);
  486. } else {
  487. self::guestOffline($client_id, $uid);
  488. }
  489. return;
  490. }
  491. //客服下线了 系统调用,不能手动调用
  492. public static function serviceOffline($client_id, $uid)
  493. {
  494. $group = $_SESSION['group'];
  495. $uinfo = self::$redis->hget(self::KFINFOKEY, $uid);
  496. $uinfo = json_decode($uinfo, true);
  497. $user_info = $uinfo['user_info'];
  498. $kfid = self::getkfid($uid);
  499. $now = time();
  500. $starttime = $now - 86400 * 7;
  501. self::$redis->hset('loginTmp:' . $uid, 'uid', time());
  502. self::$redis->expire('loginTmp:' . $uid, 5);
  503. if (!empty($user_info)) {
  504. foreach ($user_info as $val => $serverid) {
  505. self::$redis->hdel(self::SERVICELOG, intval($serverid));
  506. self::MySendMsg($val, json_encode(['message_type' => 'serviceoffline', 'msg' => '客户人员下线!'], 256));
  507. Gateway::closeClient($val);
  508. }
  509. }
  510. $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 ";
  511. echo "客服退出: " . $uid . "\n";
  512. self::$db->query($sql);
  513. self::$db->update('ws_users')->cols(array('online_status' => 0, 'online_connectid' => ''))->where('id=' . $kfid)->query();
  514. self::writeLogKfStatus($uid, 0);
  515. self::$redis->hdel(self::KFINFOKEY, $uid);
  516. return;
  517. }
  518. //用户下线了 系统调用,不能手动调用
  519. public static function guestOffline($client_id, $uid)
  520. {
  521. self::$redis->hset('loginTmp:' . $uid, 'uid', time());
  522. self::$redis->expire('loginTmp:' . $uid, 3);
  523. $uid = intval($uid);
  524. $krclient_id = 0;
  525. $data = self::$redis->hget(self::USERINFOKEY, $uid);
  526. if (empty($data)) {
  527. return;
  528. }
  529. $info = json_decode($data, true);
  530. self::$redis->hdel(self::USERLIST, $uid);
  531. self::$redis->hdel(self::USERINFOKEY, $uid);
  532. if (!empty($info['kfuid'])) {
  533. $kfinfo = self::$redis->hget(self::KFINFOKEY, $info['kfuid']);
  534. if (!empty($kfinfo)) {
  535. $kfinfoArr = json_decode($kfinfo, true);
  536. $krclient_id = $kfinfoArr['client_id'];
  537. $kfinfoArr['user_info'] = self::ArrayDataopt($kfinfoArr['user_info'], $client_id, 0);
  538. $kfinfoArr['task'] = count($kfinfoArr['user_info']);
  539. self::$redis->hset(self::KFINFOKEY, $info['kfuid'], json_encode($kfinfoArr, 256));
  540. }
  541. }
  542. $chat_message = [
  543. 'message_type' => 'userClose',
  544. 'data' => [
  545. 'content' => '用户连接已断开',
  546. 'id' => $uid,
  547. 'time' => date('H:i'),
  548. ]
  549. ];
  550. $now = time();
  551. $serverid = intval($info['serverid']);
  552. if ($serverid) {
  553. $sql = "update `ws_service_log` set `status` = '3' where servicelog_id=$serverid ";
  554. self::$db->query($sql);
  555. }
  556. if ($krclient_id) {
  557. Gateway::sendToClient($krclient_id, json_encode($chat_message, 256));
  558. }
  559. return;
  560. }
  561. /**
  562. * 客服结束会话
  563. *
  564. * tips: 未有$client_id的关闭
  565. */
  566. public static function closeUser($servicelog_id, $userId, $kf_id, $groupId)
  567. {
  568. }
  569. /**
  570. * 工单结束
  571. * @param int $client_id 连接id
  572. *
  573. * tips: 当服务端主动退出的时候,会出现 exit status 9.原因是:服务端主动断开之后,连接的客户端会走这个方法,而短时间内进程
  574. * 需要处理这多的逻辑,又有cas操作,导致进程退出会超时,然后会被内核杀死,从而报出错误 9.实际对真正的业务没有任何的影响。
  575. */
  576. public static function serverClose($servicelogId, $closeBy = 0)
  577. {
  578. // 获取当前工单数据.
  579. $data = json_decode(self::$redis->HGET('SERVICELOG', $servicelogId), true);
  580. if (empty($data)) {
  581. return;
  582. }
  583. // 获取当前工单数据.
  584. $kfInfo = json_decode(self::$redis->HGET('KFINFO', 'KF' . $data['kf_id']), true);
  585. // 删除当前工单.
  586. self::$redis->hdel('SERVICELOG', $servicelogId);
  587. // 当前服务客服删除当前人员.
  588. $kfUserList = self::ArrayDataopt($kfInfo['user_info'], $data['client_id'], 0);
  589. // 删除当前人员信息.
  590. self::$redis->hdel('USERINFO', $data['user_id']);
  591. // 当前客服所接待人员.
  592. $kfInfo['user_info'] = $kfUserList;
  593. $kfInfo['task'] = count($kfUserList);
  594. // 存入客服信息.
  595. self::$redis->HSET('KFINFO', 'KF' . $data['kf_id'], json_encode($kfInfo, 256));
  596. // 发送消息给用户.
  597. $chat_message = [
  598. 'message_type' => 'closeBysever',
  599. 'data' => [
  600. 'content' => '客服停止了该会话',
  601. 'time' => date('H:i'),
  602. ]
  603. ];
  604. Gateway::sendToClient($data['client_id'], json_encode($chat_message, 256));
  605. // 关闭用户连接.
  606. Gateway::closeClient($data['client_id']);
  607. // 发送消息给客服.
  608. $del_message = [
  609. 'message_type' => 'delUser',
  610. 'data' => [
  611. 'id' => $data['user_id']
  612. ]
  613. ];
  614. Gateway::sendToClient($data['kf_client_id'], json_encode($del_message, 256));
  615. // 查询工单会话总数.
  616. $chatCount = self::$db->select('count(*) as count')->from('ws_chat_log')->where("servicelog_id=$servicelogId")->row();
  617. print_r($chatCount);
  618. // 将数据存入数据库.
  619. $updateServiceLogData = [
  620. 'status' => 2,
  621. 'evaluate_id' => isset($data['evaluate_id']) ? $data['evaluate_id'] : 0,
  622. 'evaluate_content' => isset($data['evaluate_content']) ? $data['evaluate_content'] : '',
  623. 'servicelog_close_type' => $closeBy,
  624. 'end_time' => time(),
  625. ];
  626. $updataAlarmData = [
  627. 'alarm_userSensitive' => $data['alarm_userSensitive'],
  628. 'alarm_serverSensitive' => $data['alarm_serverSensitive'],
  629. 'alarm_corresponding' => $data['alarm_corresponding'],
  630. 'alarm_cvtOvertime' => time() - $data['start_time'],
  631. 'alarm_respond' => $data['alarm_respond'],
  632. 'alarm_lineTime' => $data['start_time'] - $data['intime'],
  633. 'alarm_count' => $chatCount['count'],
  634. ];
  635. self::$db->update('ws_service_log')->cols($updateServiceLogData)->where("servicelog_id=$servicelogId")->query();
  636. self::$db->update('ws_alarm')->cols($updataAlarmData)->where("servicelog_id=$servicelogId")->query();
  637. }
  638. /**
  639. * 有人退出
  640. * @param $group
  641. */
  642. private static function userOfflineTask($group)
  643. {
  644. }
  645. /**
  646. * 有人进入执行分配
  647. * @param $client_id
  648. * @param $group
  649. * @param $uid
  650. */
  651. private static function userOnlineTask($group = 0, $uid = 0)
  652. {
  653. $allusergkarr = self::getUserListData();
  654. if (empty($allusergkarr)) {
  655. return;
  656. }
  657. $allkfgkarr = self::getWorkKfData();
  658. if (empty($allkfgkarr)) {
  659. return;
  660. }
  661. $maxset = (self::$global->systemconfig)['KFMaxServices'] ?? 5;
  662. $maxset = intval($maxset);
  663. if ($group && $uid) {
  664. // 指定用指定组 [可能存在断线重连的情况] 如果存在旧的会话,直接连线客服和用户
  665. //否则按先到后到以及客服最大服务数限制
  666. $last = self::UserHasOldTalk($uid);
  667. if ($last) {
  668. self::BeginTalk(self::getkfuid($last['kf_id']), $uid, $last['group_id'], $last['servicelog_id']);
  669. return;
  670. }
  671. }
  672. //系统定时调用时,无组,无用户
  673. foreach ($allusergkarr as $group => $gusersArr) {
  674. if (!isset($allkfgkarr[$group]) || count($allkfgkarr[$group]) <= 0) {
  675. //所属客服组无人在线
  676. continue;
  677. }
  678. $nowkfs = $allkfgkarr[$group];
  679. $count = count($nowkfs);
  680. $i = 0;
  681. foreach ($gusersArr as $user) {
  682. if ($nowkfs[$i]['task'] > $maxset) {
  683. break;
  684. }
  685. $nowkfs[$i]['task']++;
  686. self::BeginTalk($nowkfs[$i]['id'], $user['id'], $group, 0, $user);
  687. self::$redis->hdel(self::USERLIST, $user['id']);
  688. $i++;
  689. if ($i >= $count) {
  690. $i = 0;
  691. }
  692. }
  693. }
  694. return;
  695. }
  696. //开启一个会话
  697. private static function BeginTalk($kfuid, $uid, $group, $serviceid = 0, $userInfo = false)
  698. {
  699. $serviceid = intval($serviceid);
  700. if (!$userInfo) {
  701. $userInfo = json_decode(self::$redis->hget(self::USERINFOKEY, $uid), true);
  702. }
  703. $kfinfo = json_decode(self::$redis->hget(self::KFINFOKEY, $kfuid), true);
  704. if (empty($userInfo) || empty($kfinfo)) {
  705. return false;
  706. }
  707. $server = [];
  708. $armarr = [];
  709. if ($serviceid) {
  710. $server = self::$db->select('*')->from('ws_service_log')->where("servicelog_id=$serviceid ")->row();
  711. if ($server) {
  712. $armarr = self::$db->select('*')->from('ws_alarm')->where("servicelog_id=$serviceid ")->row();
  713. }
  714. }
  715. if (empty($server)) {
  716. $array = [
  717. 'user_id' => $uid,
  718. 'client_id' => $userInfo['client_id'],
  719. 'user_name' => $userInfo['name'],
  720. 'user_avatar' => $userInfo['avatar'],
  721. 'user_ip' => $userInfo['ip'],
  722. 'kf_id' => self::getkfid($kfuid),
  723. 'start_time' => time(),
  724. 'group_id' => $userInfo['group'],
  725. 'website' => $userInfo['website'],
  726. 'system' => $userInfo['system'],
  727. 'browse' => $userInfo['browse'],
  728. 'intime' => $userInfo['intime'],
  729. 'status' => 1,
  730. 'evaluate_id' => 0,
  731. 'servicelog_close_type' => 0
  732. ];
  733. $serviceid = self::$db->insert('ws_service_log')->cols($array)->query();
  734. $server = array_merge(['servicelog_id' => $serviceid], $array);
  735. $armid = self::$db->insert('ws_alarm')->cols(['servicelog_id' => $serviceid])->query();
  736. $armarr = self::$db->select('*')->from('ws_alarm')->where("alarm_id=$armid")->row();
  737. }
  738. $redisData = array_merge($server, $armarr, ['kf_client_id' => $kfinfo['client_id']]);
  739. self::$redis->hset(self::SERVICELOG, $serviceid, json_encode($redisData, 256));
  740. $kfinfo['user_info'] = array_merge($kfinfo['user_info'], [$userInfo['client_id'] => $serviceid]);
  741. $kfinfo['task'] = count($kfinfo['user_info']);
  742. self::$redis->hset(self::KFINFOKEY, $kfuid, json_encode($kfinfo, 256));
  743. $userInfo['serverid'] = $serviceid;
  744. $userInfo['kfuid'] = $kfuid;
  745. self::$redis->hset(self::USERINFOKEY, $uid, json_encode($userInfo, 256));
  746. // 通知会员发送信息绑定客服的id
  747. $noticeUser = [
  748. 'message_type' => 'connect',
  749. 'data' => [
  750. 'kf_id' => $kfuid,
  751. 'conversationId' => $serviceid,
  752. 'serverInfo' => $kfinfo,
  753. 'kf_name' => $kfinfo['job_name']
  754. ]
  755. ];
  756. self::MySendMsg($userInfo['client_id'], json_encode($noticeUser, 256));
  757. $sayHello = (self::$global->replay)['2'];
  758. if (!empty($sayHello) && 1 == $sayHello['status']) {
  759. $chat_message = [
  760. 'message_type' => 'chatMessage',
  761. 'data' => [
  762. 'id' => self::getkfuid($kfinfo['id']),
  763. 'name' => $kfinfo['name'],
  764. 'time' => date('H:i'),
  765. 'content' => $sayHello['word']
  766. ]
  767. ];
  768. self::MySendMsg($userInfo['client_id'], json_encode($chat_message, 256));
  769. unset($chat_message);
  770. }
  771. $noticeKf = [
  772. 'message_type' => 'connect',
  773. 'data' => [
  774. 'user_info' => $userInfo,
  775. 'conversationId' => $serviceid,
  776. ]
  777. ];
  778. self::MySendMsg($kfinfo['client_id'], json_encode($noticeKf, 256));
  779. unset($noticeKf);
  780. $key = date('Ymd') . 'success_in';
  781. self::$global->increment($key);
  782. return;
  783. }
  784. //用户排队数据 按组
  785. private static function getUserListData()
  786. {
  787. $alluser = self::$redis->hgetall(self::USERLIST);
  788. if (empty($alluser)) {
  789. return false;
  790. }
  791. $allusergkarr = [];
  792. foreach ($alluser as $val) {
  793. $now = json_decode($val, true);
  794. if ($now) {
  795. //用户分组后的数组
  796. $allusergkarr[$now['group']][] = $now;
  797. }
  798. }
  799. foreach ($allusergkarr as $group => $nowgroups) {
  800. usort($allusergkarr[$group], function ($a, $b) {
  801. if ($a['intime'] == $b['intime']) {
  802. return 0;
  803. }
  804. return ($a['intime'] > $b['intime']) ? 1 : -1;
  805. });
  806. }
  807. if (!$allusergkarr) {
  808. return false;
  809. }
  810. unset($alluser);
  811. return $allusergkarr;
  812. }
  813. //找到可以接工单的客服 按组
  814. private static function getWorkKfData()
  815. {
  816. $allkfs = self::$redis->hgetall(self::KFINFOKEY);
  817. if (empty($allkfs)) {
  818. return false;
  819. }
  820. $allkfgkarr = [];
  821. foreach ($allkfs as $val) {
  822. $now = json_decode($val, true);
  823. if ($now && $now['status'] == 1) {
  824. //客分组后的数组
  825. $allkfgkarr[$now['group']][] = $now;
  826. }
  827. }
  828. if (!$allkfgkarr) {
  829. return false;
  830. }
  831. //客服每组按任务数由小到大排序 任务相同时按时间先后顺序
  832. foreach ($allkfgkarr as $group => $nowgroups) {
  833. usort($allkfgkarr[$group], function ($a, $b) {
  834. if ($a['task'] == $b['task']) {
  835. if ($a['intime'] == $b['intime']) {
  836. return 0;
  837. }
  838. return ($a['intime'] > $b['intime']) ? 1 : -1;
  839. }
  840. return ($a['task'] > $b['task']) ? 1 : -1;
  841. });
  842. }
  843. unset($allkfs);
  844. return $allkfgkarr;
  845. }
  846. //找到用户是否有一条未关闭的会话
  847. private static function UserHasOldTalk($uid)
  848. {
  849. $uid = intval($uid);
  850. $start_time = time() - 86400;
  851. $ret = self::$db->select('*')->from('ws_service_log')->where("start_time>=$start_time and user_id=$uid and status!=2 ")->orderByDESC(['servicelog_id'])->row();
  852. return $ret;
  853. }
  854. //今天排序累加
  855. private static function todayqueuelength()
  856. {
  857. $dtype = 'user.queue.day.length';
  858. $today = date("Y-m-d");
  859. $sret = self::$db->select('*')->from('ws_countmidtable')->where('dtype=:dtype and mdate=:mdate')->bindValues(array('dtype' => $dtype, 'mdate' => $today))->row();
  860. if ($sret) {
  861. self::$db->update('ws_countmidtable')->cols(array('dcontent' => intval($sret['dcontent']) + 1))->where('id=' . $sret['id'])->query();
  862. } else {
  863. self::$db->insert('ws_countmidtable')->cols(array(
  864. 'dtype' => $dtype,
  865. 'mdate' => $today,
  866. 'datatype' => 1,
  867. 'dcontent' => 1))->query();
  868. }
  869. }
  870. //客服工单转单
  871. private static function servicetrutoother($type, $owen, $otherkfid, $serverid, $clientuid)
  872. {
  873. $owen = intval(substr($owen, 2));
  874. $otherkfid = intval(substr($otherkfid, 2));
  875. self::$db->insert('ws_serviceturn_log')->cols(array(
  876. 'stype' => $type,
  877. 'uid' => $owen,
  878. 'tuid' => $otherkfid,
  879. 'serverid' => $serverid,
  880. 'guestuid' => $clientuid
  881. ))->query();
  882. }
  883. /**
  884. * 给客服分配会员【均分策略】
  885. * @param $kfList
  886. * @param $userList
  887. * @param $group
  888. * @param $total
  889. */
  890. private static function assignmentTask($kfList, $userList, $group, $total, $uid = 0)
  891. {
  892. }
  893. /**
  894. * 获取最大的服务人数
  895. * @return int
  896. */
  897. private static function getMaxServiceNum()
  898. {
  899. $maxNumber = self::$db->query('select `max_service` from `ws_kf_config` where `id` = 1');
  900. if (!empty($maxNumber)) {
  901. $maxNumber = 5;
  902. } else {
  903. $maxNumber = $maxNumber['0']['max_service'];
  904. }
  905. return $maxNumber;
  906. }
  907. /**
  908. * 将内存中的数据写入统计表
  909. * @param int $flag
  910. */
  911. private static function writeLog($flag = 1)
  912. {
  913. // 上午 8点 到 22 点开始统计
  914. if (date('H') < 8 || date('H') > 22) {
  915. return;
  916. }
  917. $inQueue_1 = self::$redis->hget(self::USERLIST);
  918. $inQueue = empty($inQueue_1) ? 0 : count($inQueue_1);
  919. $allkf = self::$redis->hgetall(self::KFINFOKEY);
  920. $nowTalking = $onlineKf = 0;
  921. if (!empty($allkf)) {
  922. foreach ($allkf as $kfuid => $val) {
  923. $tmp = json_decode($val, true);
  924. $onlineKf++;
  925. $nowTalking += count($tmp['user_info']);
  926. }
  927. }
  928. $key = date('Ymd') . 'total_in';
  929. $key2 = date('Ymd') . 'success_in';
  930. $param = [
  931. 'is_talking' => $nowTalking,
  932. 'in_queue' => $inQueue,
  933. 'online_kf' => $onlineKf,
  934. 'success_in' => self::$global->$key2,
  935. 'total_in' => self::$global->$key,
  936. 'now_date' => date('Y-m-d')
  937. ];
  938. self::$db->update('ws_now_data')->cols($param)->where('id=1')->query();
  939. if (2 == $flag) {
  940. $param = [
  941. 'is_talking' => $nowTalking,
  942. 'in_queue' => $inQueue,
  943. 'online_kf' => $onlineKf,
  944. 'success_in' => self::$global->$key2,
  945. 'total_in' => self::$global->$key,
  946. 'add_date' => date('Y-m-d'),
  947. 'add_hour' => date('H'),
  948. 'add_minute' => date('i'),
  949. ];
  950. self::$db->insert('ws_service_data')->cols($param)->query();
  951. }
  952. unset($allkf, $nowTalking, $inQueue, $onlineKf, $key, $key2, $param);
  953. }
  954. /**
  955. * 机器人问答
  956. * @param $client_id 服务ID
  957. * @param $message 数据
  958. */
  959. private static function toRobot($client_id, $message)
  960. {
  961. $groups_id = $message['data']['groups_id'];
  962. $robot_name = $message['data']['robot_name'];
  963. $robotgroups_id = $message['data']['robotgroups_id'];
  964. // 查询问题.
  965. $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 . "'");
  966. $chat_message = [
  967. 'message_type' => 'robotMessage',
  968. //'message_type' => 'chatMessage',
  969. 'data' => [
  970. 'name' => '智能助手',
  971. 'time' => date('H:i'),
  972. 'content' => $getRobot ? $getRobot[0]['robot_content'] : 'error',
  973. ]
  974. ];
  975. Gateway::sendToClient($client_id, json_encode($chat_message, 256));
  976. }
  977. /**
  978. * 评价
  979. * @param $client_id 服务ID
  980. * @param $message 数据
  981. */
  982. private static function evaluate($client_id, $message)
  983. {
  984. // 修改数据库.
  985. $evaluate_id = $message['data']['evaluate_id'];
  986. $result = self::$db->query("UPDATE `ws_service_log` SET `evaluate_id` = '" . $evaluate_id . "' WHERE `client_id`='" . $client_id . "'");
  987. if ($result) {
  988. $chat_message = [
  989. 'message_type' => 'evaluate',
  990. 'data' => [
  991. 'status' => 1,
  992. 'time' => date('H:i'),
  993. ]
  994. ];
  995. } else {
  996. $chat_message = [
  997. 'message_type' => 'evaluate',
  998. 'data' => [
  999. 'status' => 2,
  1000. 'time' => date('H:i'),
  1001. ]
  1002. ];
  1003. }
  1004. Gateway::sendToClient($client_id, json_encode($chat_message, 256));
  1005. }
  1006. //获取系统配置
  1007. private static function upsystemconfig()
  1008. {
  1009. $systemConfigData = self::$db->query("SELECT * FROM `ws_systemconfig`");
  1010. $arr = [];
  1011. if ($systemConfigData) {
  1012. foreach ($systemConfigData as $item) {
  1013. $arr[$item['systemconfig_enName']] = $item;
  1014. }
  1015. self::$global->systemconfig = $arr;
  1016. }
  1017. $group = self::$db->query("SELECT * FROM `ws_groups`");
  1018. $arr = [];
  1019. if ($group) {
  1020. foreach ($group as $val) {
  1021. $arr[$val['id']] = $val['name'];
  1022. }
  1023. self::$global->groupmap = $arr;
  1024. }
  1025. $arr = [];
  1026. $replay = self::$db->query('select * from `ws_reply`');
  1027. if ($replay) {
  1028. foreach ($replay as $val) {
  1029. $arr[$val['id']] = $val;
  1030. }
  1031. self::$global->replay = $arr;
  1032. }
  1033. }
  1034. /**
  1035. * 超时
  1036. * @param $client_id 服务ID
  1037. * @param $message 数据
  1038. */
  1039. private static function overTime()
  1040. {
  1041. // 查询对话时效设置.
  1042. $systemConfigData = self::$db->query("SELECT `systemconfig_data`,`systemconfig_enName`,`systemconfig_content` FROM `ws_systemconfig`");
  1043. foreach ($systemConfigData as $k => $v) {
  1044. if ($v['systemconfig_enName'] == 'overtime') {
  1045. $configOvertime = $v;
  1046. } elseif ($v['systemconfig_enName'] == 'unoperated') {
  1047. $configUnoperated = $v;
  1048. }
  1049. }
  1050. // 查询未断开的工单.
  1051. $serviceLog = self::$redis->hGetall('SERVICELOG');
  1052. $setOvertime = strtotime('-' . ($configOvertime['systemconfig_data'] - 60) . ' second');
  1053. $overtime = strtotime('-' . ($configOvertime['systemconfig_data']) . ' second');
  1054. $setUnoperated = strtotime('-' . ($configUnoperated['systemconfig_data'] - 60) . ' second');
  1055. $unoperated = strtotime('-' . ($configUnoperated['systemconfig_data']) . ' second');
  1056. foreach ($serviceLog as $k => $v) {
  1057. // 无效会话关闭.如果没有说一句话.
  1058. $data = json_decode($v, true);
  1059. if (!isset($data['userLastTime'])) {
  1060. if ($data['start_time'] <= $unoperated) {
  1061. self::serverClose($k, 1);
  1062. // 如果小于设定时间前一分钟则给出提示.
  1063. } elseif ($data['start_time'] <= $setUnoperated) {
  1064. $chat_message = [
  1065. 'message_type' => 'overtime',
  1066. 'data' => [
  1067. 'content' => self::$global->unoperated['systemconfig_content'],
  1068. ]
  1069. ];
  1070. Gateway::sendToClient($data['client_id'], json_encode($chat_message, 256));
  1071. }
  1072. // 双方静默超时.
  1073. } elseif ($data['userLastTime'] <= $overtime && $data['serverLastTime'] <= $overtime) {
  1074. self::serverClose($k, 2);
  1075. // 如果小于设定时间前一分钟则给出提示.
  1076. } elseif ($data['userLastTime'] <= $setOvertime && $data['serverLastTime'] <= $setOvertime) {
  1077. $chat_message = [
  1078. 'message_type' => 'overtime',
  1079. 'data' => [
  1080. 'content' => self::$global->overtime['systemconfig_content'],
  1081. ]
  1082. ];
  1083. Gateway::sendToClient($data['client_id'], json_encode($chat_message, 256));
  1084. }
  1085. }
  1086. }
  1087. /**
  1088. * 系统监控
  1089. * @param $message 数据
  1090. */
  1091. private static function systemMonitoring($adminList)
  1092. {
  1093. // 查询正进行的工单.
  1094. $serviceLog = self::$redis->hGetall('SERVICELOG');
  1095. // 查询系统设置表.
  1096. $systemconfig = self::$db->query("SELECT `systemconfig_data`,`systemconfig_enName` FROM `ws_systemconfig` WHERE `systemconfig_enName`='verifyReturnTime' or `systemconfig_enName`='verifyAllTime'");
  1097. // 质检会话响应时长.
  1098. $returnTimeKey = array_search('verifyReturnTime', array_column($systemconfig, 'systemconfig_enName'));
  1099. $verifyReturnTime = $systemconfig[$returnTimeKey]['systemconfig_data'];
  1100. // 质检会话时长.
  1101. $allTimeKey = array_search('verifyAllTime', array_column($systemconfig, 'systemconfig_enName'));
  1102. $verifyAllTime = $systemconfig[$allTimeKey]['systemconfig_data'];
  1103. $evaluateCount = 0; // 差评总次数.
  1104. $overtimeNumber = 0; // 会话超时总次数.
  1105. $overtimeTime = []; // 每次会话超时时间.
  1106. $userSensitive = 0; // 用户敏感词报警总次数.
  1107. $serverSensitive = 0; // 客服敏感词报警总次数.
  1108. $csdNumber = 0; // 响应超时总次数.
  1109. $csdTime = []; // 每次响应超时时间.
  1110. foreach ($serviceLog as $k => $v) {
  1111. $data = json_decode($v, true);
  1112. // 工单报警次数.
  1113. $allCount = 0;
  1114. if ($data['evaluate_id'] == 3) {
  1115. $evaluateCount++; // 差评次数.
  1116. $allCount++; // 工单报警次数.
  1117. }
  1118. // 会话超时.
  1119. $duration = time() - $data['start_time'];
  1120. if ($duration > $verifyAllTime) {
  1121. $overtimeNumber++; // 会话超时总次数.
  1122. $allCount++; // 工单报警次数.
  1123. $overtimeTime[] = $duration; // 响应超时时间.
  1124. }
  1125. // 敏感词报警.
  1126. $userSensitive += $data['alarm_userSensitive'];
  1127. $allCount += $data['alarm_userSensitive'];
  1128. $serverSensitive += $data['alarm_serverSensitive'];
  1129. $allCount += $data['alarm_serverSensitive'];
  1130. // 响应超时.
  1131. if ($data['alarm_corresponding'] > $verifyReturnTime) {
  1132. $csdTime[] = $data['alarm_corresponding']; // 响应超时时间.
  1133. $csdNumber++; // 响应超时总次数.
  1134. $allCount++; // 工单报警次数.
  1135. }
  1136. $serviceLog[$k] = $data;
  1137. $serviceLog[$k]['allCount'] = $allCount; // 工单报警次数.
  1138. }
  1139. self::DebugOut([$serviceLog, $csdTime, $verifyReturnTime], 'systemMonitoring');
  1140. // 查询对话时效设置.
  1141. foreach ($adminList as $v) {
  1142. $chat_message = [
  1143. 'message_type' => 'monitor',
  1144. 'data' => [
  1145. 'cvtList' => $serviceLog,
  1146. 'userSensitive' => $userSensitive,
  1147. 'serverSensitive' => $serverSensitive,
  1148. 'csdNumber' => $csdNumber,
  1149. 'csdTime' => $csdTime,
  1150. 'overtimeNumber' => $overtimeNumber,
  1151. 'overtimeTime' => $overtimeTime,
  1152. 'evaluateCount' => $evaluateCount,
  1153. ]
  1154. ];
  1155. Gateway::sendToClient($v, json_encode($chat_message, 256));
  1156. }
  1157. }
  1158. //客户工单内部组转接
  1159. public static function changeOtherhKeFu($client_id, $smessage)
  1160. {
  1161. $message = $smessage['data'];
  1162. $groupid = isset($message['fromgroup']) ? intval($message['fromgroup']) : 0;
  1163. $groupidto = isset($message['togroup']) ? intval($message['togroup']) : 0;
  1164. $toukfid = isset($message['toukfuid']) ? $message['toukfuid'] : 0;
  1165. $fromkfuid = isset($message['fromkfuid']) ? $message['fromkfuid'] : 0;
  1166. $uid = isset($message['uid']) ? intval($message['uid']) : 0;
  1167. $word = isset($message['word']) ? $message['word'] : '';
  1168. if (empty($groupid) || empty($groupidto) || empty($toukfid) || empty($fromkfuid) || empty($uid) || ($toukfid == $fromkfuid)) {
  1169. self::DebugOut('changeOtherhKeFu exit1...');
  1170. return false;
  1171. }
  1172. if (!Gateway::isUidOnline($toukfid) || !Gateway::isUidOnline($uid)) {
  1173. self::DebugOut('changeOtherhKeFu exit2...');
  1174. return false;
  1175. }
  1176. $kf_info_from = json_decode(self::$redis->hget(self::KFINFOKEY, $fromkfuid), true);
  1177. $kf_info_to = json_decode(self::$redis->hget(self::KFINFOKEY, $toukfid), true);
  1178. $user_info = json_decode(self::$redis->hget(self::USERINFOKEY, $uid), true);
  1179. $serviceid = intval($user_info['serverid']);
  1180. if (empty($kf_info_from) || empty($kf_info_to) || empty($user_info) || empty($serviceid)) {
  1181. self::DebugOut('changeOtherhKeFu exit23...');
  1182. return false;
  1183. }
  1184. if ($kf_info_to['status'] != 1) {
  1185. self::DebugOut('changeOtherhKeFu exit4...');
  1186. return false;
  1187. }
  1188. /////////取消原有会话,开启新会话
  1189. $oldlog = self::$db->select('*')->from('ws_service_log')->where('servicelog_id=:servicelog_id ')->bindValues(['servicelog_id' => $serviceid])->orderByDESC(['servicelog_id'])->row();
  1190. if (!$oldlog) {
  1191. self::DebugOut('changeOtherhKeFu exit5...');
  1192. return false;
  1193. }
  1194. self::$db->update('ws_service_log')->cols(['servicelog_close_type' => 5, 'status' => 2, 'end_time' => time()])->where("servicelog_id=$serviceid")->query();
  1195. self::$redis->hdel(self::SERVICELOG, $serviceid);
  1196. unset($oldlog['servicelog_id']);
  1197. $oldlog = array_merge($oldlog, ['kf_id' => self::getkfid($toukfid), 'start_time' => time(), 'end_time' => 0, 'status' => 1, 'evaluate_id' => 0]);
  1198. $new_id = self::$db->insert('ws_service_log')->cols($oldlog)->query();
  1199. if (!$new_id) {
  1200. self::DebugOut('changeOtherhKeFu exit6...');
  1201. return false;
  1202. }
  1203. ///更新redis数据
  1204. $kf_info_from['user_info'] = self::ArrayDataopt($kf_info_from['user_info'], $user_info['client_id'], 0);
  1205. $kf_info_from['task'] = count($kf_info_from['user_info']);
  1206. self::$redis->hset(self::KFINFOKEY, $fromkfuid, json_encode($kf_info_from, 256));
  1207. $kf_info_to['user_info'] = self::ArrayDataopt($kf_info_to['user_info'], $user_info['client_id'], 1, $new_id);
  1208. $kf_info_to['task'] = count($kf_info_to['user_info']);
  1209. self::$redis->hset(self::KFINFOKEY, $toukfid, json_encode($kf_info_to, 256));
  1210. $user_info['kfuid'] = $toukfid;
  1211. $user_info['serverid'] = $new_id;
  1212. self::$redis->hset(self::USERINFOKEY, $uid, json_encode($user_info, 256));
  1213. unset($kf_info_to['user_info']);
  1214. ///通知消息发送--------------
  1215. // 通知会员发送信息绑定客服的id
  1216. $noticeUser = [
  1217. 'message_type' => 'connect',
  1218. 'data' => [
  1219. 'kf_id' => $toukfid,
  1220. 'conversationId' => $new_id,
  1221. 'kf_name' => $kf_info_to['name'],
  1222. 'serverInfo' => $kf_info_to,
  1223. ]
  1224. ];
  1225. Gateway::sendToClient($user_info['client_id'], json_encode($noticeUser, 256));
  1226. unset($noticeUser);
  1227. // 通知客服端绑定会员的信息
  1228. $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']];
  1229. $noticeKf = [
  1230. 'message_type' => 'connect',
  1231. 'data' => [
  1232. 'user_info' => $userinfoarr,
  1233. 'conversationId' => $new_id,
  1234. ]
  1235. ];
  1236. Gateway::sendToClient($kf_info_to['client_id'], json_encode($noticeKf, 256));
  1237. unset($noticeKf);
  1238. self::servicetrutoother('OUT', $fromkfuid, $toukfid, $serviceid, $uid);
  1239. self::servicetrutoother('IN', $toukfid, $fromkfuid, $new_id, $uid);
  1240. //回转接人,转接成功
  1241. Gateway::sendToCurrentClient(json_encode(['message_type' => 'trunconnect', 'data' => ['status' => 1]], 256));
  1242. self::DebugOut('changekf 转换成功!');
  1243. return;
  1244. }
  1245. //客服在线状态写组
  1246. private static function writeLogKfStatus($kf, $status, $flag = 1)
  1247. {
  1248. if ($flag == 1) {
  1249. $status = intval($status);
  1250. if ($status == 0) {
  1251. self::$db->delete('ws_kfonline')->where("uid='$kf'")->query();
  1252. } else {
  1253. $now = date('Y-m-d H:i;s');
  1254. $ip = isset($_SESSION['remotip']) ? $_SESSION['remotip'] : '';
  1255. $sql = "insert into ws_kfonline(uid,status,uptime,ip) values('$kf',$status,'$now','$ip') ON DUPLICATE KEY UPDATE status=$status,uptime='$now' ";
  1256. self::$db->query($sql);
  1257. }
  1258. } else {
  1259. self::$db->query("delete from ws_kfonline ");
  1260. }
  1261. }
  1262. public static function resetServiceLog($kfid = 0)
  1263. {
  1264. $t = time() - 24 * 3600 * 7;
  1265. $now = time();
  1266. if ($kfid) {
  1267. if ((substr($kfid, 0, 2) == 'KF')) {
  1268. $kfid = intval(substr($kfid, 2));
  1269. }
  1270. $kfid = intval($kfid);
  1271. self::$db->query("update ws_service_log set status=2,end_time=$now where start_time>=$t and kf_id=$kfid and status!=2");
  1272. self::$redis->hdel(self::KFINFOKEY, 'KF' . $kfid);
  1273. } else {
  1274. self::$redis->del(self::KFINFOKEY);
  1275. self::$redis->del(self::USERLIST);
  1276. self::$redis->del(self::USERINFOKEY);
  1277. self::$db->query("update ws_service_log set status=2,end_time=$now where start_time>=$t and status!=2");
  1278. }
  1279. }
  1280. public static function onWorkerStop($businessWorker)
  1281. {
  1282. if ($businessWorker->worker_id == 1) {
  1283. self::resetServiceLog();
  1284. }
  1285. }
  1286. //用户下线通知
  1287. private static function userCloseNotice($client_id, $cuid, $group)
  1288. {
  1289. }
  1290. //踢掉同一用户的旧用户
  1291. private static function tickOlduser($uid)
  1292. {
  1293. }
  1294. private static function DebugOut($msg, $title = '', $type = 'info')
  1295. {
  1296. $config = self::$global->systemconfig;
  1297. if (!isset($config['isdebug']) || empty($config['isdebug']['systemconfig_data'])) {
  1298. return;
  1299. }
  1300. if (!is_string($msg)) {
  1301. $msg = json_encode([$msg], 256);
  1302. }
  1303. $msg = date("Y-m-d H:i:s") . ' - ' . $type . ' - ' . $title . ' - ' . $msg . "\n";
  1304. echo $msg;
  1305. }
  1306. //定时器相关
  1307. private static function TimerThing($worker)
  1308. {
  1309. // 当天的累积接入值
  1310. $key = date('Ymd') . 'total_in';
  1311. if (is_null(self::$global->$key)) {
  1312. self::$global->$key = 0;
  1313. $oldKey = date('Ymd', strtotime('-1 day')); // 删除前一天的统计值
  1314. unset(self::$global->$oldKey);
  1315. unset($oldKey, $key);
  1316. }
  1317. // 成功接入值
  1318. $key = date('Ymd') . 'success_in';
  1319. if (is_null(self::$global->$key)) {
  1320. self::$global->$key = 0;
  1321. $oldKey = date('Ymd', strtotime('-1 day')); // 删除前一天的统计值
  1322. unset(self::$global->$oldKey);
  1323. unset($oldKey, $key);
  1324. }
  1325. // 定时统计数据
  1326. if (0 == $worker->id) {
  1327. self::writeLogKfStatus(0, 0, 0);
  1328. //每5秒更新进行一次人员分配
  1329. Timer::add(5, function () {
  1330. self::userOnlineTask();
  1331. });
  1332. //每1分钟报告一次本组排列人员(如果有人排队)
  1333. Timer::add(60, function () {
  1334. self::lineup();
  1335. });
  1336. // 1分钟统计一次实时数据
  1337. Timer::add(60 * 1, function () {
  1338. self::writeLog(1);
  1339. });
  1340. // 40分钟写一次当前日期点数的log数据
  1341. Timer::add(60 * 40, function () {
  1342. self::writeLog(2);
  1343. });
  1344. //初始化.....
  1345. self::upsystemconfig();
  1346. //每3分钟更新一次系统配置文件
  1347. Timer::add(60 * 3, function () {
  1348. self::upsystemconfig();
  1349. });
  1350. // 删除前一天的统计值
  1351. Timer::add(60 * 60 * 12, function () {
  1352. $oldKey = date('Ymd', strtotime('-1 day'));
  1353. unset(self::$global->$oldKey);
  1354. });
  1355. self::resetServiceLog();
  1356. }
  1357. }
  1358. //调试使用
  1359. public static function mydebug($client_id, $message)
  1360. {
  1361. }
  1362. public static function MySendMsg($clientId, $msg)
  1363. {
  1364. Gateway::sendToClient($clientId, $msg);
  1365. }
  1366. //得到客服的UID字符值
  1367. public static function getkfuid($uid)
  1368. {
  1369. if (substr($uid, 0, 2) == 'KF') {
  1370. return $uid;
  1371. } else {
  1372. return 'KF' . intval($uid);
  1373. }
  1374. }
  1375. //得到客服的ID整数值
  1376. public static function getkfid($id)
  1377. {
  1378. if (strtolower(substr($id, 0, 2)) == 'kf') {
  1379. return intval(substr($id, 2));
  1380. }
  1381. return intval($id);
  1382. }
  1383. //从数组中获取参数
  1384. public static function getPars($array, $key, $default = '')
  1385. {
  1386. if (isset($array[$key])) {
  1387. return $array[$key];
  1388. }
  1389. return $default;
  1390. }
  1391. //获取在线客服信息
  1392. public static function getOnlineKfData($group = 0, $status = 0)
  1393. {
  1394. $all = self::$redis->hgetall(self::KFINFOKEY);
  1395. if (!$all) {
  1396. return false;
  1397. }
  1398. $return = [];
  1399. foreach ($all as $val) {
  1400. $now = json_decode($val, true);
  1401. if ($group) {
  1402. if ($now['group'] != $group) {
  1403. continue;
  1404. }
  1405. }
  1406. if ($status) {
  1407. if ($now['status'] != $status) {
  1408. continue;
  1409. }
  1410. }
  1411. $return[$now['id']] = $now;
  1412. }
  1413. return $return;
  1414. }
  1415. //找到在排队的用户按时间先后顺序
  1416. public static function getUselistData($group)
  1417. {
  1418. $all = self::$redis->hgetall(self::USERLIST);
  1419. if (!$all) {
  1420. return false;
  1421. }
  1422. $return = [];
  1423. foreach ($all as $val) {
  1424. $now = json_decode($val, true);
  1425. if ($group == $now['group']) {
  1426. $return[] = $now;
  1427. }
  1428. }
  1429. usort($return, function ($a, $b) {
  1430. if ($a['intime'] == $b['intime']) {
  1431. return 0;
  1432. }
  1433. return $a['intime'] > $b['intime'] ? 1 : -1;
  1434. });
  1435. return $return;
  1436. }
  1437. //对客服的用户user_info数组进行加减操作 $clientid用户连接号 opt=1添加 0删除 $serverid服务工单号
  1438. public static function ArrayDataopt($array, $clientid, $opt, $serverid = 0)
  1439. {
  1440. if (!is_array($array)) {
  1441. return [];
  1442. }
  1443. if ($opt == 0) {
  1444. if (isset($array[$clientid])) {
  1445. unset($array[$clientid]);
  1446. }
  1447. return $array;
  1448. } else {
  1449. $array[$clientid] = $serverid;
  1450. return $array;
  1451. }
  1452. }
  1453. }