Events.php 79 KB

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