Events.php 79 KB

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