Events.php 82 KB

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