Events.php 59 KB

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