Events.php 72 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825
  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. /**
  35. * 进程启动后初始化数据库连接
  36. */
  37. public static function onWorkerStart($worker)
  38. {
  39. if (empty(self::$db)) {
  40. self::$db = new \Workerman\MySQL\Connection('192.168.2.200', '3306', 'vali', '1234', 'customer_service');
  41. }
  42. if (empty(self::$global)) {
  43. self::$global = new \GlobalData\Client('127.0.0.1:2207');
  44. // 客服列表
  45. if (is_null(self::$global->kfList)) {
  46. self::$global->kfList = [];
  47. }
  48. // 会员列表[动态的,这里面只是目前未被分配的会员信息]
  49. if (is_null(self::$global->userList)) {
  50. self::$global->userList = [];
  51. }
  52. // 会员以 uid 为key的信息简表,只有在用户退出的时候,才去执行修改
  53. if (is_null(self::$global->uidSimpleList)) {
  54. self::$global->uidSimpleList = [];
  55. }
  56. // 当天的累积接入值
  57. $key = date('Ymd') . 'total_in';
  58. if (is_null(self::$global->$key)) {
  59. self::$global->$key = 0;
  60. $oldKey = date('Ymd', strtotime('-1 day')); // 删除前一天的统计值
  61. unset(self::$global->$oldKey);
  62. unset($oldKey, $key);
  63. }
  64. // 成功接入值
  65. $key = date('Ymd') . 'success_in';
  66. if (is_null(self::$global->$key)) {
  67. self::$global->$key = 0;
  68. $oldKey = date('Ymd', strtotime('-1 day')); // 删除前一天的统计值
  69. unset(self::$global->$oldKey);
  70. unset($oldKey, $key);
  71. }
  72. }
  73. // 定时统计数据
  74. if (0 === $worker->id) {
  75. self::writeLogKfStatus(0, 0, 0);
  76. // 1分钟统计一次实时数据
  77. Timer::add(60 * 1, function () {
  78. self::writeLog(1);
  79. });
  80. // 40分钟写一次当前日期点数的log数据
  81. Timer::add(60 * 40, function () {
  82. self::writeLog(2);
  83. });
  84. }
  85. if (1 == $worker->id) {
  86. //每1分钟发一次本组排队数
  87. Timer::add(60 * 1, function () {
  88. self::lineup();
  89. });
  90. //初始化.....
  91. self::upsystemconfig();
  92. //每5分钟更新一次系统配置文件
  93. Timer::add(60 * 10, function () {
  94. self::upsystemconfig();
  95. });
  96. }
  97. if (2 == $worker->id) {
  98. // 检查对话时效给出.
  99. Timer::add(6, function () {
  100. self::overTime();
  101. });
  102. }
  103. if (3 == $worker->id) {
  104. // 实时监控.
  105. Timer::add(60, function () {
  106. $adminList = self::$global->adminList ?? [];
  107. self::systemMonitoring($adminList);
  108. });
  109. }
  110. }
  111. /**
  112. * 每分钟定时向客服发送一次排队情况
  113. */
  114. public static function lineup()
  115. {
  116. $userlist = self::$global->userList;
  117. $kflist = self::$global->kfList;
  118. if (empty($userlist) || empty($kflist)) {
  119. return;
  120. }
  121. $return = [];
  122. foreach ($userlist as $val) {
  123. $return[$val['group']] = isset($return[$val['group']]) ? $return[$val['group']] + 1 : 1;
  124. }
  125. $krgroupclientid = [];
  126. foreach ($kflist as $gid => $sval) {
  127. foreach ($sval as $tval) {
  128. $krgroupclientid[$gid][] = $tval['client_id'];
  129. }
  130. }
  131. foreach ($return as $fgroup => $fval) {
  132. foreach ($krgroupclientid as $sikey => $sival) {
  133. if ($fgroup == $sikey) {
  134. Gateway::sendToClient($sival, json_encode(['type' => 'lineupCount', $fval], 256));
  135. }
  136. }
  137. }
  138. return;
  139. }
  140. /**
  141. * 当客户端连接时触发
  142. * 如果业务不需此回调可以删除onConnect
  143. *
  144. * @param int $client_id 连接id
  145. */
  146. public static function onConnect($client_id)
  147. {
  148. // 检测是否开启自动应答
  149. $sayHello = self::$db->query('select `word`,`status` from `ws_reply` where `id` = 1');
  150. if (!empty($sayHello) && 1 == $sayHello['0']['status']) {
  151. $hello = [
  152. 'message_type' => 'helloMessage',
  153. 'data' => [
  154. 'name' => '智能助手',
  155. 'time' => date('H:i'),
  156. 'content' => $sayHello['0']['word']
  157. ]
  158. ];
  159. Gateway::sendToClient($client_id, json_encode($hello, 256));
  160. unset($hello);
  161. }
  162. unset($sayHello);
  163. // 检测是否开启广告
  164. $advertisement = self::$db->query('select * from `ws_advertisement` where `advertisement_status` = 1');
  165. if (!empty($advertisement)) {
  166. $chat_message = [
  167. 'message_type' => 'advertisement',
  168. 'data' => $advertisement
  169. ];
  170. Gateway::sendToClient($client_id, json_encode($chat_message, 256));
  171. unset($chat_message);
  172. }
  173. unset($advertisement);
  174. }
  175. /**
  176. * 当客户端发来消息时触发
  177. * @param int $client_id 连接id
  178. * @param mixed $message 具体消息
  179. */
  180. public static function onMessage($client_id, $message)
  181. {
  182. if ($message == '{"type":"ping"}' || $message == '{"type":"pong"}') {
  183. //Gateway::sendToCurrentClient('{"type":"pong"}');
  184. return;
  185. } else {
  186. // echo "onMessage: " . $message . "\r\n";
  187. // print_r([self::$global->kfList, self::$global->userList, self::$global->uidSimpleList, self::$global->userToKf]);
  188. }
  189. $message = json_decode($message, true);
  190. if (isset($message['type'])) {
  191. switch ($message['type']) {
  192. // 管理员初始化
  193. case 'adminInit':
  194. $token = $message['token'];
  195. self::adminInit($client_id, $token);
  196. break;
  197. // 客服初始化
  198. case 'init':
  199. $data = $message['data'];
  200. self::Kfinit($client_id, $data);
  201. break;
  202. // 顾客初始化
  203. case 'userInit';
  204. $data = $message['data'];
  205. self::userInitEnt($client_id, $data);
  206. break;
  207. //在线客服信息
  208. case 'getkfonlines':
  209. Gateway::sendToCurrentClient(json_encode(self::getkfonlines(), 256));
  210. break;
  211. case 'chatMessage':
  212. $client = Gateway::getClientIdByUid($message['data']['to_id']);
  213. if (!empty($client)) {
  214. $chat_message = [
  215. 'message_type' => 'chatMessage',
  216. 'data' => [
  217. 'name' => $message['data']['from_name'],
  218. 'id' => $message['data']['from_id'],
  219. 'time' => date('H:i'),
  220. 'content' => $message['data']['content'],
  221. ]
  222. ];
  223. Gateway::sendToClient($client['0'], json_encode($chat_message));
  224. unset($chat_message);
  225. // 聊天信息入库
  226. $serviceLog = [
  227. 'from_id' => $message['data']['from_id'],
  228. 'from_name' => $message['data']['from_name'],
  229. 'to_id' => $message['data']['to_id'],
  230. 'to_name' => $message['data']['to_name'],
  231. 'content' => $message['data']['content'],
  232. 'servicelog_id' => $message['data']['conversationId'],
  233. 'time_line' => time()
  234. ];
  235. self::$db->insert('ws_chat_log')->cols($serviceLog)->query();
  236. if ($message['data']['sensitiveNumber']) {
  237. }
  238. self::$db->query("update `ws_alarm` set `alarm_corresponding` = '$corresponding',alarm_respond=2 where `servicelog_id`= '$servicelog_id'");
  239. unset($serviceLog);
  240. }
  241. if (isset($message['data']['isFirst']) && $message['data']['isFirst']) {
  242. $servicelog_id = $message['data']['conversationId'];
  243. $serviceLog = self::$db->query("select `start_time` from `ws_service_log` where `servicelog_id`= '$servicelog_id'");
  244. $corresponding = time() - $serviceLog[0]['start_time'];
  245. self::$db->query("update `ws_alarm` set `alarm_corresponding` = '$corresponding',alarm_respond=2 where `servicelog_id`= '$servicelog_id'");
  246. }
  247. break;
  248. // 转接
  249. case 'changeGroup':
  250. // 通知客户端转接中
  251. $simpleList = self::$global->uidSimpleList;
  252. if (!isset($simpleList[$message['uid']])) { // 客户已经退出
  253. return;
  254. }
  255. $userClient = $simpleList[$message['uid']]['0'];
  256. $userGroup = $simpleList[$message['uid']]['1']; // 会员原来的分组也是客服的分组
  257. $reLink = [
  258. 'message_type' => 'relinkMessage'
  259. ];
  260. Gateway::sendToClient($userClient, json_encode($reLink, 256));
  261. unset($reLink);
  262. // 记录该客服与该会员的服务结束
  263. $servicelog_id = $message['data']['conversationId'];
  264. self::$db->query("update `ws_service_log` set `end_time` = " . time() . " , `status` = '2' where `servicelog_id`= '" . $servicelog_id . "'");
  265. // 修改会话时长
  266. $serviceLog = self::$db->query("select `start_time`,`intime` from `ws_service_log` where `servicelog_id`= '$servicelog_id'");
  267. $logCount = self::$db->query("select count(*) as `count` from `ws_chat_log` where `servicelog_id`= '$servicelog_id'");
  268. $alarmCount = $logCount[0]['count'];
  269. $cvtOvertime = time() - $serviceLog[0]['start_time'];
  270. $alarmLineTime = $serviceLog[0]['start_time'] - $serviceLog[0]['intime'];
  271. self::$db->query("update `ws_alarm` set `alarm_cvtOvertime` = '$cvtOvertime',`alarm_lineTime` = '$alarmLineTime',`alarm_count` = '$alarmCount'
  272. where `servicelog_id`= '$servicelog_id'");
  273. // 从当前客服的服务表中删除这个会员
  274. $old = $kfList = self::$global->kfList;
  275. if (!isset($kfList[$userGroup])) {
  276. $waitMsg = '暂时没有相关客服上班,请稍后再咨询。';
  277. // 逐一通知
  278. foreach (self::$global->userList as $vo) {
  279. $waitMessage = [
  280. 'message_type' => 'wait',
  281. 'data' => [
  282. 'content' => $waitMsg,
  283. ]
  284. ];
  285. Gateway::sendToClient($userClient, json_encode($waitMessage, 256));
  286. unset($waitMessage);
  287. }
  288. return;
  289. }
  290. $myList = $kfList[$userGroup]; // 该客服分组数组
  291. foreach ($myList as $key => $vo) {
  292. if (in_array($userClient, $vo['user_info'])) {
  293. // 维护现在的该客服的服务信息
  294. $kfList[$userGroup][$key]['task'] -= 1; // 当前服务的人数 -1
  295. foreach ($vo['user_info'] as $k => $v) {
  296. if ($userClient == $v) {
  297. unset($kfList[$userGroup][$key]['user_info'][$k]);
  298. break;
  299. }
  300. }
  301. break;
  302. }
  303. }
  304. while (!self::$global->cas('kfList', $old, $kfList)) {
  305. }; // 刷新内存中客服的服务列表
  306. unset($old, $kfList, $myList);
  307. // 将会员加入队列中
  308. $userList = self::$global->userList;
  309. do {
  310. $NewUserList = $userList;
  311. $NewUserList[$message['uid']] = [
  312. 'id' => $message['uid'],
  313. 'name' => $message['name'],
  314. 'avatar' => $message['avatar'],
  315. 'ip' => $message['ip'],
  316. 'group' => $message['group'], // 指定要链接的分组
  317. 'client_id' => $userClient
  318. ];
  319. } while (!self::$global->cas('userList', $userList, $NewUserList));
  320. unset($NewUserList, $userList);
  321. // 执行会员分配通知双方
  322. self::userOnlineTask($userClient, $message['group']);
  323. unset($userClient, $userGroup);
  324. break;
  325. case 'closeUser':
  326. $userInfo = self::$global->uidSimpleList;
  327. if (isset($userInfo[$message['uid']])) {
  328. $waitMessage = [
  329. 'message_type' => 'wait',
  330. 'data' => [
  331. 'content' => '暂时没有客服上班,请稍后再咨询。',
  332. ]
  333. ];
  334. Gateway::sendToClient($userInfo[$message['uid']]['0'], json_encode($waitMessage, 256));
  335. unset($waitMessage);
  336. }
  337. unset($userInfo);
  338. break;
  339. // 机器人问答.
  340. case 'toRobot':
  341. self::toRobot($client_id, $message);
  342. break;
  343. // 评价.
  344. case 'evaluate':
  345. self::evaluate($client_id, $message);
  346. break;
  347. // 客服关闭会话.
  348. case 'kfCloseUser':
  349. $userId = $message['data']['to_id'];
  350. $client = Gateway::getClientIdByUid($userId);
  351. if (!empty($client)) {
  352. $clientId = $client['0'];
  353. self::serverClose($clientId, $message['data']['conversationId']);
  354. }
  355. break;
  356. // 客服更改状态.
  357. case 'kfOnline':
  358. $kfList = self::$global->kfList;
  359. $userId = $message['data']['uid'];
  360. $status = $message['data']['status'];
  361. foreach ($kfList as $k => $v) {
  362. foreach ($v as $ke => $va) {
  363. if ($ke == $userId) {
  364. $kfList[$k][$ke]['status'] = $status;
  365. }
  366. }
  367. }
  368. self::$global->kfList = $kfList;
  369. self::writeLogKfStatus($userId, $status);
  370. break;
  371. case 'changeOtherhKeFu';
  372. self::changeOtherhKeFu($client_id, $message);
  373. break;
  374. // 弹出评价.
  375. case 'getEvaluate';
  376. $client = Gateway::getClientIdByUid($message['data']['to_id']);
  377. if (!empty($client)) {
  378. $chat_message = [
  379. 'message_type' => 'getEvaluate',
  380. 'data' => [
  381. 'content' => '欢迎你的咨询,请对我们的服务做出评价',
  382. ]
  383. ];
  384. Gateway::sendToClient($client['0'], json_encode($chat_message, 256));
  385. unset($chat_message);
  386. }
  387. }
  388. }
  389. }
  390. //获取在线客服列表
  391. public static function getkfonlines()
  392. {
  393. $return = [
  394. 'message_type' => 'onlinekfs',
  395. 'data' => [],
  396. ];
  397. $nowkfid = $_SESSION['uid'];
  398. $kfs = self::$global->kfList;
  399. $groupnamemap = self::$global->groupmap;
  400. if (!$kfs || empty($nowkfid)) {
  401. return $return;
  402. }
  403. $ret = [];
  404. foreach ($kfs as $gruop => $users) {
  405. foreach ($users as $uid => $uinfo) {
  406. if ($uid != $nowkfid) {
  407. $ret[] = ['groupid' => $gruop, 'groupname' => $groupnamemap[$gruop], 'kfuid' => $uid, 'kfname' => $uinfo['name'], 'kfjobname' => $uinfo['job_name']];
  408. }
  409. }
  410. }
  411. $return['data'] = $ret;
  412. return $return;
  413. }
  414. //客户工单内部组转接
  415. public static function changeOtherhKeFu($client_id, $smessage)
  416. {
  417. $message = $smessage['data'];
  418. $groupid = isset($message['group']) ? intval($message['group']) : 0;
  419. $toukfid = isset($message['toukfuid']) ? $message['toukfuid'] : 0;
  420. $fromkfuid = isset($message['fromkfuid']) ? $message['fromkfuid'] : 0;
  421. $uid = isset($message['uid']) ? $message['uid'] : 0;
  422. $word = isset($message['word']) ? $message['word'] : '';
  423. if (empty($groupid) || empty($toukfid) || empty($fromkfuid) || empty($uid) || empty($word) || ($toukfid == $fromkfuid)) {
  424. return false;
  425. }
  426. if (!Gateway::isUidOnline($toukfid) || !Gateway::isUidOnline($uid)) {
  427. return false;
  428. }
  429. $tokfidclientid = Gateway::getClientIdByUid($toukfid);
  430. $tokfidclientid = $tokfidclientid['0'];
  431. $uidclientid = Gateway::getClientIdByUid($uid);
  432. $uidclientid = $uidclientid['0'];
  433. $kfList = $kfList_new = self::$global->kfList;
  434. $userToKf = $userToKf_new = self::$global->userToKf;
  435. if (!isset($kfList[$groupid]) || !isset($kfList[$groupid][$toukfid]) || !isset($kfList[$groupid][$fromkfuid])) {
  436. return false;
  437. }
  438. if ($kfList[$groupid][$toukfid]['status'] != 1) {
  439. return false;
  440. }
  441. foreach ($kfList[$groupid] as $key => $val) {
  442. if ($key == $fromkfuid) {
  443. $kfList_new[$groupid][$fromkfuid]['task']--;
  444. foreach ($kfList[$groupid][$key]['user_info'] as $skey => $sval) {
  445. if ($sval == $uidclientid) {
  446. unset($kfList_new[$groupid][$key]['user_info'][$skey]);
  447. }
  448. }
  449. }
  450. if ($key == $toukfid) {
  451. $kfList_new[$groupid][$toukfid]['task']++;
  452. array_push($kfList_new[$groupid][$key]['user_info'], $uidclientid);
  453. }
  454. }
  455. do {
  456. } while (!self::$global->cas('kfList', $kfList, $kfList_new));
  457. if (isset($userToKf[$uid])) {
  458. $userToKf_new[$uid]['1'] = $toukfid;
  459. }
  460. do {
  461. } while (!self::$global->cas('userToKf', $userToKf, $userToKf_new));
  462. /////////取消原有会话,开启新会话
  463. $histarttimelimit = time() - 3600 * 24;
  464. $bindval = ['user_id' => $uid, 'client_id' => $uidclientid, 'kf_id' => intval(trim($fromkfuid, 'KF')), 'histime' => $histarttimelimit];
  465. $oldlog = self::$db->select('*')->from('ws_service_log')->where('user_id= :user_id and client_id=:client_id and kf_id=:kf_id and status!=2 and start_time>=:histime ')->bindValues($bindval)->row();
  466. if (!$oldlog) {
  467. return false;
  468. }
  469. self::$db->update('ws_service_log')->cols(['status' => 2, 'end_time' => time()])->where('servicelog_id=' . $oldlog['servicelog_id'])->query();
  470. unset($oldlog['servicelog_id']);
  471. // 修改会话时长
  472. $servicelog_id = $oldlog['servicelog_id'];
  473. $serviceLog = self::$db->query("select `start_time`,`intime` from `ws_service_log` where `servicelog_id`= '$servicelog_id'");
  474. $logCount = self::$db->query("select count(*) as `count` from `ws_chat_log` where `servicelog_id`= '$servicelog_id'");
  475. $alarmCount = $logCount[0]['count'];
  476. $cvtOvertime = time() - $serviceLog[0]['start_time'];
  477. $alarmLineTime = $serviceLog[0]['start_time'] - $serviceLog[0]['intime'];
  478. self::$db->query("update `ws_alarm` set `alarm_cvtOvertime` = '$cvtOvertime',`alarm_lineTime` = '$alarmLineTime',`alarm_count` = '$alarmCount'
  479. where `servicelog_id`= '$servicelog_id'");
  480. $oldlog = array_merge($oldlog, ['kf_id' => intval(trim($toukfid, 'KF')), 'start_time' => time(), 'end_time' => 0, 'status' => 1, 'evaluate_id' => 0]);
  481. $new_id = self::$db->insert('ws_service_log')->cols($oldlog)->query();
  482. if (!$new_id) {
  483. return false;
  484. }
  485. ///通知消息发送--------------
  486. // 通知会员发送信息绑定客服的id
  487. $noticeUser = [
  488. 'message_type' => 'connect',
  489. 'data' => [
  490. 'kf_id' => $toukfid,
  491. 'conversationId' => $new_id,
  492. 'kf_name' => Gateway::getSession(Gateway::getClientIdByUid($toukfid)['0'])['name'],
  493. 'serverInfo' => self::$global->kfList[$groupid][$toukfid],
  494. ]
  495. ];
  496. Gateway::sendToClient($uidclientid, json_encode($noticeUser, 256));
  497. unset($noticeUser);
  498. // 通知客服端绑定会员的信息
  499. $noticeKf = [
  500. 'message_type' => 'connect',
  501. 'data' => [
  502. 'user_info' => $uid,
  503. 'conversationId' => $new_id,
  504. ]
  505. ];
  506. Gateway::sendToClient($tokfidclientid, json_encode($noticeKf, 256));
  507. unset($noticeKf);
  508. //回转接人,转接成功
  509. Gateway::sendToCurrentClient(json_encode(['message_type' => 'trunconnect', 'data' => ['status' => 1], 256]));
  510. return;
  511. }
  512. //客服接入sock,及初始化
  513. public static function Kfinit($client_id, $message)
  514. {
  515. $kfList = self::$global->kfList;
  516. //客服登陆验证 不符合的直接断掉
  517. //$logcheck = true; //开发时使用
  518. $kfinfo = self::KfloginChedk($client_id, $message);
  519. if (empty($kfinfo)) {
  520. Gateway::sendToClient($client_id, json_encode(["message_type" => 'checkfalse', 'data' => "验证失败"], 256));
  521. Gateway::closeCurrentClient();
  522. return true;
  523. } elseif ($kfinfo['status'] != 1) {
  524. Gateway::sendToClient($client_id, json_encode(["message_type" => 'checkfalse', 'data' => "禁用中..."], 256));
  525. Gateway::closeCurrentClient();
  526. return true;
  527. }
  528. if (isset($kfList[$message['group']][$message['uid']])) {
  529. Gateway::sendToCurrentClient(json_encode(['message_type' => 'reLoginErr', 'msg' => '你的账号已经登陆过,请先退出再登陆'], 256));
  530. Gateway::closeCurrentClient();
  531. return;
  532. }
  533. // 如果该客服未在内存中记录则记录
  534. if (!isset($kfList[$message['group']]) || !array_key_exists($message['uid'], $kfList[$message['group']])) {
  535. do {
  536. $newKfList = $kfList;
  537. $newKfList[$message['group']][$message['uid']] = [
  538. 'id' => 'KF' . $kfinfo['id'],
  539. 'name' => $kfinfo['user_name'],
  540. 'job_name' => $kfinfo['user_job_number'],
  541. 'avatar' => $kfinfo['user_avatar'],
  542. 'client_id' => $client_id,
  543. 'task' => 0,
  544. 'signature' => $kfinfo['signature'],
  545. 'status' => 2,// 1为在线(接收分配、接收消息)2为隐身(不接收分配、只接收消息)3、休息
  546. 'user_info' => []
  547. ];
  548. } while (!self::$global->cas('kfList', $kfList, $newKfList));
  549. unset($newKfList, $kfList);
  550. } else if (isset($kfList[$message['group']][$message['uid']])) {
  551. do {
  552. $newKfList = $kfList;
  553. $newKfList[$message['group']][$message['uid']]['client_id'] = $client_id;
  554. } while (!self::$global->cas('kfList', $kfList, $newKfList));
  555. unset($newKfList, $kfList);
  556. }
  557. // 绑定 client_id 和 uid
  558. Gateway::bindUid($client_id, $message['uid']);
  559. $_SESSION['group'] = $message['group'];
  560. $_SESSION['iskefu'] = 1;
  561. $_SESSION['uid'] = $message['uid'];
  562. $_SESSION['name'] = $message['name'];
  563. Gateway::joinGroup($client_id, 'group_' . $message['group']);
  564. $chat_message = [
  565. 'message_type' => 'loginSuccess',
  566. ];
  567. Gateway::sendToClient($client_id, json_encode($chat_message, 256));
  568. unset($chat_message);
  569. self::writeLogKfStatus($message['uid'], 2);
  570. // TODO 尝试拉取用户来服务 [二期规划]
  571. }
  572. /**
  573. * 管理员
  574. * @param $client_id 服务ID
  575. * @param $message 数据
  576. */
  577. public static function adminInit($client_id, $token)
  578. {
  579. // 查询token是否存在.
  580. $systemConfigData = self::$db->query("SELECT `id` FROM `ws_admins` where `token`= '$token'");
  581. //print_r(self::$global->adminList);
  582. if ($systemConfigData) {
  583. $adminList = self::$global->adminList;
  584. $adminList[] = $client_id;
  585. self::$global->adminList = $adminList;
  586. self::systemMonitoring([$client_id]);
  587. } else {
  588. Gateway::closeClient($client_id);
  589. }
  590. }
  591. //客服登陆验证
  592. public static function KfloginChedk($client, $messageArray)
  593. {
  594. $uid = isset($messageArray['uid']) ? $messageArray['uid'] : '';
  595. $token = isset($messageArray['token']) ? $messageArray['token'] : '';
  596. if (empty($uid) || empty($token)) {
  597. return false;
  598. }
  599. $expire_time_vali = time() - 60 * 60 * 24;
  600. $kfid = intval(substr($uid, 2));
  601. $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();
  602. if ($ret) {
  603. self::$db->update('ws_users')->cols(array('online_status' => 1, 'online_connectid' => $client))->where('id=' . $kfid)->query();
  604. return $ret;
  605. }
  606. return false;
  607. }
  608. //用户发送邦定用户事件
  609. public static function userInitEnt($client_id, $message)
  610. {
  611. $userList = self::$global->userList;
  612. // 如果该顾客未在内存中记录则记录
  613. $uidSimpleList = self::$global->uidSimpleList;
  614. if (isset($uidSimpleList[$message['uid']])) {
  615. $uidSimpleList = self::$global->uidSimpleList;
  616. $oldclientid = $uidSimpleList[$message['uid']]['0'];
  617. Gateway::sendToClient($oldclientid, json_encode(['type' => 'reLoginErr', 'msg' => '相同账号登陆,本次退出'], 256));
  618. Gateway::closeClient($oldclientid);
  619. sleep(2);
  620. }
  621. $group = $message['group'];
  622. $onlinekf = self::$global->kfList;
  623. if (!isset($onlinekf[$group]) || count($onlinekf[$group]) <= 0) {
  624. Gateway::sendToClient($client_id, json_encode(['message_type' => 'notice', 'content' => '暂时没有客服上班,请稍后再咨询。'], 256));
  625. sleep(2);
  626. Gateway::closeClient($client_id);
  627. return;
  628. }
  629. if (!array_key_exists($message['uid'], $userList)) {
  630. do {
  631. $NewUserList = $userList;
  632. $NewUserList[$message['uid']] = [
  633. 'id' => $message['uid'],
  634. 'name' => $message['name'],
  635. 'avatar' => $message['avatar'],
  636. 'website' => $_SESSION['origin'],//$_SERVER['HTTP_ORIGIN'],
  637. 'browse' => Gateway::browse_info(),
  638. 'system' => Gateway::get_os(),
  639. 'ip' => isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '',
  640. 'group' => $message['group'],
  641. 'intime' => time(),
  642. 'client_id' => $client_id
  643. ];
  644. } while (!self::$global->cas('userList', $userList, $NewUserList));
  645. unset($NewUserList, $userList);
  646. // 维护 UID对应的client_id 数组
  647. do {
  648. $old = $newList = self::$global->uidSimpleList;
  649. $newList[$message['uid']] = [
  650. $client_id,
  651. $message['group']
  652. ];
  653. } while (!self::$global->cas('uidSimpleList', $old, $newList));
  654. unset($old, $newList);
  655. // 写入接入值
  656. $key = date('Ymd') . 'total_in';
  657. self::$global->$key = 0;
  658. do {
  659. $oldKey = date('Ymd', strtotime('-1 day')); // 删除前一天的统计值
  660. unset(self::$global->$oldKey);
  661. } while (!self::$global->increment($key));
  662. unset($key);
  663. }
  664. // 绑定 client_id 和 uid
  665. Gateway::bindUid($client_id, $message['uid']);
  666. $_SESSION['iskefu'] = 0;
  667. $_SESSION['uid'] = $message['uid'];
  668. // 尝试分配新会员进入服务
  669. self::userOnlineTask($client_id, $message['group'], $message['uid']);
  670. }
  671. /**
  672. * 当用户断开连接时触发
  673. * @param int $client_id 连接id
  674. *
  675. * tips: 当服务端主动退出的时候,会出现 exit status 9.原因是:服务端主动断开之后,连接的客户端会走这个方法,而短时间内进程
  676. * 需要处理这多的逻辑,又有cas操作,导致进程退出会超时,然后会被内核杀死,从而报出错误 9.实际对真正的业务没有任何的影响。
  677. */
  678. public static function onClose($client_id)
  679. {
  680. $isKefuoff = isset($_SESSION['iskefu']) ? $_SESSION['iskefu'] : 0;
  681. $uid = isset($_SESSION['uid']) ? $_SESSION['uid'] : false;
  682. //echo "下线:$uid - $client_id - $isKefuoff \n";
  683. $adminList = self::$global->adminList ?? [];
  684. $key = array_search($client_id, $adminList);
  685. if (strlen($key)) {
  686. array_splice($adminList, $key, 1);
  687. self::$global->adminList = $adminList;
  688. }
  689. if (empty($uid)) {
  690. return;
  691. }
  692. if ($isKefuoff) {
  693. self::serviceOffline($client_id, $uid);
  694. } else {
  695. self::guestOffline($client_id, $uid);
  696. }
  697. return;
  698. }
  699. //客服下线了
  700. public static function serviceOffline($client_id, $uid)
  701. {
  702. $group = $_SESSION['group'];
  703. $kefuinfo_old = $kefuinfo_old_new = self::$global->kfList;
  704. $user_info = $kefuinfo_old_new[$group][$uid]['user_info'];
  705. $simpliUsers = self::$global->uidSimpleList;
  706. $simpliUsersID_UID_Arr = [];
  707. if (!empty($simpliUsers)) {
  708. foreach ($simpliUsers as $key => $val) {
  709. $simpliUsersID_UID_Arr[$val['0']] = $key;
  710. }
  711. }
  712. $now = time();
  713. if (!empty($user_info)) {
  714. foreach ($user_info as $val) {
  715. Gateway::sendToClient($val, json_encode(['type' => 'serviceoffline', 'msg' => '客户人员下线!'], 256));
  716. if (isset($simpliUsersID_UID_Arr[$val])) {
  717. self::$db->query("update `ws_service_log` set `status` = '2',end_time=$now where `user_id`= '$simpliUsersID_UID_Arr[$val]' and kf_id='$uid' and group_id=$group and `status`!=2 ");
  718. // 修改会话时长
  719. $serviceLog = self::$db->query("select `start_time`,`servicelog_id`,`intime` from `ws_service_log` where `user_id`= '$simpliUsersID_UID_Arr[$val]' and kf_id='$uid' and group_id=$group and `status`!=2");
  720. $logCount = self::$db->query("select count(*) as `count` from `ws_chat_log` where `servicelog_id`= '$servicelog_id'");
  721. $alarmCount = $logCount[0]['count'];
  722. $servicelog_id = $serviceLog[0]['servicelog_id'];
  723. $cvtOvertime = time() - $serviceLog[0]['start_time'];
  724. $alarmLineTime = $serviceLog[0]['start_time'] - $serviceLog[0]['intime'];
  725. self::$db->query("update `ws_alarm` set `alarm_cvtOvertime` = '$cvtOvertime',`alarm_lineTime` = '$alarmLineTime',`alarm_count` = '$alarmCount'
  726. where `servicelog_id`= '$servicelog_id'");
  727. }
  728. Gateway::closeClient($val);
  729. }
  730. }
  731. unset($kefuinfo_old_new[$group][$uid]);
  732. $kfid = intval(substr($uid, 2));
  733. self::$db->update('ws_users')->cols(array('online_status' => 0, 'online_connectid' => ''))->where('id=' . $kfid)->query();
  734. do {
  735. } while (!self::$global->cas('kfList', $kefuinfo_old, $kefuinfo_old_new));
  736. self::writeLogKfStatus($uid, 0);
  737. return;
  738. }
  739. //用户下线了
  740. public static function guestOffline($client_id, $uid)
  741. {
  742. $kfuid = -1;
  743. $krclient_id = 0;
  744. $kfgroup = -1;
  745. $userToKf = $userToKfNew = self::$global->userToKf;
  746. if (isset($userToKfNew[$uid])) {
  747. $kfuid = isset($userToKfNew[$uid]['1']) ? $userToKfNew[$uid]['1'] : -1;
  748. $krclient_id = isset(Gateway::getClientIdByUid($kfuid)['0']) ? Gateway::getClientIdByUid($kfuid)['0'] : 0;
  749. unset($userToKfNew[$uid]);
  750. do {
  751. } while (!self::$global->cas('userToKf', $userToKf, $userToKfNew));
  752. }
  753. $uidSimpleList = $uidSimpleListNew = self::$global->uidSimpleList;
  754. if (isset($uidSimpleListNew[$uid])) {
  755. $kfgroup = $uidSimpleListNew[$uid]['1'];
  756. unset($uidSimpleListNew[$uid]);
  757. do {
  758. } while (!self::$global->cas('uidSimpleList', $uidSimpleList, $uidSimpleListNew));
  759. }
  760. $userList = $userListNew = self::$global->userList;
  761. $group_wait_count = 0;
  762. if (!empty($userList)) {
  763. $ischange = 0;
  764. foreach ($userList as $key => $val) {
  765. if ($val['group'] == $kfuid) {
  766. $group_wait_count++;
  767. }
  768. if ($val['id'] == $uid) {
  769. unset($userListNew[$key]);
  770. $ischange = 1;
  771. $group_wait_count--;
  772. break;
  773. }
  774. }
  775. if ($ischange) {
  776. do {
  777. } while (!self::$global->cas('userList', $userList, $userListNew));
  778. Gateway::sendToGroup('group_' . $kfgroup, json_encode(['message_type' => 'kfqueuelength', 'leng' => $group_wait_count], 256));
  779. }
  780. }
  781. if ($kfuid != -1 && $kfgroup != -1) {
  782. $kefuinfo_old = $kefuinfo_old_new = self::$global->kfList;
  783. $ischange_kf_list = 0;
  784. if (isset($kefuinfo_old[$kfgroup][$kfuid])) {
  785. $infos = $kefuinfo_old[$kfgroup][$kfuid]['user_info'];
  786. if ($infos) {
  787. if (is_array($infos)) {
  788. foreach ($infos as $key => $val) {
  789. if ($val == $client_id) {
  790. $ischange_kf_list = 1;
  791. unset($kefuinfo_old_new[$kfgroup][$kfuid]['user_info'][$key]);
  792. $kefuinfo_old_new[$kfgroup][$kfuid]['task'] = $kefuinfo_old_new[$kfgroup][$kfuid]['task'] - 1;
  793. }
  794. }
  795. }
  796. if ($ischange_kf_list) {
  797. do {
  798. } while (!self::$global->cas('kfList', $kefuinfo_old, $kefuinfo_old_new));
  799. $chat_message = [
  800. 'message_type' => 'userClose',
  801. 'data' => [
  802. 'content' => '用户连接已断开',
  803. 'id' => $uid,
  804. 'time' => date('H:i'),
  805. ]
  806. ];
  807. $now = time();
  808. $kf__uid = substr($kfuid, 2);
  809. $sql = "update `ws_service_log` set `status` = '3',end_time=$now where `user_id`= '$uid' and kf_id='$kf__uid' and group_id=$kfgroup and status=1 ";
  810. //echo "客户退出:". $sql ."\n";
  811. self::$db->query($sql);
  812. Gateway::sendToClient($krclient_id, json_encode($chat_message, 256));
  813. }
  814. }
  815. }
  816. }
  817. }
  818. /**
  819. * 客服结束会话
  820. * @param int $client_id 连接id
  821. *
  822. * tips: 当服务端主动退出的时候,会出现 exit status 9.原因是:服务端主动断开之后,连接的客户端会走这个方法,而短时间内进程
  823. * 需要处理这多的逻辑,又有cas操作,导致进程退出会超时,然后会被内核杀死,从而报出错误 9.实际对真正的业务没有任何的影响。
  824. */
  825. public static function serverClose($client_id, $servicelog_id)
  826. {
  827. // 返回.
  828. $chat_message = [
  829. 'message_type' => 'closeBysever',
  830. 'data' => [
  831. 'content' => '客服停止了该会话',
  832. 'time' => date('H:i'),
  833. ]
  834. ];
  835. Gateway::sendToClient($client_id, json_encode($chat_message, 256));
  836. Gateway::closeClient($client_id);
  837. $now = time();
  838. $sql = "update `ws_service_log` set `status`='2',end_time=$now where `servicelog_id`= '$servicelog_id'";
  839. //echo "客户退出:". $sql ."\n";
  840. self::$db->query($sql);
  841. $isServiceUserOut = false;
  842. // 修改会话时长
  843. $serviceLog = self::$db->query("select `start_time`,`intime` from `ws_service_log` where `servicelog_id`= '$servicelog_id'");
  844. $logCount = self::$db->query("select count(*) as `count` from `ws_chat_log` where `servicelog_id`= '$servicelog_id'");
  845. $alarmCount = $logCount[0]['count'];
  846. $cvtOvertime = time() - $serviceLog[0]['start_time'];
  847. $alarmLineTime = $serviceLog[0]['start_time'] - $serviceLog[0]['intime'];
  848. self::$db->query("update `ws_alarm` set `alarm_cvtOvertime` = '$cvtOvertime',`alarm_lineTime` = '$alarmLineTime',`alarm_count` = '$alarmCount'
  849. where `servicelog_id`= '$servicelog_id'");
  850. // 将会员服务信息,从客服的服务列表中移除
  851. $old = $kfList = self::$global->kfList;
  852. foreach ($kfList as $k => $v) {
  853. foreach ($v as $key => $vo) {
  854. if (in_array($client_id, $vo['user_info'])) {
  855. $isServiceUserOut = true;
  856. // 根据client id 去更新会话工单一些信息
  857. self::$db->query("update `ws_service_log` set `end_time` = " . time() . " , `status` = '2' where `client_id`= '" . $client_id . "'");
  858. // 从会员的内存表中检索出该会员的信息,并更新内存
  859. $oldSimple = $simpleList = self::$global->uidSimpleList;
  860. $outUser = [];
  861. foreach ($simpleList as $u => $c) {
  862. if ($c['0'] == $client_id) {
  863. $outUser[] = [
  864. 'user_id' => $u,
  865. 'group_id' => $c['1']
  866. ];
  867. unset($simpleList[$u]);
  868. break;
  869. }
  870. }
  871. while (!self::$global->cas('uidSimpleList', $oldSimple, $simpleList)) {
  872. };
  873. unset($oldSimple, $simpleList);
  874. $outUser = self::$db->query("select `user_id`,`group_id` from `ws_service_log` where `client_id`= '" . $client_id . "'");
  875. // 通知 客服删除退出的用户
  876. if (!empty($outUser)) {
  877. $del_message = [
  878. 'message_type' => 'delUser',
  879. 'data' => [
  880. 'id' => $outUser['0']['user_id']
  881. ]
  882. ];
  883. Gateway::sendToClient($vo['client_id'], json_encode($del_message, 256));
  884. unset($del_message);
  885. // 尝试分配新会员进入服务
  886. self::userOfflineTask($outUser['0']['group_id']);
  887. }
  888. unset($outUser);
  889. // 维护现在的该客服的服务信息
  890. $kfList[$k][$key]['task'] -= 1; // 当前服务的人数 -1
  891. foreach ($vo['user_info'] as $m => $l) {
  892. if ($client_id == $l) {
  893. unset($kfList[$k][$key]['user_info'][$m]);
  894. break;
  895. }
  896. }
  897. // 刷新内存中客服的服务列表
  898. while (!self::$global->cas('kfList', $old, $kfList)) {
  899. };
  900. unset($old, $kfList);
  901. break;
  902. }
  903. }
  904. if ($isServiceUserOut) break;
  905. }
  906. // 尝试从排队的用户中删除退出的客户端
  907. if (false == $isServiceUserOut) {
  908. $old = $userList = self::$global->userList;
  909. foreach (self::$global->userList as $key => $vo) {
  910. if ($client_id == $vo['client_id']) {
  911. $isServiceUserOut = true;
  912. unset($userList[$key]);
  913. break;
  914. }
  915. }
  916. while (!self::$global->cas('userList', $old, $userList)) {
  917. };
  918. // 从会员的内存表中检索出该会员的信息,并更新内存
  919. $oldSimple = $simpleList = self::$global->uidSimpleList;
  920. foreach ($simpleList as $u => $c) {
  921. if ($c['0'] == $client_id) {
  922. unset($simpleList[$u]);
  923. break;
  924. }
  925. }
  926. while (!self::$global->cas('uidSimpleList', $oldSimple, $simpleList)) {
  927. };
  928. unset($oldSimple, $simpleList);
  929. }
  930. // 尝试是否是客服退出
  931. if (false == $isServiceUserOut) {
  932. $old = $kfList = self::$global->kfList;
  933. foreach (self::$global->kfList as $k => $v) {
  934. foreach ($v as $key => $vo) {
  935. // 客服服务列表中无数据,才去删除客服内存信息
  936. if ($client_id == $vo['client_id'] && (0 == count($vo['user_info']))) {
  937. unset($kfList[$k][$key]);
  938. break;
  939. }
  940. }
  941. }
  942. while (!self::$global->cas('kfList', $old, $kfList)) {
  943. };
  944. }
  945. }
  946. /**
  947. * 有人退出
  948. * @param $group
  949. */
  950. private static function userOfflineTask($group)
  951. {
  952. // TODO 此处查询最大的可服务人数,后面可以用其他的方式,存储这个数值,让其更高效的访问
  953. $maxNumber = self::getMaxServiceNum();
  954. $res = self::assignmentTask(self::$global->kfList, self::$global->userList, $group, $maxNumber);
  955. unset($maxNumber);
  956. if (1 == $res['code']) {
  957. while (!self::$global->cas('kfList', self::$global->kfList, $res['data']['4'])) {
  958. }; // 更新客服数据
  959. while (!self::$global->cas('userList', self::$global->userList, $res['data']['5'])) {
  960. }; // 更新会员数据
  961. // 服务信息入库
  962. $serviceLog = [
  963. 'user_id' => $res['data']['3']['id'],
  964. 'client_id' => $res['data']['3']['client_id'],
  965. 'user_name' => $res['data']['3']['name'],
  966. 'user_ip' => $res['data']['3']['ip'],
  967. 'user_avatar' => $res['data']['3']['avatar'],
  968. 'kf_id' => intval(ltrim($res['data']['0'], 'KF')),
  969. 'start_time' => time(),
  970. 'group_id' => $group,
  971. 'website' => $res['data']['3']['website'],
  972. 'system' => $res['data']['3']['system'],
  973. 'browse' => $res['data']['3']['browse'],
  974. 'status' => 1,
  975. 'intime' => $res['data']['3']['intime'],
  976. 'end_time' => 0
  977. ];
  978. $hisSession = self::$db->select('*')->from('ws_service_log')->where('user_id=:user_id and kf_id=:kf_id and group_id=:group_id and status in (1,3)')->bindValues(array('user_id' => $res['data']['3']['id'], 'kf_id' => intval(ltrim($res['data']['0'], 'KF')), 'group_id' => $group))->row();
  979. if (!$hisSession) {
  980. $conversationId = self::$db->insert('ws_service_log')->cols($serviceLog)->query();
  981. } else {
  982. self::$db->update('ws_service_log')->cols(['status' => 1])->where('servicelog_id=' . $hisSession['servicelog_id'])->query();
  983. $conversationId = $hisSession['servicelog_id'];
  984. }
  985. unset($serviceLog);
  986. // 通知会员发送信息绑定客服的id
  987. $noticeUser = [
  988. 'message_type' => 'connect',
  989. 'data' => [
  990. 'kf_id' => $res['data']['0'],
  991. 'kf_name' => $res['data']['1'],
  992. 'conversationId' => $conversationId,
  993. 'serverInfo' => self::$global->kfList[$group][$res['data']['0']],
  994. ]
  995. ];
  996. Gateway::sendToClient($res['data']['3']['client_id'], json_encode($noticeUser, 256));
  997. unset($noticeUser);
  998. // 通知客服端绑定会员的信息
  999. $noticeKf = [
  1000. 'message_type' => 'connect',
  1001. 'data' => [
  1002. 'user_info' => $res['data']['3'],
  1003. 'conversationId' => $conversationId,
  1004. ]
  1005. ];
  1006. Gateway::sendToClient($res['data']['2'], json_encode($noticeKf, 256));
  1007. unset($noticeKf);
  1008. // 逐一通知
  1009. $number = 1;
  1010. foreach (self::$global->userList as $vo) {
  1011. $waitMsg = '您前面还有 ' . $number . ' 位会员在等待。';
  1012. $waitMessage = [
  1013. 'message_type' => 'wait',
  1014. 'data' => [
  1015. 'content' => $waitMsg,
  1016. ]
  1017. ];
  1018. Gateway::sendToClient($vo['client_id'], json_encode($waitMessage, 256));
  1019. $number++;
  1020. }
  1021. unset($waitMessage, $number);
  1022. // 写入接入值
  1023. $key = date('Ymd') . 'success_in';
  1024. self::$global->$key = 0;
  1025. do {
  1026. $oldKey = date('Ymd', strtotime('-1 day')); // 删除前一天的统计值
  1027. unset(self::$global->$oldKey);
  1028. } while (!self::$global->increment($key));
  1029. unset($key);
  1030. } else {
  1031. switch ($res['code']) {
  1032. case -1:
  1033. $waitMsg = '暂时没有客服上班,请稍后再咨询。';
  1034. // 逐一通知
  1035. foreach (self::$global->userList as $vo) {
  1036. $waitMessage = [
  1037. 'message_type' => 'wait',
  1038. 'data' => [
  1039. 'content' => $waitMsg,
  1040. ]
  1041. ];
  1042. Gateway::sendToClient($vo['client_id'], json_encode($waitMessage, 256));
  1043. }
  1044. break;
  1045. case -2:
  1046. break;
  1047. case -3:
  1048. break;
  1049. case -4:
  1050. // 逐一通知
  1051. $number = 1;
  1052. foreach (self::$global->userList as $vo) {
  1053. $waitMsg = '您前面还有 ' . $number . ' 位会员在等待。';
  1054. $waitMessage = [
  1055. 'message_type' => 'wait',
  1056. 'data' => [
  1057. 'content' => $waitMsg,
  1058. ]
  1059. ];
  1060. Gateway::sendToClient($vo['client_id'], json_encode($waitMessage, 256));
  1061. $number++;
  1062. }
  1063. break;
  1064. }
  1065. unset($waitMessage, $number);
  1066. }
  1067. }
  1068. /**
  1069. * 有人进入执行分配
  1070. * @param $client_id
  1071. * @param $group
  1072. * @param $uid
  1073. */
  1074. private static function userOnlineTask($client_id, $group, $uid = 0)
  1075. {
  1076. // TODO 此处查询最大的可服务人数,后面可以用其他的方式,存储这个数值,让其更高效的访问
  1077. $maxNumber = self::getMaxServiceNum();
  1078. $res = self::assignmentTask(self::$global->kfList, self::$global->userList, $group, $maxNumber, $uid);
  1079. unset($maxNumber);
  1080. if (1 == $res['code']) {
  1081. while (!self::$global->cas('kfList', self::$global->kfList, $res['data']['4'])) {
  1082. }; // 更新客服数据
  1083. while (!self::$global->cas('userList', self::$global->userList, $res['data']['5'])) {
  1084. }; // 更新会员数据
  1085. $userToKf = self::$global->userToKf;
  1086. $userToKf[$res['data']['3']['id']] = [
  1087. $res['data']['3']['id'],
  1088. $res['data']['0']
  1089. ];
  1090. self::$global->userToKf = $userToKf;
  1091. // 服务信息入库
  1092. $serviceLog = [
  1093. 'user_id' => $res['data']['3']['id'],
  1094. 'client_id' => $res['data']['3']['client_id'],
  1095. 'user_name' => $res['data']['3']['name'],
  1096. 'user_ip' => $res['data']['3']['ip'],
  1097. 'user_avatar' => $res['data']['3']['avatar'],
  1098. 'kf_id' => intval(ltrim($res['data']['0'], 'KF')),
  1099. 'start_time' => time(),
  1100. 'group_id' => $group,
  1101. 'website' => $res['data']['3']['website'],
  1102. 'system' => $res['data']['3']['system'],
  1103. 'browse' => $res['data']['3']['browse'],
  1104. 'status' => 1,
  1105. 'intime' => $res['data']['3']['intime'],
  1106. 'end_time' => 0
  1107. ];
  1108. $hisSession = self::$db->select('*')->from('ws_service_log')->where('user_id=:user_id and kf_id=:kf_id and group_id=:group_id and status in (1,3)')->bindValues(array('user_id' => $res['data']['3']['id'], 'kf_id' => intval(ltrim($res['data']['0'], 'KF')), 'group_id' => $group))->row();
  1109. if (!$hisSession) {
  1110. $conversationId = self::$db->insert('ws_service_log')->cols($serviceLog)->query();
  1111. $alarmData = [
  1112. 'servicelog_id' => $conversationId,
  1113. ];
  1114. self::$db->insert('ws_alarm')->cols($alarmData)->query();
  1115. } else {
  1116. self::$db->update('ws_service_log')->cols(['status' => 1])->where('servicelog_id=' . $hisSession['servicelog_id'])->query();
  1117. $conversationId = $hisSession['servicelog_id'];
  1118. }
  1119. unset($serviceLog);
  1120. // 通知会员发送信息绑定客服的id
  1121. $noticeUser = [
  1122. 'message_type' => 'connect',
  1123. 'data' => [
  1124. 'kf_id' => $res['data']['0'],
  1125. 'conversationId' => $conversationId,
  1126. 'serverInfo' => self::$global->kfList[$group][$res['data']['0']],
  1127. 'kf_name' => $res['data']['1']
  1128. ]
  1129. ];
  1130. Gateway::sendToClient($client_id, json_encode($noticeUser, 256));
  1131. unset($noticeUser);
  1132. // 发送客服欢迎语
  1133. $sayHello = self::$db->query('select `word`,`status` from `ws_reply` where `id` = 2');
  1134. if (!empty($sayHello) && 1 == $sayHello['0']['status']) {
  1135. $chat_message = [
  1136. 'message_type' => 'chatMessage',
  1137. 'data' => [
  1138. 'name' => $res['data']['1'],
  1139. //'avatar' => self::$global->kfList[$group][$res['data']['0']],
  1140. 'id' => $res['data']['0'],
  1141. 'time' => date('H:i'),
  1142. 'content' => $sayHello['0']['word']
  1143. ]
  1144. ];
  1145. Gateway::sendToClient($client_id, json_encode($chat_message, 256));
  1146. unset($chat_message);
  1147. }
  1148. unset($sayHello);
  1149. // 通知客服端绑定会员的信息
  1150. $noticeKf = [
  1151. 'message_type' => 'connect',
  1152. 'data' => [
  1153. 'user_info' => $res['data']['3'],
  1154. 'conversationId' => $conversationId,
  1155. ]
  1156. ];
  1157. Gateway::sendToClient($res['data']['2'], json_encode($noticeKf, 256));
  1158. unset($noticeKf);
  1159. // 写入接入值
  1160. $key = date('Ymd') . 'success_in';
  1161. self::$global->$key = 0;
  1162. do {
  1163. $oldKey = date('Ymd', strtotime('-1 day')); // 删除前一天的统计值
  1164. unset(self::$global->$oldKey);
  1165. } while (!self::$global->increment($key));
  1166. unset($key);
  1167. } else {
  1168. $waitMsg = '';
  1169. switch ($res['code']) {
  1170. case -1:
  1171. $waitMsg = '暂时没有客服上班,请稍后再咨询。';
  1172. break;
  1173. case -2:
  1174. break;
  1175. case -3:
  1176. break;
  1177. case -4:
  1178. $number = count(self::$global->userList);
  1179. $waitMsg = '您前面还有 ' . $number . ' 位会员在等待。';
  1180. break;
  1181. }
  1182. $waitMessage = [
  1183. 'message_type' => 'wait',
  1184. 'data' => [
  1185. 'content' => $waitMsg,
  1186. ]
  1187. ];
  1188. Gateway::sendToClient($client_id, json_encode($waitMessage, 256));
  1189. unset($waitMessage);
  1190. }
  1191. $userlist = self::$global->userList;
  1192. $waitcount = 0;
  1193. if ($userlist) {
  1194. foreach ($userlist as $val) {
  1195. if ($val['group'] == $group) {
  1196. $waitcount++;
  1197. }
  1198. }
  1199. Gateway::sendToGroup('group_' . $group, json_encode(['message_type' => 'kfqueuelength', 'leng' => $waitcount], 256));
  1200. }
  1201. }
  1202. /**
  1203. * 给客服分配会员【均分策略】
  1204. * @param $kfList
  1205. * @param $userList
  1206. * @param $group
  1207. * @param $total
  1208. */
  1209. private static function assignmentTask($kfList, $userList, $group, $total, $uid = 0)
  1210. {
  1211. // 注:修改为已上线(status为1上线status为2不接受分配)
  1212. $onlineKF = [];
  1213. foreach ($kfList as $k => $v) {
  1214. foreach ($v as $ke => $va) {
  1215. if ($va['status'] == 1) {
  1216. $onlineKF[$k][$ke] = $va;
  1217. }
  1218. }
  1219. }
  1220. // 没有客服上线
  1221. if (empty($onlineKF) || empty($onlineKF[$group])) {
  1222. return ['code' => -1];
  1223. }
  1224. // 没有待分配的会员
  1225. if (empty($userList)) {
  1226. return ['code' => -2];
  1227. }
  1228. // 未设置每个客服可以服务多少人
  1229. if (0 == $total) {
  1230. return ['code' => -3];
  1231. }
  1232. // 查看该组的客服是否在线
  1233. if (!isset($onlineKF[$group])) {
  1234. return ['code' => -1];
  1235. }
  1236. //上次用户掉线后,还可以继续上一次 (如果没有关闭) 的会话 --1
  1237. $odltalksession = false;
  1238. $user = $user_first = array_shift($userList);
  1239. if ($uid > 0 && $user['id'] != $uid && count($userList) > 1) {
  1240. $timevalielimit = time() - 60 * 5;
  1241. $odltalksession = self::$db->select('*')->from('ws_service_log')->where('user_id=:uid and `group`=:group and `status`=3 and end_time>=:timevalielimit"')->bindValues(array('uid' => $uid, 'group' => $group, 'timevalielimit' => $timevalielimit))->row();
  1242. if ($odltalksession) {
  1243. foreach ($userList as $ttkey => $ttval) {
  1244. if ($ttval['id'] == $uid) {
  1245. array_unshift($userList, $user);
  1246. $user = $userList[$ttkey];
  1247. unset($userList[$ttkey]);
  1248. break;
  1249. }
  1250. }
  1251. }
  1252. }
  1253. //上次用户掉线后,还可以继续上一次 (如果没有关闭) 的会话 --2
  1254. if ($odltalksession) {
  1255. $oldkrid = 'KF' . $odltalksession['kf_id'];
  1256. if (isset($onlineKF[$group][$oldkrid])) {
  1257. $kf = $onlineKF[$group][$oldkrid];
  1258. $min = $kf['task'];
  1259. $flag = $kf['id'];
  1260. unset($onlineKF[$group][$oldkrid]);
  1261. } else {
  1262. goto NOSIGNKF;
  1263. }
  1264. } else {
  1265. NOSIGNKF:
  1266. $kf = $onlineKF[$group];
  1267. $kf = array_shift($kf);
  1268. $min = $kf['task'];
  1269. $flag = $kf['id'];
  1270. foreach ($onlineKF[$group] as $key => $vo) {
  1271. if ($vo['task'] < $min) {
  1272. $min = $vo['task'];
  1273. $flag = $key;
  1274. }
  1275. }
  1276. unset($kf);
  1277. }
  1278. // 需要排队了
  1279. if ($onlineKF[$group][$flag]['task'] == $total) {
  1280. array_unshift($userList, $user);
  1281. return ['code' => -4];
  1282. }
  1283. $kfList[$group][$flag]['task'] += 1;
  1284. array_push($kfList[$group][$flag]['user_info'], $user['client_id']); // 被分配的用户信息
  1285. return [
  1286. 'code' => 1,
  1287. 'data' => [
  1288. $onlineKF[$group][$flag]['id'],
  1289. $onlineKF[$group][$flag]['name'],
  1290. $onlineKF[$group][$flag]['client_id'],
  1291. $user,
  1292. $kfList,
  1293. $userList
  1294. ]
  1295. ];
  1296. }
  1297. /**
  1298. * 获取最大的服务人数
  1299. * @return int
  1300. */
  1301. private static function getMaxServiceNum()
  1302. {
  1303. $maxNumber = self::$db->query('select `max_service` from `ws_kf_config` where `id` = 1');
  1304. if (!empty($maxNumber)) {
  1305. $maxNumber = 5;
  1306. } else {
  1307. $maxNumber = $maxNumber['0']['max_service'];
  1308. }
  1309. return $maxNumber;
  1310. }
  1311. /**
  1312. * 将内存中的数据写入统计表
  1313. * @param int $flag
  1314. */
  1315. private static function writeLog($flag = 1)
  1316. {
  1317. // 上午 8点 到 22 点开始统计
  1318. if (date('H') < 8 || date('H') > 22) {
  1319. return;
  1320. }
  1321. // 当前正在接入的人 和 在线客服数
  1322. $kfList = self::$global->kfList;
  1323. $nowTalking = 0;
  1324. $onlineKf = 0;
  1325. if (!empty($kfList)) {
  1326. foreach ($kfList as $key => $vo) {
  1327. $onlineKf += count($vo);
  1328. foreach ($vo as $k => $v) {
  1329. $nowTalking += count($v['user_info']);
  1330. }
  1331. }
  1332. }
  1333. // 在队列中的用户
  1334. $inQueue = count(self::$global->userList);
  1335. $key = date('Ymd') . 'total_in';
  1336. $key2 = date('Ymd') . 'success_in';
  1337. $param = [
  1338. 'is_talking' => $nowTalking,
  1339. 'in_queue' => $inQueue,
  1340. 'online_kf' => $onlineKf,
  1341. 'success_in' => self::$global->$key2,
  1342. 'total_in' => self::$global->$key,
  1343. 'now_date' => date('Y-m-d')
  1344. ];
  1345. self::$db->update('ws_now_data')->cols($param)->where('id=1')->query();
  1346. if (2 == $flag) {
  1347. $param = [
  1348. 'is_talking' => $nowTalking,
  1349. 'in_queue' => $inQueue,
  1350. 'online_kf' => $onlineKf,
  1351. 'success_in' => self::$global->$key2,
  1352. 'total_in' => self::$global->$key,
  1353. 'add_date' => date('Y-m-d'),
  1354. 'add_hour' => date('H'),
  1355. 'add_minute' => date('i'),
  1356. ];
  1357. self::$db->insert('ws_service_data')->cols($param)->query();
  1358. }
  1359. unset($kfList, $nowTalking, $inQueue, $onlineKf, $key, $key2, $param);
  1360. }
  1361. /**
  1362. * 机器人问答
  1363. * @param $client_id 服务ID
  1364. * @param $message 数据
  1365. */
  1366. private static function toRobot($client_id, $message)
  1367. {
  1368. $groups_id = $message['data']['groups_id'];
  1369. $robot_name = $message['data']['robot_name'];
  1370. $robotgroups_id = $message['data']['robotgroups_id'];
  1371. // 查询问题.
  1372. $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 . "'");
  1373. $chat_message = [
  1374. 'message_type' => 'robotMessage',
  1375. //'message_type' => 'chatMessage',
  1376. 'data' => [
  1377. 'name' => '智能助手',
  1378. 'time' => date('H:i'),
  1379. 'content' => $getRobot ? $getRobot[0]['robot_content'] : 'error',
  1380. ]
  1381. ];
  1382. sleep(1);
  1383. Gateway::sendToClient($client_id, json_encode($chat_message, 256));
  1384. }
  1385. /**
  1386. * 评价
  1387. * @param $client_id 服务ID
  1388. * @param $message 数据
  1389. */
  1390. private static function evaluate($client_id, $message)
  1391. {
  1392. // 修改数据库.
  1393. $evaluate_id = $message['data']['evaluate_id'];
  1394. $result = self::$db->query("UPDATE `ws_service_log` SET `evaluate_id` = '" . $evaluate_id . "' WHERE `client_id`='" . $client_id . "'");
  1395. if ($result) {
  1396. $chat_message = [
  1397. 'message_type' => 'evaluate',
  1398. 'data' => [
  1399. 'status' => 1,
  1400. 'time' => date('H:i'),
  1401. ]
  1402. ];
  1403. } else {
  1404. $chat_message = [
  1405. 'message_type' => 'evaluate',
  1406. 'data' => [
  1407. 'status' => 2,
  1408. 'time' => date('H:i'),
  1409. ]
  1410. ];
  1411. }
  1412. Gateway::sendToClient($client_id, json_encode($chat_message, 256));
  1413. }
  1414. //获取系统配置
  1415. private static function upsystemconfig()
  1416. {
  1417. $systemConfigData = self::$db->query("SELECT * FROM `ws_systemconfig`");
  1418. $arr = [];
  1419. if ($systemConfigData) {
  1420. foreach ($systemConfigData as $item) {
  1421. $arr[$item['systemconfig_enName']] = $item;
  1422. }
  1423. self::$global->systemconfig = $arr;
  1424. }
  1425. $group = self::$db->query("SELECT * FROM `ws_groups`");
  1426. $arr = [];
  1427. if ($group) {
  1428. foreach ($group as $val) {
  1429. $arr[$val['id']] = $val['name'];
  1430. }
  1431. self::$global->groupmap = $arr;
  1432. }
  1433. }
  1434. /**
  1435. * 超时
  1436. * @param $client_id 服务ID
  1437. * @param $message 数据
  1438. */
  1439. private static function overTime()
  1440. {
  1441. // 查询对话时效设置.
  1442. $systemConfigData = self::$db->query("SELECT `systemconfig_data`,`systemconfig_enName`,`systemconfig_content` FROM `ws_systemconfig`");
  1443. foreach ($systemConfigData as $k => $v) {
  1444. if ($v['systemconfig_enName'] == 'overtime') {
  1445. self::$global->overtime = $v;
  1446. } elseif ($v['systemconfig_enName'] == 'unoperated') {
  1447. self::$global->unoperated = $v;
  1448. } elseif ($v['systemconfig_enName'] == 'noResponse') {
  1449. self::$global->noResponse = $v;
  1450. }
  1451. }
  1452. // 查询未断开的工单.
  1453. $serviceLog = self::$db->query("SELECT `servicelog_id`,`client_id`,`start_time` FROM `ws_service_log` WHERE `status`='1' OR `status`='3'");
  1454. $whereOr = '1=0';
  1455. foreach ($serviceLog as $k => $v) {
  1456. if ($k == 0) {
  1457. $whereOr = "`servicelog_id`=" . $v['servicelog_id'];
  1458. } else {
  1459. $whereOr .= " OR `servicelog_id`=" . $v['servicelog_id'];
  1460. }
  1461. }
  1462. // 查询最后一次会话.
  1463. //$chatLog = self::$db->query("SELECT `servicelog_id`,MAX(`time_line`) FROM `ws_chat_log` WHERE ".$whereOr." group by `servicelog_id`");
  1464. $chatLog = self::$db->query("
  1465. select * from ws_chat_log as a where time_line=(
  1466. select max(b.time_line) from ws_chat_log as b where a.servicelog_id = b.servicelog_id and (" . $whereOr . ") group by servicelog_id
  1467. )
  1468. ");
  1469. $setOvertime = strtotime('-' . (self::$global->overtime['systemconfig_data'] - 60) . ' second');
  1470. $overtime = strtotime('-' . (self::$global->overtime['systemconfig_data']) . ' second');
  1471. $setUnoperated = strtotime('-' . (self::$global->unoperated['systemconfig_data'] - 60) . ' second');
  1472. $unoperated = strtotime('-' . (self::$global->unoperated['systemconfig_data']) . ' second');
  1473. $noResponse = strtotime('-' . (self::$global->noResponse['systemconfig_data']) . ' second');
  1474. foreach ($serviceLog as $k => $v) {
  1475. if (!strlen(array_search($v['servicelog_id'], array_column($chatLog, 'servicelog_id')))) {
  1476. // 如果小于设定时间则关闭会话.
  1477. if ($v['start_time'] <= $unoperated) {
  1478. self::serverClose($v['client_id'], $v['servicelog_id']);
  1479. // 如果小于设定时间前一分钟则给出提示.
  1480. } elseif ($v['start_time'] <= $setUnoperated) {
  1481. $chat_message = [
  1482. 'message_type' => 'overtime',
  1483. 'data' => [
  1484. 'content' => self::$global->unoperated['systemconfig_content'],
  1485. ]
  1486. ];
  1487. Gateway::sendToClient($v['client_id'], json_encode($chat_message, 256));
  1488. }
  1489. }
  1490. }
  1491. // 循环检测会话时效.
  1492. foreach ($chatLog as $k => $v) {
  1493. $toWho = substr($v['to_id'], 0, 2);
  1494. // 如果对话为客服的最后一次对话且时间小于设定时间则结束工单.
  1495. if ($v['time_line'] <= $overtime) {
  1496. $found_key = array_search($v['servicelog_id'], array_column($serviceLog, 'servicelog_id'));
  1497. print_r([1, $serviceLog[$found_key]['client_id']]);
  1498. self::serverClose($serviceLog[$found_key]['client_id'], $v['servicelog_id']);
  1499. // 如果对话为客服的最后一次对话且时间小于设定时间前一分钟则给出提示.
  1500. } elseif ($v['time_line'] <= $setOvertime) {
  1501. $chat_message = [
  1502. 'message_type' => 'overtime',
  1503. 'data' => [
  1504. 'content' => self::$global->overtime['systemconfig_content'],
  1505. ]
  1506. ];
  1507. $found_key = array_search($v['servicelog_id'], array_column($serviceLog, 'servicelog_id'));
  1508. Gateway::sendToClient($serviceLog[$found_key]['client_id'], json_encode($chat_message, 256));
  1509. }
  1510. }
  1511. }
  1512. /**
  1513. * 系统监控
  1514. * @param $message 数据
  1515. */
  1516. private static function systemMonitoring($adminList)
  1517. {
  1518. // 查询未结束工单.
  1519. $serviceLog = self::$db->query("select ws_service_log.servicelog_id,ws_users.user_name as server_name,ws_service_log.user_name,kf_id,start_time,end_time,ws_service_log.group_id,evaluate_id,intime,ws_service_log.status,alarm_userSensitive,alarm_serverSensitive,alarm_corresponding
  1520. from `ws_service_log`
  1521. join `ws_alarm` on ws_service_log.servicelog_id=ws_alarm.servicelog_id
  1522. join `ws_users` on ws_service_log.kf_id=ws_users.id
  1523. WHERE ws_service_log.status='1' OR ws_service_log.status='3'");
  1524. // 查询系统设置表.
  1525. $systemconfig = self::$db->query("SELECT `systemconfig_data` FROM `ws_systemconfig` WHERE `systemconfig_enName`='verifyReturnTime' or `systemconfig_enName`='verifyAllTime'");
  1526. $found_key = array_search('verifyReturnTime', array_column($systemconfig, 'systemconfig_enName'));
  1527. // 质检会话响应时长.
  1528. $verifyReturnTime = $systemconfig[$found_key]['systemconfig_data'];
  1529. $found_key = array_search('verifyAllTime', array_column($systemconfig, 'systemconfig_enName'));
  1530. // 质检会话时长.
  1531. $verifyAllTime = $systemconfig[$found_key]['systemconfig_data'];
  1532. // 差评次数.
  1533. $evaluateCount = 0;
  1534. // 未结束工单id.
  1535. $servicelog_ids = '';
  1536. $overtimeNumber = 0; // 会话超时次数.
  1537. $overtimeTime = []; // 会话超时时间.
  1538. $userSensitive = 0; // 用户敏感词报警次数.
  1539. $serverSensitive = 0; // 客服敏感词报警次数.
  1540. $csdNumber = 0; // 响应超时次数.
  1541. $csdTime = []; // 响应超时时间.
  1542. foreach ($serviceLog as $k => $v) {
  1543. // 工单报警总次数.
  1544. $allCount = 0;
  1545. // 差评次数.
  1546. if ($v['evaluate_id'] == 3) {
  1547. $evaluateCount++;
  1548. $allCount++;
  1549. }
  1550. $duration = time() - $v['start_time'];
  1551. // 会话超时.
  1552. if ($duration > $verifyAllTime) {
  1553. $overtimeNumber++;
  1554. $allCount++;
  1555. $overtimeTime[] = $duration;
  1556. }
  1557. // 敏感词报警.
  1558. $userSensitive += $v['alarm_userSensitive'];
  1559. $allCount += $v['alarm_userSensitive'];
  1560. $serverSensitive += $v['alarm_serverSensitive'];
  1561. $allCount += $v['alarm_serverSensitive'];
  1562. // 响应超时.
  1563. if ($v['alarm_corresponding'] > $verifyReturnTime) {
  1564. $csdTime[] = $v['alarm_corresponding'];
  1565. $csdNumber++;
  1566. $allCount++;
  1567. }
  1568. $serviceLog[$k]['allCount'] = $allCount;
  1569. }
  1570. // 查询对话时效设置.
  1571. foreach ($adminList as $v) {
  1572. $chat_message = [
  1573. 'message_type' => 'monitor',
  1574. 'data' => [
  1575. 'cvtList' => $serviceLog,
  1576. 'userSensitive' => $userSensitive,
  1577. 'serverSensitive' => $serverSensitive,
  1578. 'csdNumber' => $csdNumber,
  1579. 'csdTime' => $csdTime,
  1580. 'overtimeNumber' => $overtimeNumber,
  1581. 'overtimeTime' => $overtimeTime,
  1582. 'evaluateCount' => $evaluateCount,
  1583. ]
  1584. ];
  1585. Gateway::sendToClient($v, json_encode($chat_message, 256));
  1586. }
  1587. }
  1588. //客服在线状态写组
  1589. private static function writeLogKfStatus($kf, $status, $flag = 1)
  1590. {
  1591. if ($flag == 1) {
  1592. $status = intval($status);
  1593. if ($status == 0) {
  1594. self::$db->delete('ws_kfonline')->where("uid='$kf'")->query();
  1595. } else {
  1596. $now = date('Y-m-d H:i;s');
  1597. $sql = "insert into ws_kfonline(uid,status,uptime) values('$kf',$status,'$now') ON DUPLICATE KEY UPDATE status=$status,uptime='$now' ";
  1598. self::$db->query($sql);
  1599. }
  1600. } else {
  1601. self::$db->query("delete from ws_kfonline ");
  1602. }
  1603. }
  1604. //用户下线通知
  1605. private static function userCloseNotice($client_id, $cuid, $group)
  1606. {
  1607. }
  1608. //踢掉同一用户的旧用户
  1609. private static function tickOlduser($uid)
  1610. {
  1611. }
  1612. }