Events.php 80 KB

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