Events.php 75 KB

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