Events.php 58 KB

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