Events.php 58 KB

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