Events.php 79 KB

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