Events.php 63 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628
  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.186', '3306', 'root', '', '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. }
  100. /**
  101. * 每分钟定时向客服发送一次排队情况
  102. */
  103. public static function lineup()
  104. {
  105. $userlist = self::$global->userList;
  106. $kflist = self::$global->kfList;
  107. if (empty($userlist) || empty($kflist)) {
  108. return;
  109. }
  110. $return = [];
  111. foreach ($userlist as $val) {
  112. $return[$val['group']] = isset($return[$val['group']]) ? $return[$val['group']] + 1 : 1;
  113. }
  114. $krgroupclientid = [];
  115. foreach ($kflist as $gid => $sval) {
  116. foreach ($sval as $tval) {
  117. $krgroupclientid[$gid][] = $tval['client_id'];
  118. }
  119. }
  120. foreach ($return as $fgroup => $fval) {
  121. foreach ($krgroupclientid as $sikey => $sival) {
  122. if ($fgroup == $sikey) {
  123. Gateway::sendToClient($sival, json_encode(['type' => 'lineupCount', $fval], 256));
  124. }
  125. }
  126. }
  127. return;
  128. }
  129. /**
  130. * 当客户端连接时触发
  131. * 如果业务不需此回调可以删除onConnect
  132. *
  133. * @param int $client_id 连接id
  134. */
  135. public static function onConnect($client_id)
  136. {
  137. // 检测是否开启自动应答
  138. $sayHello = self::$db->query('select `word`,`status` from `ws_reply` where `id` = 1');
  139. if (!empty($sayHello) && 1 == $sayHello['0']['status']) {
  140. $hello = [
  141. 'message_type' => 'helloMessage',
  142. 'data' => [
  143. 'name' => '智能助手',
  144. 'time' => date('H:i'),
  145. 'content' => htmlspecialchars($sayHello['0']['word'])
  146. ]
  147. ];
  148. Gateway::sendToClient($client_id, json_encode($hello, 256));
  149. unset($hello);
  150. }
  151. unset($sayHello);
  152. // 检测是否开启广告
  153. $advertisement = self::$db->query('select `*` from `ws_advertisement` where `advertisement_status` = 1');
  154. if (!empty($advertisement)) {
  155. $chat_message = [
  156. 'message_type' => 'advertisement',
  157. 'data' => $advertisement
  158. ];
  159. Gateway::sendToClient($client_id, json_encode($chat_message, 256));
  160. unset($chat_message);
  161. }
  162. unset($advertisement);
  163. }
  164. /**
  165. * 当客户端发来消息时触发
  166. * @param int $client_id 连接id
  167. * @param mixed $message 具体消息
  168. */
  169. public static function onMessage($client_id, $message)
  170. {
  171. if ($message == '{"type":"ping"}' || $message == '{"type":"pong"}') {
  172. //Gateway::sendToCurrentClient('{"type":"pong"}');
  173. return;
  174. } else {
  175. echo "onMessage: " . $message . "\r\n";
  176. print_r([self::$global->kfList, self::$global->userList, self::$global->uidSimpleList, self::$global->userToKf]);
  177. }
  178. $message = json_decode($message, true);
  179. if (isset($message['type'])) {
  180. switch ($message['type']) {
  181. // 客服初始化
  182. case 'init':
  183. $data = $message['data'];
  184. self::Kfinit($client_id, $data);
  185. break;
  186. // 顾客初始化
  187. case 'userInit';
  188. $data = $message['data'];
  189. self::userInitEnt($client_id, $data);
  190. break;
  191. //在线客服信息
  192. case 'getkfonlines':
  193. Gateway::sendToCurrentClient(json_encode(self::getkfonlines(), 256));
  194. break;
  195. case 'chatMessage':
  196. $client = Gateway::getClientIdByUid($message['data']['to_id']);
  197. if (!empty($client)) {
  198. $chat_message = [
  199. 'message_type' => 'chatMessage',
  200. 'data' => [
  201. 'name' => $message['data']['from_name'],
  202. 'avatar' => $message['data']['from_avatar'],
  203. 'id' => $message['data']['from_id'],
  204. 'time' => date('H:i'),
  205. 'content' => htmlspecialchars($message['data']['content']),
  206. ]
  207. ];
  208. Gateway::sendToClient($client['0'], json_encode($chat_message));
  209. unset($chat_message);
  210. // 聊天信息入库
  211. $serviceLog = [
  212. 'from_id' => $message['data']['from_id'],
  213. 'from_name' => $message['data']['from_name'],
  214. 'from_avatar' => $message['data']['from_avatar'],
  215. 'to_id' => $message['data']['to_id'],
  216. 'to_name' => $message['data']['to_name'],
  217. 'content' => $message['data']['content'],
  218. 'servicelog_id' => $message['data']['conversationId'],
  219. 'time_line' => time()
  220. ];
  221. self::$db->insert('ws_chat_log')->cols($serviceLog)->query();
  222. unset($serviceLog);
  223. }
  224. break;
  225. // 转接
  226. case 'changeGroup':
  227. // 通知客户端转接中
  228. $simpleList = self::$global->uidSimpleList;
  229. if (!isset($simpleList[$message['uid']])) { // 客户已经退出
  230. return;
  231. }
  232. $userClient = $simpleList[$message['uid']]['0'];
  233. $userGroup = $simpleList[$message['uid']]['1']; // 会员原来的分组也是客服的分组
  234. $reLink = [
  235. 'message_type' => 'relinkMessage'
  236. ];
  237. Gateway::sendToClient($userClient, json_encode($reLink, 256));
  238. unset($reLink);
  239. // 记录该客服与该会员的服务结束
  240. self::$db->query("update `ws_service_log` set `end_time` = " . time() . " , `status` = '2' where `client_id`= '" . $userClient . "'");
  241. // 从当前客服的服务表中删除这个会员
  242. $old = $kfList = self::$global->kfList;
  243. if (!isset($kfList[$userGroup])) {
  244. $waitMsg = '暂时没有相关客服上班,请稍后再咨询。';
  245. // 逐一通知
  246. foreach (self::$global->userList as $vo) {
  247. $waitMessage = [
  248. 'message_type' => 'wait',
  249. 'data' => [
  250. 'content' => $waitMsg,
  251. ]
  252. ];
  253. Gateway::sendToClient($userClient, json_encode($waitMessage, 256));
  254. unset($waitMessage);
  255. }
  256. return;
  257. }
  258. $myList = $kfList[$userGroup]; // 该客服分组数组
  259. foreach ($myList as $key => $vo) {
  260. if (in_array($userClient, $vo['user_info'])) {
  261. // 维护现在的该客服的服务信息
  262. $kfList[$userGroup][$key]['task'] -= 1; // 当前服务的人数 -1
  263. foreach ($vo['user_info'] as $k => $v) {
  264. if ($userClient == $v) {
  265. unset($kfList[$userGroup][$key]['user_info'][$k]);
  266. break;
  267. }
  268. }
  269. break;
  270. }
  271. }
  272. while (!self::$global->cas('kfList', $old, $kfList)) {
  273. }; // 刷新内存中客服的服务列表
  274. unset($old, $kfList, $myList);
  275. // 将会员加入队列中
  276. $userList = self::$global->userList;
  277. do {
  278. $NewUserList = $userList;
  279. $NewUserList[$message['uid']] = [
  280. 'id' => $message['uid'],
  281. 'name' => $message['name'],
  282. 'avatar' => $message['avatar'],
  283. 'ip' => $message['ip'],
  284. 'group' => $message['group'], // 指定要链接的分组
  285. 'client_id' => $userClient
  286. ];
  287. } while (!self::$global->cas('userList', $userList, $NewUserList));
  288. unset($NewUserList, $userList);
  289. // 执行会员分配通知双方
  290. self::userOnlineTask($userClient, $message['group']);
  291. unset($userClient, $userGroup);
  292. break;
  293. case 'closeUser':
  294. $userInfo = self::$global->uidSimpleList;
  295. if (isset($userInfo[$message['uid']])) {
  296. $waitMessage = [
  297. 'message_type' => 'wait',
  298. 'data' => [
  299. 'content' => '暂时没有客服上班,请稍后再咨询。',
  300. ]
  301. ];
  302. Gateway::sendToClient($userInfo[$message['uid']]['0'], json_encode($waitMessage, 256));
  303. unset($waitMessage);
  304. }
  305. unset($userInfo);
  306. break;
  307. // 机器人问答.
  308. case 'toRobot':
  309. self::toRobot($client_id, $message);
  310. break;
  311. // 评价.
  312. case 'evaluate':
  313. self::evaluate($client_id, $message);
  314. break;
  315. // 客服关闭会话.
  316. case 'kfCloseUser':
  317. $client = Gateway::getClientIdByUid($userId);
  318. if (!empty($client)) {
  319. $userId = $message['data']['to_id'];
  320. $kfId = $message['data']['kf_id'];
  321. $groupId = $message['data']['group_id'];
  322. $clientId = $client['0'];
  323. $sql = "select 'servicelog_id' from `ws_service_log` where `user_id`= '$userId' and `client_id`= '$clientId' and `status`!= '2' and `group_id`!= '$groupId' and `kf_id`!= '$kfId'";
  324. $serviceLog = self::$db->query($sql);
  325. self::serverClose($clientId, $serviceLog[0]['servicelog_id']);
  326. }
  327. break;
  328. // 客服更改状态.
  329. case 'kfOnline':
  330. $kfList = self::$global->kfList;
  331. $userId = $message['data']['uid'];
  332. $status = $message['data']['status'];
  333. foreach ($kfList as $k => $v) {
  334. foreach ($v as $ke => $va) {
  335. if ($ke == $userId) {
  336. $kfList[$k][$ke]['status'] = $status;
  337. }
  338. }
  339. }
  340. self::$global->kfList = $kfList;
  341. self::writeLogKfStatus($userId, $status);
  342. break;
  343. case 'changeOtherhKeFu';
  344. self::changeOtherhKeFu($client_id, $message);
  345. break;
  346. // 弹出评价.
  347. case 'getEvaluate';
  348. $client = Gateway::getClientIdByUid($message['data']['to_id']);
  349. if (!empty($client)) {
  350. $chat_message = [
  351. 'message_type' => 'getEvaluate',
  352. 'data' => [
  353. 'content' => '欢迎你的咨询,请对我们的服务做出评价',
  354. ]
  355. ];
  356. Gateway::sendToClient($client['0'], json_encode($chat_message, 256));
  357. unset($chat_message);
  358. }
  359. }
  360. }
  361. }
  362. //获取在线客服列表
  363. public static function getkfonlines()
  364. {
  365. $return = [
  366. 'message_type' => 'onlinekfs',
  367. 'data' => [],
  368. ];
  369. $kfs = self::$global->kfList;
  370. if (!$kfs) {
  371. return $return;
  372. }
  373. $ret = [];
  374. foreach ($kfs as $gruop => $fs) {
  375. foreach ($fs as $kfid => $kfdata) {
  376. if ($kfdata['status'] == 1) {
  377. $ret[$gruop][] = ['id' => $kfid, 'name' => $kfdata['name'], 'job_member' => $kfdata['job_name'], 'avatar' => $kfdata['avatar'], 'signature' => $kfdata['signature']];
  378. }
  379. }
  380. }
  381. $return['data'] = $ret;
  382. return $return;
  383. }
  384. //客户工单内部组转接
  385. public static function changeOtherhKeFu($client_id, $smessage)
  386. {
  387. $message = $smessage['data'];
  388. $groupid = isset($message['group']) ? intval($message['group']) : 0;
  389. $toukfid = isset($message['toukfuid']) ? $message['toukfuid'] : 0;
  390. $fromkfuid = isset($message['fromkfuid']) ? $message['fromkfuid'] : 0;
  391. $uid = isset($message['uid']) ? $message['uid'] : 0;
  392. $word = isset($message['word']) ? $message['word'] : '';
  393. if (empty($groupid) || empty($toukfid) || empty($fromkfuid) || empty($uid) || empty($word) || ($toukfid == $fromkfuid)) {
  394. return false;
  395. }
  396. if (!Gateway::isUidOnline($toukfid) || !Gateway::isUidOnline($uid)) {
  397. return false;
  398. }
  399. $tokfidclientid = Gateway::getClientIdByUid($toukfid);
  400. $tokfidclientid = $tokfidclientid['0'];
  401. $uidclientid = Gateway::getClientIdByUid($uid);
  402. $uidclientid = $uidclientid['0'];
  403. $kfList = $kfList_new = self::$global->kfList;
  404. $userToKf = $userToKf_new = self::$global->userToKf;
  405. if (!isset($kfList[$groupid]) || !isset($kfList[$groupid][$toukfid]) || !isset($kfList[$groupid][$fromkfuid])) {
  406. return false;
  407. }
  408. if ($kfList[$groupid][$toukfid]['status'] != 1) {
  409. return false;
  410. }
  411. foreach ($kfList[$groupid] as $key => $val) {
  412. if ($key == $fromkfuid) {
  413. $kfList_new[$groupid][$fromkfuid]['task']--;
  414. foreach ($kfList[$groupid][$key]['user_info'] as $skey => $sval) {
  415. if ($sval == $uidclientid) {
  416. unset($kfList_new[$groupid][$key]['user_info'][$skey]);
  417. }
  418. }
  419. }
  420. if ($key == $toukfid) {
  421. $kfList_new[$groupid][$toukfid]['task']++;
  422. array_push($kfList_new[$groupid][$key]['user_info'], $uidclientid);
  423. }
  424. }
  425. do {
  426. } while (!self::$global->cas('kfList', $kfList, $kfList_new));
  427. if (isset($userToKf[$uid])) {
  428. $userToKf_new[$uid]['1'] = $toukfid;
  429. }
  430. do {
  431. } while (!self::$global->cas('userToKf', $userToKf, $userToKf_new));
  432. /////////取消原有会话,开启新会话
  433. $histarttimelimit = time() - 3600 * 24;
  434. $bindval = ['user_id' => $uid, 'client_id' => $uidclientid, 'kf_id' => intval(trim($fromkfuid, 'KF')), 'histime' => $histarttimelimit];
  435. $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();
  436. if (!$oldlog) {
  437. return false;
  438. }
  439. self::$db->update('ws_service_log')->cols(['status' => 2, 'end_time' => time()])->where('servicelog_id=' . $oldlog['servicelog_id'])->query();
  440. unset($oldlog['servicelog_id']);
  441. $oldlog = array_merge($oldlog, ['kf_id' => intval(trim($toukfid, 'KF')), 'start_time' => time(), 'end_time' => 0, 'status' => 1, 'evaluate_id' => 0]);
  442. $new_id = self::$db->insert('ws_service_log')->cols($oldlog)->query();
  443. if (!$new_id) {
  444. return false;
  445. }
  446. ///通知消息发送--------------
  447. // 通知会员发送信息绑定客服的id
  448. $noticeUser = [
  449. 'message_type' => 'connect',
  450. 'data' => [
  451. 'kf_id' => $toukfid,
  452. 'kf_name' => Gateway::getSession(Gateway::getClientIdByUid($toukfid)['0'])['name'],
  453. ]
  454. ];
  455. Gateway::sendToClient($uidclientid, json_encode($noticeUser, 256));
  456. unset($noticeUser);
  457. // 通知客服端绑定会员的信息
  458. $noticeKf = [
  459. 'message_type' => 'connect',
  460. 'data' => [
  461. 'user_info' => $uid
  462. ]
  463. ];
  464. Gateway::sendToClient($tokfidclientid, json_encode($noticeKf, 256));
  465. unset($noticeKf);
  466. //回转接人,转接成功
  467. Gateway::sendToCurrentClient(json_encode(['message_type' => 'trunconnect', 'data' => ['status' => 1], 256]));
  468. return;
  469. }
  470. //客服接入sock,及初始化
  471. public static function Kfinit($client_id, $message)
  472. {
  473. $kfList = self::$global->kfList;
  474. //客服登陆验证 不符合的直接断掉
  475. //$logcheck = true; //开发时使用
  476. $kfinfo = self::KfloginChedk($client_id, $message);
  477. if (empty($kfinfo)) {
  478. Gateway::sendToClient($client_id, json_encode(["message_type" => 'checkfalse', 'data' => "验证失败"], 256));
  479. Gateway::closeCurrentClient();
  480. return true;
  481. } elseif ($kfinfo['status'] != 1) {
  482. Gateway::sendToClient($client_id, json_encode(["message_type" => 'checkfalse', 'data' => "禁用中..."], 256));
  483. Gateway::closeCurrentClient();
  484. return true;
  485. }
  486. if (isset($kfList[$message['group']][$message['uid']])) {
  487. Gateway::sendToCurrentClient(json_encode(['type' => 'reLoginErr', 'msg' => '你的账号已经登陆过,请先退出再登陆'], 256));
  488. Gateway::closeCurrentClient();
  489. return;
  490. }
  491. // 如果该客服未在内存中记录则记录
  492. if (!isset($kfList[$message['group']]) || !array_key_exists($message['uid'], $kfList[$message['group']])) {
  493. do {
  494. $newKfList = $kfList;
  495. $newKfList[$message['group']][$message['uid']] = [
  496. 'id' => 'KF' . $kfinfo['id'],
  497. 'name' => $kfinfo['user_name'],
  498. 'job_name' => $kfinfo['user_job_number'],
  499. 'avatar' => $kfinfo['user_avatar'],
  500. 'client_id' => $client_id,
  501. 'task' => 0,
  502. 'signature' => $kfinfo['signature'],
  503. 'status' => 2,// 1为在线(接收分配、接收消息)2为隐身(不接收分配、只接收消息)
  504. 'user_info' => []
  505. ];
  506. } while (!self::$global->cas('kfList', $kfList, $newKfList));
  507. unset($newKfList, $kfList);
  508. } else if (isset($kfList[$message['group']][$message['uid']])) {
  509. do {
  510. $newKfList = $kfList;
  511. $newKfList[$message['group']][$message['uid']]['client_id'] = $client_id;
  512. } while (!self::$global->cas('kfList', $kfList, $newKfList));
  513. unset($newKfList, $kfList);
  514. }
  515. // 绑定 client_id 和 uid
  516. Gateway::bindUid($client_id, $message['uid']);
  517. $_SESSION['group'] = $message['group'];
  518. $_SESSION['iskefu'] = 1;
  519. $_SESSION['uid'] = $message['uid'];
  520. $_SESSION['name'] = $message['name'];
  521. Gateway::joinGroup($client_id, 'group_' . $message['group']);
  522. self::writeLogKfStatus($message['uid'], 2);
  523. // TODO 尝试拉取用户来服务 [二期规划]
  524. }
  525. //客服登陆验证
  526. public static function KfloginChedk($client, $messageArray)
  527. {
  528. $uid = isset($messageArray['uid']) ? $messageArray['uid'] : '';
  529. $token = isset($messageArray['token']) ? $messageArray['token'] : '';
  530. if (empty($uid) || empty($token)) {
  531. return false;
  532. }
  533. $expire_time_vali = time() - 60 * 60 * 24 * 3;
  534. $kfid = intval(substr($uid, 2));
  535. $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();
  536. if ($ret) {
  537. self::$db->update('ws_users')->cols(array('online_status' => 1, 'online_connectid' => $client))->where('id=' . $kfid)->query();
  538. return $ret;
  539. }
  540. return false;
  541. }
  542. //用户发送邦定用户事件
  543. public static function userInitEnt($client_id, $message)
  544. {
  545. $userList = self::$global->userList;
  546. // 如果该顾客未在内存中记录则记录
  547. $uidSimpleList = self::$global->uidSimpleList;
  548. if (isset($uidSimpleList[$message['uid']])) {
  549. $uidSimpleList = self::$global->uidSimpleList;
  550. $oldclientid = $uidSimpleList[$message['uid']]['0'];
  551. Gateway::sendToClient($oldclientid, json_encode(['type' => 'reLoginErr', 'msg' => '相同账号登陆,本次退出'], 256));
  552. Gateway::closeClient($oldclientid);
  553. sleep(2);
  554. }
  555. $group = $message['group'];
  556. $onlinekf = self::$global->kfList;
  557. if (!isset($onlinekf[$group]) || count($onlinekf[$group]) <= 0) {
  558. Gateway::sendToClient($client_id, json_encode(['message_type' => 'notice', 'content' => '暂时没有客服上班,请稍后再咨询。'], 256));
  559. sleep(2);
  560. Gateway::closeClient($client_id);
  561. return;
  562. }
  563. if (!array_key_exists($message['uid'], $userList)) {
  564. do {
  565. $NewUserList = $userList;
  566. $NewUserList[$message['uid']] = [
  567. 'id' => $message['uid'],
  568. 'name' => $message['name'],
  569. 'avatar' => $message['avatar'],
  570. 'website' => $_SESSION['origin'],//$_SERVER['HTTP_ORIGIN'],
  571. 'browse' => Gateway::browse_info(),
  572. 'system' => Gateway::get_os(),
  573. 'ip' => isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '',
  574. 'group' => $message['group'],
  575. 'intime' => time(),
  576. 'client_id' => $client_id
  577. ];
  578. } while (!self::$global->cas('userList', $userList, $NewUserList));
  579. unset($NewUserList, $userList);
  580. // 维护 UID对应的client_id 数组
  581. do {
  582. $old = $newList = self::$global->uidSimpleList;
  583. $newList[$message['uid']] = [
  584. $client_id,
  585. $message['group']
  586. ];
  587. } while (!self::$global->cas('uidSimpleList', $old, $newList));
  588. unset($old, $newList);
  589. // 写入接入值
  590. $key = date('Ymd') . 'total_in';
  591. self::$global->$key = 0;
  592. do {
  593. $oldKey = date('Ymd', strtotime('-1 day')); // 删除前一天的统计值
  594. unset(self::$global->$oldKey);
  595. } while (!self::$global->increment($key));
  596. unset($key);
  597. }
  598. // 绑定 client_id 和 uid
  599. Gateway::bindUid($client_id, $message['uid']);
  600. $_SESSION['iskefu'] = 0;
  601. $_SESSION['uid'] = $message['uid'];
  602. // 尝试分配新会员进入服务
  603. self::userOnlineTask($client_id, $message['group'], $message['uid']);
  604. }
  605. /**
  606. * 当用户断开连接时触发
  607. * @param int $client_id 连接id
  608. *
  609. * tips: 当服务端主动退出的时候,会出现 exit status 9.原因是:服务端主动断开之后,连接的客户端会走这个方法,而短时间内进程
  610. * 需要处理这多的逻辑,又有cas操作,导致进程退出会超时,然后会被内核杀死,从而报出错误 9.实际对真正的业务没有任何的影响。
  611. */
  612. public static function onClose($client_id)
  613. {
  614. $isKefuoff = isset($_SESSION['iskefu']) ? $_SESSION['iskefu'] : 0;
  615. $uid = isset($_SESSION['uid']) ? $_SESSION['uid'] : false;
  616. //echo "下线:$uid - $client_id - $isKefuoff \n";
  617. if (empty($uid)) {
  618. return;
  619. }
  620. if ($isKefuoff) {
  621. self::serviceOffline($client_id, $uid);
  622. } else {
  623. self::guestOffline($client_id, $uid);
  624. }
  625. return;
  626. }
  627. //客服下线了
  628. public static function serviceOffline($client_id, $uid)
  629. {
  630. $group = $_SESSION['group'];
  631. $kefuinfo_old = $kefuinfo_old_new = self::$global->kfList;
  632. $user_info = $kefuinfo_old_new[$group][$uid]['user_info'];
  633. $simpliUsers = self::$global->uidSimpleList;
  634. $simpliUsersID_UID_Arr = [];
  635. if (!empty($simpliUsers)) {
  636. foreach ($simpliUsers as $key => $val) {
  637. $simpliUsersID_UID_Arr[$val['0']] = $key;
  638. }
  639. }
  640. $now = time();
  641. if (!empty($user_info)) {
  642. foreach ($user_info as $val) {
  643. Gateway::sendToClient($val, json_encode(['type' => 'serviceoffline', 'msg' => '客户人员下线!'], 256));
  644. if (isset($simpliUsersID_UID_Arr[$val])) {
  645. 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 ");
  646. }
  647. Gateway::closeClient($val);
  648. }
  649. }
  650. unset($kefuinfo_old_new[$group][$uid]);
  651. $kfid = intval(substr($uid, 2));
  652. self::$db->update('ws_users')->cols(array('online_status' => 0, 'online_connectid' => ''))->where('id=' . $kfid)->query();
  653. do {
  654. } while (!self::$global->cas('kfList', $kefuinfo_old, $kefuinfo_old_new));
  655. self::writeLogKfStatus($uid, 0);
  656. return;
  657. }
  658. //用户下线了
  659. public static function guestOffline($client_id, $uid)
  660. {
  661. $kfuid = -1;
  662. $krclient_id = 0;
  663. $kfgroup = -1;
  664. $userToKf = $userToKfNew = self::$global->userToKf;
  665. if (isset($userToKfNew[$uid])) {
  666. $kfuid = isset($userToKfNew[$uid]['1']) ? $userToKfNew[$uid]['1'] : -1;
  667. $krclient_id = isset(Gateway::getClientIdByUid($kfuid)['0']) ? Gateway::getClientIdByUid($kfuid)['0'] : 0;
  668. unset($userToKfNew[$uid]);
  669. do {
  670. } while (!self::$global->cas('userToKf', $userToKf, $userToKfNew));
  671. }
  672. $uidSimpleList = $uidSimpleListNew = self::$global->uidSimpleList;
  673. if (isset($uidSimpleListNew[$uid])) {
  674. $kfgroup = $uidSimpleListNew[$uid]['1'];
  675. unset($uidSimpleListNew[$uid]);
  676. do {
  677. } while (!self::$global->cas('uidSimpleList', $uidSimpleList, $uidSimpleListNew));
  678. }
  679. $userList = $userListNew = self::$global->userList;
  680. $group_wait_count = 0;
  681. if (!empty($userList)) {
  682. $ischange = 0;
  683. foreach ($userList as $key => $val) {
  684. if ($val['group'] == $kfuid) {
  685. $group_wait_count++;
  686. }
  687. if ($val['id'] == $uid) {
  688. unset($userListNew[$key]);
  689. $ischange = 1;
  690. $group_wait_count--;
  691. break;
  692. }
  693. }
  694. if ($ischange) {
  695. do {
  696. } while (!self::$global->cas('userList', $userList, $userListNew));
  697. Gateway::sendToGroup('group_' . $kfgroup, json_encode(['message_type' => 'kfqueuelength', 'leng' => $group_wait_count], 256));
  698. }
  699. }
  700. if ($kfuid != -1 && $kfgroup != -1) {
  701. $kefuinfo_old = $kefuinfo_old_new = self::$global->kfList;
  702. $ischange_kf_list = 0;
  703. if (isset($kefuinfo_old[$kfgroup][$kfuid])) {
  704. $infos = $kefuinfo_old[$kfgroup][$kfuid]['user_info'];
  705. if ($infos) {
  706. if (is_array($infos)) {
  707. foreach ($infos as $key => $val) {
  708. if ($val == $client_id) {
  709. $ischange_kf_list = 1;
  710. unset($kefuinfo_old_new[$kfgroup][$kfuid]['user_info'][$key]);
  711. $kefuinfo_old_new[$kfgroup][$kfuid]['task'] = $kefuinfo_old_new[$kfgroup][$kfuid]['task'] - 1;
  712. }
  713. }
  714. }
  715. if ($ischange_kf_list) {
  716. do {
  717. } while (!self::$global->cas('kfList', $kefuinfo_old, $kefuinfo_old_new));
  718. $chat_message = [
  719. 'message_type' => 'userClose',
  720. 'data' => [
  721. 'content' => '用户连接已断开',
  722. 'id' => $uid,
  723. 'time' => date('H:i'),
  724. ]
  725. ];
  726. $now = time();
  727. $kf__uid = substr($kfuid, 2);
  728. $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 ";
  729. //echo "客户退出:". $sql ."\n";
  730. self::$db->query($sql);
  731. Gateway::sendToClient($krclient_id, json_encode($chat_message, 256));
  732. }
  733. }
  734. }
  735. }
  736. }
  737. /**
  738. * 客服结束会话
  739. * @param int $client_id 连接id
  740. *
  741. * tips: 当服务端主动退出的时候,会出现 exit status 9.原因是:服务端主动断开之后,连接的客户端会走这个方法,而短时间内进程
  742. * 需要处理这多的逻辑,又有cas操作,导致进程退出会超时,然后会被内核杀死,从而报出错误 9.实际对真正的业务没有任何的影响。
  743. */
  744. public static function serverClose($client_id, $servicelog_id)
  745. {
  746. // 返回.
  747. $chat_message = [
  748. 'message_type' => 'closeBysever',
  749. 'data' => [
  750. 'content' => '客服停止了该会话',
  751. 'time' => date('H:i'),
  752. ]
  753. ];
  754. Gateway::sendToClient($client_id, json_encode($chat_message, 256));
  755. Gateway::closeClient($client_id);
  756. $now = time();
  757. $sql = "update `ws_service_log` set `status`='2',end_time=$now where `servicelog_id`= '$servicelog_id'";
  758. //echo "客户退出:". $sql ."\n";
  759. self::$db->query($sql);
  760. $isServiceUserOut = false;
  761. // 将会员服务信息,从客服的服务列表中移除
  762. $old = $kfList = self::$global->kfList;
  763. foreach ($kfList as $k => $v) {
  764. foreach ($v as $key => $vo) {
  765. if (in_array($client_id, $vo['user_info'])) {
  766. $isServiceUserOut = true;
  767. // 根据client id 去更新会话工单一些信息
  768. self::$db->query("update `ws_service_log` set `end_time` = " . time() . " , `status` = '2' where `client_id`= '" . $client_id . "'");
  769. // 从会员的内存表中检索出该会员的信息,并更新内存
  770. $oldSimple = $simpleList = self::$global->uidSimpleList;
  771. $outUser = [];
  772. foreach ($simpleList as $u => $c) {
  773. if ($c['0'] == $client_id) {
  774. $outUser[] = [
  775. 'user_id' => $u,
  776. 'group_id' => $c['1']
  777. ];
  778. unset($simpleList[$u]);
  779. break;
  780. }
  781. }
  782. while (!self::$global->cas('uidSimpleList', $oldSimple, $simpleList)) {
  783. };
  784. unset($oldSimple, $simpleList);
  785. $outUser = self::$db->query("select `user_id`,`group_id` from `ws_service_log` where `client_id`= '" . $client_id . "'");
  786. // 通知 客服删除退出的用户
  787. if (!empty($outUser)) {
  788. $del_message = [
  789. 'message_type' => 'delUser',
  790. 'data' => [
  791. 'id' => $outUser['0']['user_id']
  792. ]
  793. ];
  794. Gateway::sendToClient($vo['client_id'], json_encode($del_message, 256));
  795. unset($del_message);
  796. // 尝试分配新会员进入服务
  797. self::userOfflineTask($outUser['0']['group_id']);
  798. }
  799. unset($outUser);
  800. // 维护现在的该客服的服务信息
  801. $kfList[$k][$key]['task'] -= 1; // 当前服务的人数 -1
  802. foreach ($vo['user_info'] as $m => $l) {
  803. if ($client_id == $l) {
  804. unset($kfList[$k][$key]['user_info'][$m]);
  805. break;
  806. }
  807. }
  808. // 刷新内存中客服的服务列表
  809. while (!self::$global->cas('kfList', $old, $kfList)) {
  810. };
  811. unset($old, $kfList);
  812. break;
  813. }
  814. }
  815. if ($isServiceUserOut) break;
  816. }
  817. // 尝试从排队的用户中删除退出的客户端
  818. if (false == $isServiceUserOut) {
  819. $old = $userList = self::$global->userList;
  820. foreach (self::$global->userList as $key => $vo) {
  821. if ($client_id == $vo['client_id']) {
  822. $isServiceUserOut = true;
  823. unset($userList[$key]);
  824. break;
  825. }
  826. }
  827. while (!self::$global->cas('userList', $old, $userList)) {
  828. };
  829. // 从会员的内存表中检索出该会员的信息,并更新内存
  830. $oldSimple = $simpleList = self::$global->uidSimpleList;
  831. foreach ($simpleList as $u => $c) {
  832. if ($c['0'] == $client_id) {
  833. unset($simpleList[$u]);
  834. break;
  835. }
  836. }
  837. while (!self::$global->cas('uidSimpleList', $oldSimple, $simpleList)) {
  838. };
  839. unset($oldSimple, $simpleList);
  840. }
  841. // 尝试是否是客服退出
  842. if (false == $isServiceUserOut) {
  843. $old = $kfList = self::$global->kfList;
  844. foreach (self::$global->kfList as $k => $v) {
  845. foreach ($v as $key => $vo) {
  846. // 客服服务列表中无数据,才去删除客服内存信息
  847. if ($client_id == $vo['client_id'] && (0 == count($vo['user_info']))) {
  848. unset($kfList[$k][$key]);
  849. break;
  850. }
  851. }
  852. }
  853. while (!self::$global->cas('kfList', $old, $kfList)) {
  854. };
  855. }
  856. }
  857. /**
  858. * 有人退出
  859. * @param $group
  860. */
  861. private static function userOfflineTask($group)
  862. {
  863. // TODO 此处查询最大的可服务人数,后面可以用其他的方式,存储这个数值,让其更高效的访问
  864. $maxNumber = self::getMaxServiceNum();
  865. $res = self::assignmentTask(self::$global->kfList, self::$global->userList, $group, $maxNumber);
  866. unset($maxNumber);
  867. if (1 == $res['code']) {
  868. while (!self::$global->cas('kfList', self::$global->kfList, $res['data']['4'])) {
  869. }; // 更新客服数据
  870. while (!self::$global->cas('userList', self::$global->userList, $res['data']['5'])) {
  871. }; // 更新会员数据
  872. // 服务信息入库
  873. $serviceLog = [
  874. 'user_id' => $res['data']['3']['id'],
  875. 'client_id' => $res['data']['3']['client_id'],
  876. 'user_name' => $res['data']['3']['name'],
  877. 'user_ip' => $res['data']['3']['ip'],
  878. 'user_avatar' => $res['data']['3']['avatar'],
  879. 'kf_id' => intval(ltrim($res['data']['0'], 'KF')),
  880. 'start_time' => time(),
  881. 'group_id' => $group,
  882. 'website' => $res['data']['3']['website'],
  883. 'system' => $res['data']['3']['system'],
  884. 'browse' => $res['data']['3']['browse'],
  885. 'status' => 1,
  886. 'intime' => $res['data']['3']['intime'],
  887. 'end_time' => 0
  888. ];
  889. $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();
  890. if (!$hisSession) {
  891. $conversationId = self::$db->insert('ws_service_log')->cols($serviceLog)->query();
  892. } else {
  893. self::$db->update('ws_service_log')->cols(['status' => 1])->where('servicelog_id=' . $hisSession['servicelog_id'])->query();
  894. $conversationId = $hisSession['servicelog_id'];
  895. }
  896. unset($serviceLog);
  897. // 通知会员发送信息绑定客服的id
  898. $noticeUser = [
  899. 'message_type' => 'connect',
  900. 'data' => [
  901. 'kf_id' => $res['data']['0'],
  902. 'kf_name' => $res['data']['1'],
  903. 'conversationId' => $conversationId,
  904. 'serverInfo' => self::$global->kfList[$group][$res['data']['0']],
  905. ]
  906. ];
  907. Gateway::sendToClient($res['data']['3']['client_id'], json_encode($noticeUser, 256));
  908. unset($noticeUser);
  909. // 通知客服端绑定会员的信息
  910. $noticeKf = [
  911. 'message_type' => 'connect',
  912. 'data' => [
  913. 'user_info' => $res['data']['3'],
  914. 'conversationId' => $conversationId,
  915. ]
  916. ];
  917. Gateway::sendToClient($res['data']['2'], json_encode($noticeKf, 256));
  918. unset($noticeKf);
  919. // 逐一通知
  920. $number = 1;
  921. foreach (self::$global->userList as $vo) {
  922. $waitMsg = '您前面还有 ' . $number . ' 位会员在等待。';
  923. $waitMessage = [
  924. 'message_type' => 'wait',
  925. 'data' => [
  926. 'content' => $waitMsg,
  927. ]
  928. ];
  929. Gateway::sendToClient($vo['client_id'], json_encode($waitMessage, 256));
  930. $number++;
  931. }
  932. unset($waitMessage, $number);
  933. // 写入接入值
  934. $key = date('Ymd') . 'success_in';
  935. self::$global->$key = 0;
  936. do {
  937. $oldKey = date('Ymd', strtotime('-1 day')); // 删除前一天的统计值
  938. unset(self::$global->$oldKey);
  939. } while (!self::$global->increment($key));
  940. unset($key);
  941. } else {
  942. switch ($res['code']) {
  943. case -1:
  944. $waitMsg = '暂时没有客服上班,请稍后再咨询。';
  945. // 逐一通知
  946. foreach (self::$global->userList as $vo) {
  947. $waitMessage = [
  948. 'message_type' => 'wait',
  949. 'data' => [
  950. 'content' => $waitMsg,
  951. ]
  952. ];
  953. Gateway::sendToClient($vo['client_id'], json_encode($waitMessage, 256));
  954. }
  955. break;
  956. case -2:
  957. break;
  958. case -3:
  959. break;
  960. case -4:
  961. // 逐一通知
  962. $number = 1;
  963. foreach (self::$global->userList as $vo) {
  964. $waitMsg = '您前面还有 ' . $number . ' 位会员在等待。';
  965. $waitMessage = [
  966. 'message_type' => 'wait',
  967. 'data' => [
  968. 'content' => $waitMsg,
  969. ]
  970. ];
  971. Gateway::sendToClient($vo['client_id'], json_encode($waitMessage, 256));
  972. $number++;
  973. }
  974. break;
  975. }
  976. unset($waitMessage, $number);
  977. }
  978. }
  979. /**
  980. * 有人进入执行分配
  981. * @param $client_id
  982. * @param $group
  983. * @param $uid
  984. */
  985. private static function userOnlineTask($client_id, $group, $uid = 0)
  986. {
  987. // TODO 此处查询最大的可服务人数,后面可以用其他的方式,存储这个数值,让其更高效的访问
  988. $maxNumber = self::getMaxServiceNum();
  989. $res = self::assignmentTask(self::$global->kfList, self::$global->userList, $group, $maxNumber, $uid);
  990. unset($maxNumber);
  991. if (1 == $res['code']) {
  992. while (!self::$global->cas('kfList', self::$global->kfList, $res['data']['4'])) {
  993. }; // 更新客服数据
  994. while (!self::$global->cas('userList', self::$global->userList, $res['data']['5'])) {
  995. }; // 更新会员数据
  996. $userToKf = self::$global->userToKf;
  997. $userToKf[$res['data']['3']['id']] = [
  998. $res['data']['3']['id'],
  999. $res['data']['0']
  1000. ];
  1001. self::$global->userToKf = $userToKf;
  1002. // 服务信息入库
  1003. $serviceLog = [
  1004. 'user_id' => $res['data']['3']['id'],
  1005. 'client_id' => $res['data']['3']['client_id'],
  1006. 'user_name' => $res['data']['3']['name'],
  1007. 'user_ip' => $res['data']['3']['ip'],
  1008. 'user_avatar' => $res['data']['3']['avatar'],
  1009. 'kf_id' => intval(ltrim($res['data']['0'], 'KF')),
  1010. 'start_time' => time(),
  1011. 'group_id' => $group,
  1012. 'website' => $res['data']['3']['website'],
  1013. 'system' => $res['data']['3']['system'],
  1014. 'browse' => $res['data']['3']['browse'],
  1015. 'status' => 1,
  1016. 'intime' => $res['data']['3']['intime'],
  1017. 'end_time' => 0
  1018. ];
  1019. $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();
  1020. if (!$hisSession) {
  1021. $conversationId = self::$db->insert('ws_service_log')->cols($serviceLog)->query();
  1022. } else {
  1023. self::$db->update('ws_service_log')->cols(['status' => 1])->where('servicelog_id=' . $hisSession['servicelog_id'])->query();
  1024. $conversationId = $hisSession['servicelog_id'];
  1025. }
  1026. unset($serviceLog);
  1027. // 通知会员发送信息绑定客服的id
  1028. $noticeUser = [
  1029. 'message_type' => 'connect',
  1030. 'data' => [
  1031. 'kf_id' => $res['data']['0'],
  1032. 'conversationId' => $conversationId,
  1033. 'serverInfo' => self::$global->kfList[$group][$res['data']['0']],
  1034. 'kf_name' => $res['data']['1']
  1035. ]
  1036. ];
  1037. Gateway::sendToClient($client_id, json_encode($noticeUser, 256));
  1038. unset($noticeUser);
  1039. // 发送客服欢迎语
  1040. $sayHello = self::$db->query('select `word`,`status` from `ws_reply` where `id` = 2');
  1041. if (!empty($sayHello) && 1 == $sayHello['0']['status']) {
  1042. $chat_message = [
  1043. 'message_type' => 'chatMessage',
  1044. 'data' => [
  1045. 'name' => $res['data']['1'],
  1046. //'avatar' => self::$global->kfList[$group][$res['data']['0']],
  1047. 'id' => $res['data']['0'],
  1048. 'time' => date('H:i'),
  1049. 'content' => htmlspecialchars($sayHello['0']['word'])
  1050. ]
  1051. ];
  1052. Gateway::sendToClient($client_id, json_encode($chat_message, 256));
  1053. unset($chat_message);
  1054. }
  1055. unset($sayHello);
  1056. // 通知客服端绑定会员的信息
  1057. $noticeKf = [
  1058. 'message_type' => 'connect',
  1059. 'data' => [
  1060. 'user_info' => $res['data']['3'],
  1061. 'conversationId' => $conversationId,
  1062. ]
  1063. ];
  1064. Gateway::sendToClient($res['data']['2'], json_encode($noticeKf, 256));
  1065. unset($noticeKf);
  1066. // 写入接入值
  1067. $key = date('Ymd') . 'success_in';
  1068. self::$global->$key = 0;
  1069. do {
  1070. $oldKey = date('Ymd', strtotime('-1 day')); // 删除前一天的统计值
  1071. unset(self::$global->$oldKey);
  1072. } while (!self::$global->increment($key));
  1073. unset($key);
  1074. } else {
  1075. $waitMsg = '';
  1076. switch ($res['code']) {
  1077. case -1:
  1078. $waitMsg = '暂时没有客服上班,请稍后再咨询。';
  1079. break;
  1080. case -2:
  1081. break;
  1082. case -3:
  1083. break;
  1084. case -4:
  1085. $number = count(self::$global->userList);
  1086. $waitMsg = '您前面还有 ' . $number . ' 位会员在等待。';
  1087. break;
  1088. }
  1089. $waitMessage = [
  1090. 'message_type' => 'wait',
  1091. 'data' => [
  1092. 'content' => $waitMsg,
  1093. ]
  1094. ];
  1095. Gateway::sendToClient($client_id, json_encode($waitMessage, 256));
  1096. unset($waitMessage);
  1097. }
  1098. $userlist = self::$global->userList;
  1099. $waitcount = 0;
  1100. if ($userlist) {
  1101. foreach ($userlist as $val) {
  1102. if ($val['group'] == $group) {
  1103. $waitcount++;
  1104. }
  1105. }
  1106. Gateway::sendToGroup('group_' . $group, json_encode(['message_type' => 'kfqueuelength', 'leng' => $waitcount], 256));
  1107. }
  1108. }
  1109. /**
  1110. * 给客服分配会员【均分策略】
  1111. * @param $kfList
  1112. * @param $userList
  1113. * @param $group
  1114. * @param $total
  1115. */
  1116. private static function assignmentTask($kfList, $userList, $group, $total, $uid = 0)
  1117. {
  1118. // 注:修改为已上线(status为1上线status为2不接受分配)
  1119. $onlineKF = [];
  1120. foreach ($kfList as $k => $v) {
  1121. foreach ($v as $ke => $va) {
  1122. if ($va['status'] == 1) {
  1123. $onlineKF[$k][$ke] = $va;
  1124. }
  1125. }
  1126. }
  1127. // 没有客服上线
  1128. if (empty($onlineKF) || empty($onlineKF[$group])) {
  1129. return ['code' => -1];
  1130. }
  1131. // 没有待分配的会员
  1132. if (empty($userList)) {
  1133. return ['code' => -2];
  1134. }
  1135. // 未设置每个客服可以服务多少人
  1136. if (0 == $total) {
  1137. return ['code' => -3];
  1138. }
  1139. // 查看该组的客服是否在线
  1140. if (!isset($onlineKF[$group])) {
  1141. return ['code' => -1];
  1142. }
  1143. //上次用户掉线后,还可以继续上一次 (如果没有关闭) 的会话 --1
  1144. $odltalksession = false;
  1145. $user = $user_first = array_shift($userList);
  1146. if ($uid > 0 && $user['id'] != $uid && count($userList) > 1) {
  1147. $timevalielimit = time() - 60 * 5;
  1148. $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();
  1149. if ($odltalksession) {
  1150. foreach ($userList as $ttkey => $ttval) {
  1151. if ($ttval['id'] == $uid) {
  1152. array_unshift($userList, $user);
  1153. $user = $userList[$ttkey];
  1154. unset($userList[$ttkey]);
  1155. break;
  1156. }
  1157. }
  1158. }
  1159. }
  1160. //上次用户掉线后,还可以继续上一次 (如果没有关闭) 的会话 --2
  1161. if ($odltalksession) {
  1162. $oldkrid = 'KF' . $odltalksession['kf_id'];
  1163. if (isset($onlineKF[$group][$oldkrid])) {
  1164. $kf = $onlineKF[$group][$oldkrid];
  1165. $min = $kf['task'];
  1166. $flag = $kf['id'];
  1167. unset($onlineKF[$group][$oldkrid]);
  1168. } else {
  1169. goto NOSIGNKF;
  1170. }
  1171. } else {
  1172. NOSIGNKF:
  1173. $kf = $onlineKF[$group];
  1174. $kf = array_shift($kf);
  1175. $min = $kf['task'];
  1176. $flag = $kf['id'];
  1177. foreach ($onlineKF[$group] as $key => $vo) {
  1178. if ($vo['task'] < $min) {
  1179. $min = $vo['task'];
  1180. $flag = $key;
  1181. }
  1182. }
  1183. unset($kf);
  1184. }
  1185. // 需要排队了
  1186. if ($onlineKF[$group][$flag]['task'] == $total) {
  1187. array_unshift($userList, $user);
  1188. return ['code' => -4];
  1189. }
  1190. $kfList[$group][$flag]['task'] += 1;
  1191. array_push($kfList[$group][$flag]['user_info'], $user['client_id']); // 被分配的用户信息
  1192. return [
  1193. 'code' => 1,
  1194. 'data' => [
  1195. $onlineKF[$group][$flag]['id'],
  1196. $onlineKF[$group][$flag]['name'],
  1197. $onlineKF[$group][$flag]['client_id'],
  1198. $user,
  1199. $kfList,
  1200. $userList
  1201. ]
  1202. ];
  1203. }
  1204. /**
  1205. * 获取最大的服务人数
  1206. * @return int
  1207. */
  1208. private static function getMaxServiceNum()
  1209. {
  1210. $maxNumber = self::$db->query('select `max_service` from `ws_kf_config` where `id` = 1');
  1211. if (!empty($maxNumber)) {
  1212. $maxNumber = 5;
  1213. } else {
  1214. $maxNumber = $maxNumber['0']['max_service'];
  1215. }
  1216. return $maxNumber;
  1217. }
  1218. /**
  1219. * 将内存中的数据写入统计表
  1220. * @param int $flag
  1221. */
  1222. private static function writeLog($flag = 1)
  1223. {
  1224. // 上午 8点 到 22 点开始统计
  1225. if (date('H') < 8 || date('H') > 22) {
  1226. return;
  1227. }
  1228. // 当前正在接入的人 和 在线客服数
  1229. $kfList = self::$global->kfList;
  1230. $nowTalking = 0;
  1231. $onlineKf = 0;
  1232. if (!empty($kfList)) {
  1233. foreach ($kfList as $key => $vo) {
  1234. $onlineKf += count($vo);
  1235. foreach ($vo as $k => $v) {
  1236. $nowTalking += count($v['user_info']);
  1237. }
  1238. }
  1239. }
  1240. // 在队列中的用户
  1241. $inQueue = count(self::$global->userList);
  1242. $key = date('Ymd') . 'total_in';
  1243. $key2 = date('Ymd') . 'success_in';
  1244. $param = [
  1245. 'is_talking' => $nowTalking,
  1246. 'in_queue' => $inQueue,
  1247. 'online_kf' => $onlineKf,
  1248. 'success_in' => self::$global->$key2,
  1249. 'total_in' => self::$global->$key,
  1250. 'now_date' => date('Y-m-d')
  1251. ];
  1252. self::$db->update('ws_now_data')->cols($param)->where('id=1')->query();
  1253. if (2 == $flag) {
  1254. $param = [
  1255. 'is_talking' => $nowTalking,
  1256. 'in_queue' => $inQueue,
  1257. 'online_kf' => $onlineKf,
  1258. 'success_in' => self::$global->$key2,
  1259. 'total_in' => self::$global->$key,
  1260. 'add_date' => date('Y-m-d'),
  1261. 'add_hour' => date('H'),
  1262. 'add_minute' => date('i'),
  1263. ];
  1264. self::$db->insert('ws_service_data')->cols($param)->query();
  1265. }
  1266. unset($kfList, $nowTalking, $inQueue, $onlineKf, $key, $key2, $param);
  1267. }
  1268. /**
  1269. * 机器人问答
  1270. * @param $client_id 服务ID
  1271. * @param $message 数据
  1272. */
  1273. private static function toRobot($client_id, $message)
  1274. {
  1275. $groups_id = $message['data']['groups_id'];
  1276. $robot_name = $message['data']['robot_name'];
  1277. $robotgroups_id = $message['data']['robotgroups_id'];
  1278. // 查询问题.
  1279. $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 . "'");
  1280. $chat_message = [
  1281. 'message_type' => 'robotMessage',
  1282. //'message_type' => 'chatMessage',
  1283. 'data' => [
  1284. 'name' => '智能助手',
  1285. 'time' => date('H:i'),
  1286. 'content' => $getRobot ? htmlspecialchars($getRobot[0]['robot_content']) : 'error',
  1287. ]
  1288. ];
  1289. sleep(1);
  1290. Gateway::sendToClient($client_id, json_encode($chat_message, 256));
  1291. }
  1292. /**
  1293. * 评价
  1294. * @param $client_id 服务ID
  1295. * @param $message 数据
  1296. */
  1297. private static function evaluate($client_id, $message)
  1298. {
  1299. // 修改数据库.
  1300. $evaluate_id = $message['data']['evaluate_id'];
  1301. $result = self::$db->query("UPDATE `ws_service_log` SET `evaluate_id` = '" . $evaluate_id . "' WHERE `client_id`='" . $client_id . "'");
  1302. if ($result) {
  1303. $chat_message = [
  1304. 'message_type' => 'evaluate',
  1305. 'data' => [
  1306. 'status' => 1,
  1307. 'time' => date('H:i'),
  1308. ]
  1309. ];
  1310. } else {
  1311. $chat_message = [
  1312. 'message_type' => 'evaluate',
  1313. 'data' => [
  1314. 'status' => 2,
  1315. 'time' => date('H:i'),
  1316. ]
  1317. ];
  1318. }
  1319. Gateway::sendToClient($client_id, json_encode($chat_message, 256));
  1320. }
  1321. //获取系统配置
  1322. private static function upsystemconfig()
  1323. {
  1324. $systemConfigData = self::$db->query("SELECT * FROM `ws_systemconfig`");
  1325. $arr = [];
  1326. if ($systemConfigData) {
  1327. foreach ($systemConfigData as $item) {
  1328. $arr[$item['systemconfig_enName']] = $item;
  1329. }
  1330. self::$global->systemconfig = $arr;
  1331. }
  1332. }
  1333. /**
  1334. * 超时
  1335. * @param $client_id 服务ID
  1336. * @param $message 数据
  1337. */
  1338. private static function overTime()
  1339. {
  1340. // 查询对话时效设置.
  1341. $systemConfigData = self::$db->query("SELECT `systemconfig_data`,`systemconfig_enName`,`systemconfig_content` FROM `ws_systemconfig`");
  1342. foreach ($systemConfigData as $k => $v) {
  1343. if ($v['systemconfig_enName'] == 'overtime') {
  1344. self::$global->overtime = $v;
  1345. } elseif ($v['systemconfig_enName'] == 'unoperated') {
  1346. self::$global->unoperated = $v;
  1347. } elseif ($v['systemconfig_enName'] == 'noResponse') {
  1348. self::$global->noResponse = $v;
  1349. }
  1350. }
  1351. // 查询未断开的工单.
  1352. $serviceLog = self::$db->query("SELECT `servicelog_id`,`client_id`,`start_time` FROM `ws_service_log` WHERE `status`='1' OR `status`='3'");
  1353. $whereOr = '1=0';
  1354. foreach ($serviceLog as $k => $v) {
  1355. if ($k == 0) {
  1356. $whereOr = "`servicelog_id`=" . $v['servicelog_id'];
  1357. } else {
  1358. $whereOr .= " OR `servicelog_id`=" . $v['servicelog_id'];
  1359. }
  1360. }
  1361. // 查询最后一次会话.
  1362. //$chatLog = self::$db->query("SELECT `servicelog_id`,MAX(`time_line`) FROM `ws_chat_log` WHERE ".$whereOr." group by `servicelog_id`");
  1363. $chatLog = self::$db->query("
  1364. select * from ws_chat_log as a where time_line=(
  1365. select max(b.time_line) from ws_chat_log as b where a.servicelog_id = b.servicelog_id and (" . $whereOr . ") group by servicelog_id
  1366. )
  1367. ");
  1368. $setOvertime = strtotime('-' . (self::$global->overtime['systemconfig_data'] - 60) . ' second');
  1369. $overtime = strtotime('-' . (self::$global->overtime['systemconfig_data']) . ' second');
  1370. $setUnoperated = strtotime('-' . (self::$global->unoperated['systemconfig_data'] - 60) . ' second');
  1371. $unoperated = strtotime('-' . (self::$global->unoperated['systemconfig_data']) . ' second');
  1372. $noResponse = strtotime('-' . (self::$global->noResponse['systemconfig_data']) . ' second');
  1373. foreach ($serviceLog as $k => $v) {//注意该循环时间
  1374. if (!strlen(array_search($v['servicelog_id'], array_column($chatLog, 'servicelog_id')))) {
  1375. // 如果小于设定时间则关闭会话.
  1376. if ($v['start_time'] <= $unoperated) {
  1377. self::serverClose($v['client_id'], $v['servicelog_id']);
  1378. // 如果小于设定时间前一分钟则给出提示.
  1379. } elseif ($v['start_time'] <= $setUnoperated) {
  1380. $chat_message = [
  1381. 'message_type' => 'overtime',
  1382. 'data' => [
  1383. 'content' => htmlspecialchars(self::$global->unoperated['systemconfig_content']),
  1384. ]
  1385. ];
  1386. Gateway::sendToClient($v['client_id'], json_encode($chat_message, 256));
  1387. }
  1388. }
  1389. }
  1390. // 循环检测会话时效.
  1391. foreach ($chatLog as $k => $v) {
  1392. $toWho = substr($v['to_id'], 0, 2);
  1393. // 如果对话为客服的最后一次对话且时间小于设定时间则结束工单.
  1394. if ($v['time_line'] <= $overtime) {
  1395. $found_key = array_search($v['servicelog_id'], array_column($serviceLog, 'servicelog_id'));
  1396. self::serverClose($serviceLog[$found_key]['client_id'], $v['servicelog_id']);
  1397. // 如果对话为客服的最后一次对话且时间小于设定时间前一分钟则给出提示.
  1398. } elseif ($v['time_line'] <= $setOvertime) {
  1399. $chat_message = [
  1400. 'message_type' => 'overtime',
  1401. 'data' => [
  1402. 'content' => htmlspecialchars(self::$global->overtime['systemconfig_content']),
  1403. ]
  1404. ];
  1405. $found_key = array_search($v['servicelog_id'], array_column($serviceLog, 'servicelog_id'));
  1406. Gateway::sendToClient($serviceLog[$found_key]['client_id'], json_encode($chat_message, 256));
  1407. }
  1408. }
  1409. }
  1410. //客服在线状态写组
  1411. private static function writeLogKfStatus($kf, $status, $flag = 1)
  1412. {
  1413. if ($flag == 1) {
  1414. $status = intval($status);
  1415. if ($status == 0) {
  1416. self::$db->delete('ws_kfonline')->where("uid='$kf'")->query();
  1417. } else {
  1418. $now = date('Y-m-d H:i;s');
  1419. $sql = "insert into ws_kfonline(uid,status,uptime) values('$kf',$status,'$now') ON DUPLICATE KEY UPDATE status=$status,uptime='$now' ";
  1420. self::$db->query($sql);
  1421. }
  1422. } else {
  1423. self::$db->query("delete from ws_kfonline ");
  1424. }
  1425. }
  1426. //用户下线通知
  1427. private static function userCloseNotice($client_id, $cuid, $group)
  1428. {
  1429. }
  1430. //踢掉同一用户的旧用户
  1431. private static function tickOlduser($uid)
  1432. {
  1433. }
  1434. }