Events.php 79 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981
  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' 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_id]['client_id'], json_encode($del_message, 256));
  864. unset($del_message);
  865. $now = time();
  866. $sql = "update `ws_service_log` set `status`='2',end_time=$now where `servicelog_id`= '$servicelog_id'";
  867. self::$db->query($sql);
  868. // 修改会话时长
  869. $serviceLog = self::$db->query("select `start_time`,`intime` from `ws_service_log` where `servicelog_id`= '$servicelog_id'");
  870. $logCount = self::$db->query("select count(*) as `count` from `ws_chat_log` where `servicelog_id`= '$servicelog_id'");
  871. $alarmCount = $logCount[0]['count'];
  872. $cvtOvertime = time() - $serviceLog[0]['start_time'];
  873. $alarmLineTime = $serviceLog[0]['start_time'] - $serviceLog[0]['intime'];
  874. self::$db->query("update `ws_alarm` set `alarm_cvtOvertime` = '$cvtOvertime',`alarm_lineTime` = '$alarmLineTime',`alarm_count` = '$alarmCount'
  875. where `servicelog_id`= '$servicelog_id'");
  876. }
  877. /**
  878. * 客服结束会话
  879. * @param int $client_id 连接id
  880. *
  881. * tips: 当服务端主动退出的时候,会出现 exit status 9.原因是:服务端主动断开之后,连接的客户端会走这个方法,而短时间内进程
  882. * 需要处理这多的逻辑,又有cas操作,导致进程退出会超时,然后会被内核杀死,从而报出错误 9.实际对真正的业务没有任何的影响。
  883. */
  884. public static function serverClose($client_id, $servicelog_id, $userId, $kf_id, $groupId)
  885. {
  886. // 返回.
  887. $chat_message = [
  888. 'message_type' => 'closeBysever',
  889. 'data' => [
  890. 'content' => '客服停止了该会话',
  891. 'time' => date('H:i'),
  892. ]
  893. ];
  894. Gateway::sendToClient($client_id, json_encode($chat_message, 256));
  895. Gateway::closeClient($client_id);
  896. $now = time();
  897. $sql = "update `ws_service_log` set `status`='2',end_time=$now where `servicelog_id`= '$servicelog_id'";
  898. //echo "客户退出:". $sql ."\n";
  899. self::$db->query($sql);
  900. $isServiceUserOut = false;
  901. $noticeIs = 0;
  902. $userToKf = $userToKfNew = self::$global->userToKf;
  903. $kfList = $userToKfNew = self::$global->kfList;
  904. $del_message = [
  905. 'message_type' => 'delUser',
  906. 'data' => [
  907. 'id' => $userId
  908. ]
  909. ];
  910. Gateway::sendToClient($kfList[$groupId][$kf_id]['client_id'], json_encode($del_message, 256));
  911. unset($del_message);
  912. // 删除关联.
  913. if (isset($userToKfNew[$userId])) {
  914. unset($userToKfNew[$userId]);
  915. do {
  916. } while (!self::$global->cas('userToKf', $userToKf, $userToKfNew));
  917. }
  918. // 修改会话时长
  919. $serviceLog = self::$db->query("select `start_time`,`intime` from `ws_service_log` where `servicelog_id`= '$servicelog_id'");
  920. $logCount = self::$db->query("select count(*) as `count` from `ws_chat_log` where `servicelog_id`= '$servicelog_id'");
  921. $alarmCount = $logCount[0]['count'];
  922. $cvtOvertime = time() - $serviceLog[0]['start_time'];
  923. $alarmLineTime = $serviceLog[0]['start_time'] - $serviceLog[0]['intime'];
  924. self::$db->query("update `ws_alarm` set `alarm_cvtOvertime` = '$cvtOvertime',`alarm_lineTime` = '$alarmLineTime',`alarm_count` = '$alarmCount'
  925. where `servicelog_id`= '$servicelog_id'");
  926. // 将会员服务信息,从客服的服务列表中移除
  927. $old = $kfList = self::$global->kfList;
  928. foreach ($kfList as $k => $v) {
  929. foreach ($v as $key => $vo) {
  930. if (in_array($client_id, $vo['user_info'])) {
  931. $isServiceUserOut = true;
  932. // 根据client id 去更新会话工单一些信息
  933. self::$db->query("update `ws_service_log` set `end_time` = " . time() . " , `status` = '2' where `client_id`= '" . $client_id . "'");
  934. // 从会员的内存表中检索出该会员的信息,并更新内存
  935. $oldSimple = $simpleList = self::$global->uidSimpleList;
  936. $outUser = [];
  937. foreach ($simpleList as $u => $c) {
  938. if ($c['0'] == $client_id) {
  939. $outUser[] = [
  940. 'user_id' => $u,
  941. 'group_id' => $c['1']
  942. ];
  943. unset($simpleList[$u]);
  944. break;
  945. }
  946. }
  947. while (!self::$global->cas('uidSimpleList', $oldSimple, $simpleList)) {
  948. };
  949. unset($oldSimple, $simpleList);
  950. $outUser = self::$db->query("select `user_id`,`group_id` from `ws_service_log` where `client_id`= '" . $client_id . "'");
  951. // 通知 客服删除退出的用户
  952. if (!empty($outUser)) {
  953. // 尝试分配新会员进入服务
  954. self::userOfflineTask($outUser['0']['group_id']);
  955. }
  956. unset($outUser);
  957. // 维护现在的该客服的服务信息
  958. $kfList[$k][$key]['task'] -= 1; // 当前服务的人数 -1
  959. foreach ($vo['user_info'] as $m => $l) {
  960. if ($client_id == $l) {
  961. unset($kfList[$k][$key]['user_info'][$m]);
  962. break;
  963. }
  964. }
  965. // 刷新内存中客服的服务列表
  966. while (!self::$global->cas('kfList', $old, $kfList)) {
  967. };
  968. unset($old, $kfList);
  969. break;
  970. }
  971. }
  972. if ($isServiceUserOut) break;
  973. }
  974. // 尝试从排队的用户中删除退出的客户端
  975. if (false == $isServiceUserOut) {
  976. $old = $userList = self::$global->userList;
  977. foreach (self::$global->userList as $key => $vo) {
  978. if ($client_id == $vo['client_id']) {
  979. $isServiceUserOut = true;
  980. unset($userList[$key]);
  981. break;
  982. }
  983. }
  984. while (!self::$global->cas('userList', $old, $userList)) {
  985. };
  986. // 从会员的内存表中检索出该会员的信息,并更新内存
  987. $oldSimple = $simpleList = self::$global->uidSimpleList;
  988. foreach ($simpleList as $u => $c) {
  989. if ($c['0'] == $client_id) {
  990. unset($simpleList[$u]);
  991. break;
  992. }
  993. }
  994. while (!self::$global->cas('uidSimpleList', $oldSimple, $simpleList)) {
  995. };
  996. unset($oldSimple, $simpleList);
  997. }
  998. // 尝试是否是客服退出
  999. if (false == $isServiceUserOut) {
  1000. $old = $kfList = self::$global->kfList;
  1001. foreach (self::$global->kfList as $k => $v) {
  1002. foreach ($v as $key => $vo) {
  1003. // 客服服务列表中无数据,才去删除客服内存信息
  1004. if ($client_id == $vo['client_id'] && (0 == count($vo['user_info']))) {
  1005. unset($kfList[$k][$key]);
  1006. break;
  1007. }
  1008. }
  1009. }
  1010. while (!self::$global->cas('kfList', $old, $kfList)) {
  1011. };
  1012. }
  1013. }
  1014. /**
  1015. * 有人退出
  1016. * @param $group
  1017. */
  1018. private static function userOfflineTask($group)
  1019. {
  1020. // TODO 此处查询最大的可服务人数,后面可以用其他的方式,存储这个数值,让其更高效的访问
  1021. $maxNumber = self::getMaxServiceNum();
  1022. $res = self::assignmentTask(self::$global->kfList, self::$global->userList, $group, $maxNumber);
  1023. unset($maxNumber);
  1024. if (1 == $res['code']) {
  1025. while (!self::$global->cas('kfList', self::$global->kfList, $res['data']['4'])) {
  1026. }; // 更新客服数据
  1027. while (!self::$global->cas('userList', self::$global->userList, $res['data']['5'])) {
  1028. }; // 更新会员数据
  1029. // 服务信息入库
  1030. $serviceLog = [
  1031. 'user_id' => $res['data']['3']['id'],
  1032. 'client_id' => $res['data']['3']['client_id'],
  1033. 'user_name' => $res['data']['3']['name'],
  1034. 'user_ip' => $res['data']['3']['ip'],
  1035. 'user_avatar' => $res['data']['3']['avatar'],
  1036. 'kf_id' => intval(ltrim($res['data']['0'], 'KF')),
  1037. 'start_time' => time(),
  1038. 'group_id' => $group,
  1039. 'website' => $res['data']['3']['website'],
  1040. 'system' => $res['data']['3']['system'],
  1041. 'browse' => $res['data']['3']['browse'],
  1042. 'status' => 1,
  1043. 'intime' => $res['data']['3']['intime'],
  1044. 'end_time' => 0
  1045. ];
  1046. $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();
  1047. if (!$hisSession) {
  1048. $conversationId = self::$db->insert('ws_service_log')->cols($serviceLog)->query();
  1049. } else {
  1050. self::$db->update('ws_service_log')->cols(['status' => 1])->where('servicelog_id=' . $hisSession['servicelog_id'])->query();
  1051. $conversationId = $hisSession['servicelog_id'];
  1052. }
  1053. unset($serviceLog);
  1054. // 通知会员发送信息绑定客服的id
  1055. $noticeUser = [
  1056. 'message_type' => 'connect',
  1057. 'data' => [
  1058. 'kf_id' => $res['data']['0'],
  1059. 'kf_name' => $res['data']['1'],
  1060. 'conversationId' => $conversationId,
  1061. 'serverInfo' => self::$global->kfList[$group][$res['data']['0']],
  1062. ]
  1063. ];
  1064. Gateway::sendToClient($res['data']['3']['client_id'], json_encode($noticeUser, 256));
  1065. unset($noticeUser);
  1066. // 通知客服端绑定会员的信息
  1067. $noticeKf = [
  1068. 'message_type' => 'connect',
  1069. 'data' => [
  1070. 'user_info' => $res['data']['3'],
  1071. 'conversationId' => $conversationId,
  1072. ]
  1073. ];
  1074. Gateway::sendToClient($res['data']['2'], json_encode($noticeKf, 256));
  1075. unset($noticeKf);
  1076. // 逐一通知
  1077. $number = 1;
  1078. foreach (self::$global->userList as $vo) {
  1079. $waitMsg = '您前面还有 ' . $number . ' 位会员在等待。';
  1080. $waitMessage = [
  1081. 'message_type' => 'wait',
  1082. 'data' => [
  1083. 'content' => $waitMsg,
  1084. ]
  1085. ];
  1086. Gateway::sendToClient($vo['client_id'], json_encode($waitMessage, 256));
  1087. $number++;
  1088. }
  1089. unset($waitMessage, $number);
  1090. // 写入接入值
  1091. $key = date('Ymd') . 'success_in';
  1092. self::$global->$key = 0;
  1093. do {
  1094. $oldKey = date('Ymd', strtotime('-1 day')); // 删除前一天的统计值
  1095. unset(self::$global->$oldKey);
  1096. } while (!self::$global->increment($key));
  1097. unset($key);
  1098. } else {
  1099. switch ($res['code']) {
  1100. case -1:
  1101. $waitMsg = '暂时没有客服上班,请稍后再咨询。';
  1102. // 逐一通知
  1103. foreach (self::$global->userList as $vo) {
  1104. $waitMessage = [
  1105. 'message_type' => 'wait',
  1106. 'data' => [
  1107. 'content' => $waitMsg,
  1108. ]
  1109. ];
  1110. Gateway::sendToClient($vo['client_id'], json_encode($waitMessage, 256));
  1111. }
  1112. break;
  1113. case -2:
  1114. $waitMsg = '暂时没有客服上班,请稍后再咨询。';
  1115. // 逐一通知
  1116. foreach (self::$global->userList as $vo) {
  1117. $waitMessage = [
  1118. 'message_type' => 'wait',
  1119. 'data' => [
  1120. 'content' => $waitMsg,
  1121. ]
  1122. ];
  1123. Gateway::sendToClient($vo['client_id'], json_encode($waitMessage, 256));
  1124. }
  1125. break;
  1126. case -3:
  1127. $waitMsg = '暂时没有客服上班,请稍后再咨询。';
  1128. // 逐一通知
  1129. foreach (self::$global->userList as $vo) {
  1130. $waitMessage = [
  1131. 'message_type' => 'wait',
  1132. 'data' => [
  1133. 'content' => $waitMsg,
  1134. ]
  1135. ];
  1136. Gateway::sendToClient($vo['client_id'], json_encode($waitMessage, 256));
  1137. }
  1138. break;
  1139. case -4:
  1140. // 逐一通知
  1141. $number = 1;
  1142. foreach (self::$global->userList as $vo) {
  1143. $waitMsg = '您前面还有 ' . $number . ' 位会员在等待。';
  1144. $waitMessage = [
  1145. 'message_type' => 'wait',
  1146. 'data' => [
  1147. 'content' => $waitMsg,
  1148. ]
  1149. ];
  1150. Gateway::sendToClient($vo['client_id'], json_encode($waitMessage, 256));
  1151. $number++;
  1152. }
  1153. break;
  1154. }
  1155. unset($waitMessage, $number);
  1156. }
  1157. }
  1158. /**
  1159. * 有人进入执行分配
  1160. * @param $client_id
  1161. * @param $group
  1162. * @param $uid
  1163. */
  1164. private static function userOnlineTask($client_id, $group, $uid = 0)
  1165. {
  1166. // TODO 此处查询最大的可服务人数,后面可以用其他的方式,存储这个数值,让其更高效的访问
  1167. $maxNumber = self::getMaxServiceNum();
  1168. $res = self::assignmentTask(self::$global->kfList, self::$global->userList, $group, $maxNumber, $uid);
  1169. unset($maxNumber);
  1170. if (1 == $res['code']) {
  1171. while (!self::$global->cas('kfList', self::$global->kfList, $res['data']['4'])) {
  1172. }; // 更新客服数据
  1173. while (!self::$global->cas('userList', self::$global->userList, $res['data']['5'])) {
  1174. }; // 更新会员数据
  1175. $userToKf = self::$global->userToKf;
  1176. $userToKf[$res['data']['3']['id']] = [
  1177. $res['data']['3']['id'],
  1178. $res['data']['0']
  1179. ];
  1180. self::$global->userToKf = $userToKf;
  1181. // 服务信息入库
  1182. $serviceLog = [
  1183. 'user_id' => $res['data']['3']['id'],
  1184. 'client_id' => $res['data']['3']['client_id'],
  1185. 'user_name' => $res['data']['3']['name'],
  1186. 'user_ip' => $res['data']['3']['ip'],
  1187. 'user_avatar' => $res['data']['3']['avatar'],
  1188. 'kf_id' => intval(ltrim($res['data']['0'], 'KF')),
  1189. 'start_time' => time(),
  1190. 'group_id' => $group,
  1191. 'website' => $res['data']['3']['website'],
  1192. 'system' => $res['data']['3']['system'],
  1193. 'browse' => $res['data']['3']['browse'],
  1194. 'status' => 1,
  1195. 'intime' => $res['data']['3']['intime'],
  1196. 'end_time' => 0
  1197. ];
  1198. $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();
  1199. if (!$hisSession) {
  1200. $conversationId = self::$db->insert('ws_service_log')->cols($serviceLog)->query();
  1201. $alarmData = [
  1202. 'servicelog_id' => $conversationId,
  1203. ];
  1204. self::$db->insert('ws_alarm')->cols($alarmData)->query();
  1205. } else {
  1206. self::$db->update('ws_service_log')->cols(['status' => 1])->where('servicelog_id=' . $hisSession['servicelog_id'])->query();
  1207. $conversationId = $hisSession['servicelog_id'];
  1208. }
  1209. unset($serviceLog);
  1210. // 通知会员发送信息绑定客服的id
  1211. $noticeUser = [
  1212. 'message_type' => 'connect',
  1213. 'data' => [
  1214. 'kf_id' => $res['data']['0'],
  1215. 'conversationId' => $conversationId,
  1216. 'serverInfo' => self::$global->kfList[$group][$res['data']['0']],
  1217. 'kf_name' => $res['data']['1']
  1218. ]
  1219. ];
  1220. Gateway::sendToClient($client_id, json_encode($noticeUser, 256));
  1221. unset($noticeUser);
  1222. // 发送客服欢迎语
  1223. $sayHello = self::$db->query('select `word`,`status` from `ws_reply` where `id` = 2');
  1224. if (!empty($sayHello) && 1 == $sayHello['0']['status']) {
  1225. $chat_message = [
  1226. 'message_type' => 'chatMessage',
  1227. 'data' => [
  1228. 'name' => $res['data']['1'],
  1229. //'avatar' => self::$global->kfList[$group][$res['data']['0']],
  1230. 'id' => $res['data']['0'],
  1231. 'time' => date('H:i'),
  1232. 'content' => $sayHello['0']['word']
  1233. ]
  1234. ];
  1235. Gateway::sendToClient($client_id, json_encode($chat_message, 256));
  1236. unset($chat_message);
  1237. }
  1238. unset($sayHello);
  1239. // 通知客服端绑定会员的信息
  1240. $noticeKf = [
  1241. 'message_type' => 'connect',
  1242. 'data' => [
  1243. 'user_info' => $res['data']['3'],
  1244. 'conversationId' => $conversationId,
  1245. ]
  1246. ];
  1247. Gateway::sendToClient($res['data']['2'], json_encode($noticeKf, 256));
  1248. unset($noticeKf);
  1249. // 写入接入值
  1250. $key = date('Ymd') . 'success_in';
  1251. self::$global->$key = 0;
  1252. do {
  1253. $oldKey = date('Ymd', strtotime('-1 day')); // 删除前一天的统计值
  1254. unset(self::$global->$oldKey);
  1255. } while (!self::$global->increment($key));
  1256. unset($key);
  1257. } else {
  1258. $waitMsg = '';
  1259. switch ($res['code']) {
  1260. case -1:
  1261. $waitMsg = '暂时没有客服上班,请稍后再咨询。';
  1262. Gateway::sendToClient($client_id, json_encode(['message_type' => "notice", 'content' => $waitMsg], 256));
  1263. Gateway::closeClient($client_id);
  1264. return;
  1265. break;
  1266. case -2:
  1267. break;
  1268. case -3:
  1269. break;
  1270. case -4:
  1271. $number = count(self::$global->userList);
  1272. $waitMsg = '您前面还有 ' . $number . ' 位会员在等待。';
  1273. break;
  1274. }
  1275. $waitMessage = [
  1276. 'message_type' => 'wait',
  1277. 'data' => [
  1278. 'content' => $waitMsg,
  1279. ]
  1280. ];
  1281. Gateway::sendToClient($client_id, json_encode($waitMessage, 256));
  1282. unset($waitMessage);
  1283. }
  1284. $userlist = self::$global->userList;
  1285. $waitcount = 0;
  1286. if ($userlist) {
  1287. foreach ($userlist as $val) {
  1288. if ($val['group'] == $group) {
  1289. $waitcount++;
  1290. }
  1291. }
  1292. Gateway::sendToGroup('group_' . $group, json_encode(['message_type' => 'kfqueuelength', 'leng' => $waitcount], 256));
  1293. self::todayqueuelength();
  1294. }
  1295. }
  1296. //今天排序累加
  1297. private static function todayqueuelength()
  1298. {
  1299. $dtype = 'user.queue.day.length';
  1300. $today = date("Y-m-d");
  1301. $sret = self::$db->select('*')->from('ws_countmidtable')->where('dtype=:dtype and mdate=:mdate')->bindValues(array('dtype' => $dtype, 'mdate' => $today))->row();
  1302. if ($sret) {
  1303. self::$db->update('ws_countmidtable')->cols(array('dcontent' => intval($sret['dcontent']) + 1))->where('id=' . $sret['id'])->query();
  1304. } else {
  1305. self::$db->insert('ws_countmidtable')->cols(array(
  1306. 'dtype' => $dtype,
  1307. 'mdate' => $today,
  1308. 'datatype' => 1,
  1309. 'dcontent' => 1))->query();
  1310. }
  1311. }
  1312. //客服工单转单
  1313. private static function servicetrutoother($type, $owen, $otherkfid, $serverid, $clientuid)
  1314. {
  1315. $db->insert('ws_serviceturn_log')->cols(array(
  1316. 'stype' => $type,
  1317. 'uid' => $owen,
  1318. 'tuid' => $otherkfid,
  1319. 'serverid' => $serverid,
  1320. 'guestuid' => $clientuid
  1321. ))->query();
  1322. }
  1323. /**
  1324. * 给客服分配会员【均分策略】
  1325. * @param $kfList
  1326. * @param $userList
  1327. * @param $group
  1328. * @param $total
  1329. */
  1330. private static function assignmentTask($kfList, $userList, $group, $total, $uid = 0)
  1331. {
  1332. // 注:修改为已上线(status为1上线status为2不接受分配)
  1333. $onlineKF = [];
  1334. foreach ($kfList as $k => $v) {
  1335. foreach ($v as $ke => $va) {
  1336. if ($va['status'] == 1) {
  1337. $onlineKF[$k][$ke] = $va;
  1338. }
  1339. }
  1340. }
  1341. // 没有客服上线
  1342. if (empty($onlineKF) || empty($onlineKF[$group])) {
  1343. return ['code' => -1];
  1344. }
  1345. // 没有待分配的会员
  1346. if (empty($userList)) {
  1347. return ['code' => -2];
  1348. }
  1349. // 未设置每个客服可以服务多少人
  1350. if (0 == $total) {
  1351. return ['code' => -3];
  1352. }
  1353. // 查看该组的客服是否在线
  1354. if (!isset($onlineKF[$group])) {
  1355. return ['code' => -1];
  1356. }
  1357. //上次用户掉线后,还可以继续上一次 (如果没有关闭) 的会话 --1
  1358. $odltalksession = false;
  1359. $user = $user_first = array_shift($userList);
  1360. if ($uid > 0 && $user['id'] != $uid && count($userList) > 1) {
  1361. $timevalielimit = time() - 60 * 5;
  1362. $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();
  1363. if ($odltalksession) {
  1364. foreach ($userList as $ttkey => $ttval) {
  1365. if ($ttval['id'] == $uid) {
  1366. array_unshift($userList, $user);
  1367. $user = $userList[$ttkey];
  1368. unset($userList[$ttkey]);
  1369. break;
  1370. }
  1371. }
  1372. }
  1373. }
  1374. //上次用户掉线后,还可以继续上一次 (如果没有关闭) 的会话 --2
  1375. if ($odltalksession) {
  1376. $oldkrid = 'KF' . $odltalksession['kf_id'];
  1377. if (isset($onlineKF[$group][$oldkrid])) {
  1378. $kf = $onlineKF[$group][$oldkrid];
  1379. $min = $kf['task'];
  1380. $flag = $kf['id'];
  1381. unset($onlineKF[$group][$oldkrid]);
  1382. } else {
  1383. goto NOSIGNKF;
  1384. }
  1385. } else {
  1386. NOSIGNKF:
  1387. $kf = $onlineKF[$group];
  1388. $kf = array_shift($kf);
  1389. $min = $kf['task'];
  1390. $flag = $kf['id'];
  1391. foreach ($onlineKF[$group] as $key => $vo) {
  1392. if ($vo['task'] < $min) {
  1393. $min = $vo['task'];
  1394. $flag = $key;
  1395. }
  1396. }
  1397. unset($kf);
  1398. }
  1399. // 需要排队了
  1400. if ($onlineKF[$group][$flag]['task'] == $total) {
  1401. array_unshift($userList, $user);
  1402. return ['code' => -4];
  1403. }
  1404. $kfList[$group][$flag]['task'] += 1;
  1405. array_push($kfList[$group][$flag]['user_info'], $user['client_id']); // 被分配的用户信息
  1406. return [
  1407. 'code' => 1,
  1408. 'data' => [
  1409. $onlineKF[$group][$flag]['id'],
  1410. $onlineKF[$group][$flag]['name'],
  1411. $onlineKF[$group][$flag]['client_id'],
  1412. $user,
  1413. $kfList,
  1414. $userList
  1415. ]
  1416. ];
  1417. }
  1418. /**
  1419. * 获取最大的服务人数
  1420. * @return int
  1421. */
  1422. private static function getMaxServiceNum()
  1423. {
  1424. $maxNumber = self::$db->query('select `max_service` from `ws_kf_config` where `id` = 1');
  1425. if (!empty($maxNumber)) {
  1426. $maxNumber = 5;
  1427. } else {
  1428. $maxNumber = $maxNumber['0']['max_service'];
  1429. }
  1430. return $maxNumber;
  1431. }
  1432. /**
  1433. * 将内存中的数据写入统计表
  1434. * @param int $flag
  1435. */
  1436. private static function writeLog($flag = 1)
  1437. {
  1438. // 上午 8点 到 22 点开始统计
  1439. if (date('H') < 8 || date('H') > 22) {
  1440. return;
  1441. }
  1442. // 当前正在接入的人 和 在线客服数
  1443. $kfList = self::$global->kfList;
  1444. $nowTalking = 0;
  1445. $onlineKf = 0;
  1446. if (!empty($kfList)) {
  1447. foreach ($kfList as $key => $vo) {
  1448. $onlineKf += count($vo);
  1449. foreach ($vo as $k => $v) {
  1450. $nowTalking += count($v['user_info']);
  1451. }
  1452. }
  1453. }
  1454. // 在队列中的用户
  1455. $inQueue = count(self::$global->userList);
  1456. $key = date('Ymd') . 'total_in';
  1457. $key2 = date('Ymd') . 'success_in';
  1458. $param = [
  1459. 'is_talking' => $nowTalking,
  1460. 'in_queue' => $inQueue,
  1461. 'online_kf' => $onlineKf,
  1462. 'success_in' => self::$global->$key2,
  1463. 'total_in' => self::$global->$key,
  1464. 'now_date' => date('Y-m-d')
  1465. ];
  1466. self::$db->update('ws_now_data')->cols($param)->where('id=1')->query();
  1467. if (2 == $flag) {
  1468. $param = [
  1469. 'is_talking' => $nowTalking,
  1470. 'in_queue' => $inQueue,
  1471. 'online_kf' => $onlineKf,
  1472. 'success_in' => self::$global->$key2,
  1473. 'total_in' => self::$global->$key,
  1474. 'add_date' => date('Y-m-d'),
  1475. 'add_hour' => date('H'),
  1476. 'add_minute' => date('i'),
  1477. ];
  1478. self::$db->insert('ws_service_data')->cols($param)->query();
  1479. }
  1480. unset($kfList, $nowTalking, $inQueue, $onlineKf, $key, $key2, $param);
  1481. }
  1482. /**
  1483. * 机器人问答
  1484. * @param $client_id 服务ID
  1485. * @param $message 数据
  1486. */
  1487. private static function toRobot($client_id, $message)
  1488. {
  1489. $groups_id = $message['data']['groups_id'];
  1490. $robot_name = $message['data']['robot_name'];
  1491. $robotgroups_id = $message['data']['robotgroups_id'];
  1492. // 查询问题.
  1493. $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 . "'");
  1494. $chat_message = [
  1495. 'message_type' => 'robotMessage',
  1496. //'message_type' => 'chatMessage',
  1497. 'data' => [
  1498. 'name' => '智能助手',
  1499. 'time' => date('H:i'),
  1500. 'content' => $getRobot ? $getRobot[0]['robot_content'] : 'error',
  1501. ]
  1502. ];
  1503. sleep(1);
  1504. Gateway::sendToClient($client_id, json_encode($chat_message, 256));
  1505. }
  1506. /**
  1507. * 评价
  1508. * @param $client_id 服务ID
  1509. * @param $message 数据
  1510. */
  1511. private static function evaluate($client_id, $message)
  1512. {
  1513. // 修改数据库.
  1514. $evaluate_id = $message['data']['evaluate_id'];
  1515. $result = self::$db->query("UPDATE `ws_service_log` SET `evaluate_id` = '" . $evaluate_id . "' WHERE `client_id`='" . $client_id . "'");
  1516. if ($result) {
  1517. $chat_message = [
  1518. 'message_type' => 'evaluate',
  1519. 'data' => [
  1520. 'status' => 1,
  1521. 'time' => date('H:i'),
  1522. ]
  1523. ];
  1524. } else {
  1525. $chat_message = [
  1526. 'message_type' => 'evaluate',
  1527. 'data' => [
  1528. 'status' => 2,
  1529. 'time' => date('H:i'),
  1530. ]
  1531. ];
  1532. }
  1533. Gateway::sendToClient($client_id, json_encode($chat_message, 256));
  1534. }
  1535. //获取系统配置
  1536. private static function upsystemconfig()
  1537. {
  1538. $systemConfigData = self::$db->query("SELECT * FROM `ws_systemconfig`");
  1539. $arr = [];
  1540. if ($systemConfigData) {
  1541. foreach ($systemConfigData as $item) {
  1542. $arr[$item['systemconfig_enName']] = $item;
  1543. }
  1544. self::$global->systemconfig = $arr;
  1545. }
  1546. $group = self::$db->query("SELECT * FROM `ws_groups`");
  1547. $arr = [];
  1548. if ($group) {
  1549. foreach ($group as $val) {
  1550. $arr[$val['id']] = $val['name'];
  1551. }
  1552. self::$global->groupmap = $arr;
  1553. }
  1554. }
  1555. /**
  1556. * 超时
  1557. * @param $client_id 服务ID
  1558. * @param $message 数据
  1559. */
  1560. private static function overTime()
  1561. {
  1562. // 查询对话时效设置.
  1563. $systemConfigData = self::$db->query("SELECT `systemconfig_data`,`systemconfig_enName`,`systemconfig_content` FROM `ws_systemconfig`");
  1564. foreach ($systemConfigData as $k => $v) {
  1565. if ($v['systemconfig_enName'] == 'overtime') {
  1566. self::$global->overtime = $v;
  1567. } elseif ($v['systemconfig_enName'] == 'unoperated') {
  1568. self::$global->unoperated = $v;
  1569. } elseif ($v['systemconfig_enName'] == 'noResponse') {
  1570. self::$global->noResponse = $v;
  1571. }
  1572. }
  1573. // 查询未断开的工单.
  1574. $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'");
  1575. $whereOr = '1=0';
  1576. foreach ($serviceLog as $k => $v) {
  1577. if ($k == 0) {
  1578. $whereOr = "`servicelog_id`=" . $v['servicelog_id'];
  1579. } else {
  1580. $whereOr .= " OR `servicelog_id`=" . $v['servicelog_id'];
  1581. }
  1582. }
  1583. // 查询最后一次会话.
  1584. //$chatLog = self::$db->query("SELECT `servicelog_id`,MAX(`time_line`) FROM `ws_chat_log` WHERE ".$whereOr." group by `servicelog_id`");
  1585. $chatLog = self::$db->query("
  1586. select * from ws_chat_log as a where time_line=(
  1587. select max(b.time_line) from ws_chat_log as b where a.servicelog_id = b.servicelog_id and (" . $whereOr . ") group by servicelog_id
  1588. )
  1589. ");
  1590. $setOvertime = strtotime('-' . (self::$global->overtime['systemconfig_data'] - 60) . ' second');
  1591. $overtime = strtotime('-' . (self::$global->overtime['systemconfig_data']) . ' second');
  1592. $setUnoperated = strtotime('-' . (self::$global->unoperated['systemconfig_data'] - 60) . ' second');
  1593. $unoperated = strtotime('-' . (self::$global->unoperated['systemconfig_data']) . ' second');
  1594. $noResponse = strtotime('-' . (self::$global->noResponse['systemconfig_data']) . ' second');
  1595. foreach ($serviceLog as $k => $v) {
  1596. // 会话超时关闭.
  1597. if ($v['start_time'] <= $overtime) {
  1598. $servicelog_id = $v['servicelog_id'];
  1599. self::$db->query("update `ws_service_log` set `servicelog_close_type` = 2 where `servicelog_id`= '$servicelog_id'");
  1600. self::serverClose($v['client_id'], $servicelog_id, $v['user_id'], 'KF' . $v['kf_id'], $v['group_id']);
  1601. // 如果小于设定时间前一分钟则给出提示.
  1602. } elseif ($v['start_time'] <= $setOvertime) {
  1603. $chat_message = [
  1604. 'message_type' => 'overtime',
  1605. 'data' => [
  1606. 'content' => self::$global->overtime['systemconfig_content'],
  1607. ]
  1608. ];
  1609. Gateway::sendToClient($v['client_id'], json_encode($chat_message, 256));
  1610. }
  1611. // 访客静默超时.
  1612. // 如果没有说一句话.
  1613. if (!strlen(array_search($v['servicelog_id'], array_column($chatLog, 'servicelog_id')))) {
  1614. if ($v['start_time'] <= $unoperated) {
  1615. $servicelog_id = $v['servicelog_id'];
  1616. self::$db->query("update `ws_service_log` set `servicelog_close_type` = 1 where `servicelog_id`= '$servicelog_id'");
  1617. self::serverClose($v['client_id'], $servicelog_id, $v['user_id'], 'KF' . $v['kf_id'], $v['group_id']);
  1618. // 如果小于设定时间前一分钟则给出提示.
  1619. } elseif ($v['start_time'] <= $setUnoperated) {
  1620. $chat_message = [
  1621. 'message_type' => 'overtime',
  1622. 'data' => [
  1623. 'content' => self::$global->unoperated['systemconfig_content'],
  1624. ]
  1625. ];
  1626. Gateway::sendToClient($v['client_id'], json_encode($chat_message, 256));
  1627. }
  1628. }
  1629. }
  1630. // 访客静默超时.如果说了话
  1631. foreach ($chatLog as $k => $v) {
  1632. // 如果对话为客服的最后一次对话且时间小于设定时间则结束工单.
  1633. if ($v['time_line'] <= $unoperated) {
  1634. $found_key = array_search($v['servicelog_id'], array_column($serviceLog, 'servicelog_id'));
  1635. $servicelog_id = $v['servicelog_id'];
  1636. self::$db->query("update `ws_service_log` set `servicelog_close_type` = 1 where `servicelog_id`= '$servicelog_id'");
  1637. 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']);
  1638. // 如果对话为客服的最后一次对话且时间小于设定时间前一分钟则给出提示.
  1639. } elseif ($v['time_line'] <= $setUnoperated) {
  1640. $chat_message = [
  1641. 'message_type' => 'overtime',
  1642. 'data' => [
  1643. 'content' => self::$global->overtime['systemconfig_content'],
  1644. ]
  1645. ];
  1646. $found_key = array_search($v['servicelog_id'], array_column($serviceLog, 'servicelog_id'));
  1647. Gateway::sendToClient($serviceLog[$found_key]['client_id'], json_encode($chat_message, 256));
  1648. }
  1649. }
  1650. }
  1651. /**
  1652. * 系统监控
  1653. * @param $message 数据
  1654. */
  1655. private static function systemMonitoring($adminList)
  1656. {
  1657. // 查询未结束工单.
  1658. $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
  1659. from `ws_service_log`
  1660. join `ws_alarm` on ws_service_log.servicelog_id=ws_alarm.servicelog_id
  1661. join `ws_users` on ws_service_log.kf_id=ws_users.id
  1662. WHERE ws_service_log.status='1' OR ws_service_log.status='3'");
  1663. // 查询系统设置表.
  1664. $systemconfig = self::$db->query("SELECT `systemconfig_data`,`systemconfig_enName` FROM `ws_systemconfig` WHERE `systemconfig_enName`='verifyReturnTime' or `systemconfig_enName`='verifyAllTime'");
  1665. $returnTimeKey = array_search('verifyReturnTime', array_column($systemconfig, 'systemconfig_enName'));
  1666. // 质检会话响应时长.
  1667. $verifyReturnTime = $systemconfig[$returnTimeKey]['systemconfig_data'];
  1668. $allTimeKey = array_search('verifyAllTime', array_column($systemconfig, 'systemconfig_enName'));
  1669. // 质检会话时长.
  1670. $verifyAllTime = $systemconfig[$allTimeKey]['systemconfig_data'];
  1671. // 差评次数.
  1672. $evaluateCount = 0;
  1673. // 未结束工单id.
  1674. $servicelog_ids = '';
  1675. $overtimeNumber = 0; // 会话超时次数.
  1676. $overtimeTime = []; // 会话超时时间.
  1677. $userSensitive = 0; // 用户敏感词报警次数.
  1678. $serverSensitive = 0; // 客服敏感词报警次数.
  1679. $csdNumber = 0; // 响应超时次数.
  1680. $csdTime = []; // 响应超时时间.
  1681. foreach ($serviceLog as $k => $v) {
  1682. // 工单报警总次数.
  1683. $allCount = 0;
  1684. // 差评次数.
  1685. if ($v['evaluate_id'] == 3) {
  1686. $evaluateCount++;
  1687. $allCount++;
  1688. }
  1689. $duration = time() - $v['start_time'];
  1690. // 会话超时.
  1691. if ($duration > $verifyAllTime) {
  1692. $overtimeNumber++;
  1693. $allCount++;
  1694. $overtimeTime[] = $duration;
  1695. }
  1696. // 敏感词报警.
  1697. $userSensitive += $v['alarm_userSensitive'];
  1698. $allCount += $v['alarm_userSensitive'];
  1699. $serverSensitive += $v['alarm_serverSensitive'];
  1700. $allCount += $v['alarm_serverSensitive'];
  1701. // 响应超时.
  1702. if ($v['alarm_corresponding'] > $verifyReturnTime) {
  1703. $csdTime[] = $v['alarm_corresponding'];
  1704. $csdNumber++;
  1705. $allCount++;
  1706. }
  1707. $serviceLog[$k]['allCount'] = $allCount;
  1708. }
  1709. // 查询对话时效设置.
  1710. foreach ($adminList as $v) {
  1711. $chat_message = [
  1712. 'message_type' => 'monitor',
  1713. 'data' => [
  1714. 'cvtList' => $serviceLog,
  1715. 'userSensitive' => $userSensitive,
  1716. 'serverSensitive' => $serverSensitive,
  1717. 'csdNumber' => $csdNumber,
  1718. 'csdTime' => $csdTime,
  1719. 'overtimeNumber' => $overtimeNumber,
  1720. 'overtimeTime' => $overtimeTime,
  1721. 'evaluateCount' => $evaluateCount,
  1722. ]
  1723. ];
  1724. Gateway::sendToClient($v, json_encode($chat_message, 256));
  1725. }
  1726. }
  1727. //客服在线状态写组
  1728. private static function writeLogKfStatus($kf, $status, $flag = 1)
  1729. {
  1730. if ($flag == 1) {
  1731. $status = intval($status);
  1732. if ($status == 0) {
  1733. self::$db->delete('ws_kfonline')->where("uid='$kf'")->query();
  1734. } else {
  1735. $now = date('Y-m-d H:i;s');
  1736. $sql = "insert into ws_kfonline(uid,status,uptime) values('$kf',$status,'$now') ON DUPLICATE KEY UPDATE status=$status,uptime='$now' ";
  1737. self::$db->query($sql);
  1738. }
  1739. } else {
  1740. self::$db->query("delete from ws_kfonline ");
  1741. }
  1742. }
  1743. //用户下线通知
  1744. private static function userCloseNotice($client_id, $cuid, $group)
  1745. {
  1746. }
  1747. //踢掉同一用户的旧用户
  1748. private static function tickOlduser($uid)
  1749. {
  1750. }
  1751. }