Events.php 75 KB

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