Events.php 62 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618
  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. if (!array_key_exists($message['uid'], $userList)) {
  556. do {
  557. $NewUserList = $userList;
  558. $NewUserList[$message['uid']] = [
  559. 'id' => $message['uid'],
  560. 'name' => $message['name'],
  561. 'avatar' => $message['avatar'],
  562. 'website' => $_SESSION['origin'],//$_SERVER['HTTP_ORIGIN'],
  563. 'browse' => Gateway::browse_info(),
  564. 'system' => Gateway::get_os(),
  565. 'ip' => isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '',
  566. 'group' => $message['group'],
  567. 'intime' => time(),
  568. 'client_id' => $client_id
  569. ];
  570. } while (!self::$global->cas('userList', $userList, $NewUserList));
  571. unset($NewUserList, $userList);
  572. // 维护 UID对应的client_id 数组
  573. do {
  574. $old = $newList = self::$global->uidSimpleList;
  575. $newList[$message['uid']] = [
  576. $client_id,
  577. $message['group']
  578. ];
  579. } while (!self::$global->cas('uidSimpleList', $old, $newList));
  580. unset($old, $newList);
  581. // 写入接入值
  582. $key = date('Ymd') . 'total_in';
  583. self::$global->$key = 0;
  584. do {
  585. $oldKey = date('Ymd', strtotime('-1 day')); // 删除前一天的统计值
  586. unset(self::$global->$oldKey);
  587. } while (!self::$global->increment($key));
  588. unset($key);
  589. }
  590. // 绑定 client_id 和 uid
  591. Gateway::bindUid($client_id, $message['uid']);
  592. $_SESSION['iskefu'] = 0;
  593. $_SESSION['uid'] = $message['uid'];
  594. // 尝试分配新会员进入服务
  595. self::userOnlineTask($client_id, $message['group'], $message['uid']);
  596. }
  597. /**
  598. * 当用户断开连接时触发
  599. * @param int $client_id 连接id
  600. *
  601. * tips: 当服务端主动退出的时候,会出现 exit status 9.原因是:服务端主动断开之后,连接的客户端会走这个方法,而短时间内进程
  602. * 需要处理这多的逻辑,又有cas操作,导致进程退出会超时,然后会被内核杀死,从而报出错误 9.实际对真正的业务没有任何的影响。
  603. */
  604. public static function onClose($client_id)
  605. {
  606. $isKefuoff = isset($_SESSION['iskefu']) ? $_SESSION['iskefu'] : 0;
  607. $uid = isset($_SESSION['uid']) ? $_SESSION['uid'] : false;
  608. //echo "下线:$uid - $client_id - $isKefuoff \n";
  609. if (empty($uid)) {
  610. return;
  611. }
  612. if ($isKefuoff) {
  613. self::serviceOffline($client_id, $uid);
  614. } else {
  615. self::guestOffline($client_id, $uid);
  616. }
  617. return;
  618. }
  619. //客服下线了
  620. public static function serviceOffline($client_id, $uid)
  621. {
  622. $group = $_SESSION['group'];
  623. $kefuinfo_old = $kefuinfo_old_new = self::$global->kfList;
  624. $user_info = $kefuinfo_old_new[$group][$uid]['user_info'];
  625. $simpliUsers = self::$global->uidSimpleList;
  626. $simpliUsersID_UID_Arr = [];
  627. if (!empty($simpliUsers)) {
  628. foreach ($simpliUsers as $key => $val) {
  629. $simpliUsersID_UID_Arr[$val['0']] = $key;
  630. }
  631. }
  632. $now = time();
  633. if (!empty($user_info)) {
  634. foreach ($user_info as $val) {
  635. Gateway::sendToClient($val, json_encode(['type' => 'serviceoffline', 'msg' => '客户人员下线!'], 256));
  636. if (isset($simpliUsersID_UID_Arr[$val])) {
  637. 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 ");
  638. }
  639. Gateway::closeClient($val);
  640. }
  641. }
  642. unset($kefuinfo_old_new[$group][$uid]);
  643. $kfid = intval(substr($uid, 2));
  644. self::$db->update('ws_users')->cols(array('online_status' => 0, 'online_connectid' => ''))->where('id=' . $kfid)->query();
  645. do {
  646. } while (!self::$global->cas('kfList', $kefuinfo_old, $kefuinfo_old_new));
  647. self::writeLogKfStatus($uid, 0);
  648. return;
  649. }
  650. //用户下线了
  651. public static function guestOffline($client_id, $uid)
  652. {
  653. $kfuid = -1;
  654. $krclient_id = 0;
  655. $kfgroup = -1;
  656. $userToKf = $userToKfNew = self::$global->userToKf;
  657. if (isset($userToKfNew[$uid])) {
  658. $kfuid = isset($userToKfNew[$uid]['1']) ? $userToKfNew[$uid]['1'] : -1;
  659. $krclient_id = isset(Gateway::getClientIdByUid($kfuid)['0']) ? Gateway::getClientIdByUid($kfuid)['0'] : 0;
  660. unset($userToKfNew[$uid]);
  661. do {
  662. } while (!self::$global->cas('userToKf', $userToKf, $userToKfNew));
  663. }
  664. $uidSimpleList = $uidSimpleListNew = self::$global->uidSimpleList;
  665. if (isset($uidSimpleListNew[$uid])) {
  666. $kfgroup = $uidSimpleListNew[$uid]['1'];
  667. unset($uidSimpleListNew[$uid]);
  668. do {
  669. } while (!self::$global->cas('uidSimpleList', $uidSimpleList, $uidSimpleListNew));
  670. }
  671. $userList = $userListNew = self::$global->userList;
  672. $group_wait_count = 0;
  673. if (!empty($userList)) {
  674. $ischange = 0;
  675. foreach ($userList as $key => $val) {
  676. if ($val['group'] == $kfuid) {
  677. $group_wait_count++;
  678. }
  679. if ($val['id'] == $uid) {
  680. unset($userListNew[$key]);
  681. $ischange = 1;
  682. $group_wait_count--;
  683. break;
  684. }
  685. }
  686. if ($ischange) {
  687. do {
  688. } while (!self::$global->cas('userList', $userList, $userListNew));
  689. Gateway::sendToGroup('group_' . $kfgroup, json_encode(['message_type' => 'kfqueuelength', 'leng' => $group_wait_count], 256));
  690. }
  691. }
  692. if ($kfuid != -1 && $kfgroup != -1) {
  693. $kefuinfo_old = $kefuinfo_old_new = self::$global->kfList;
  694. $ischange_kf_list = 0;
  695. if (isset($kefuinfo_old[$kfgroup][$kfuid])) {
  696. $infos = $kefuinfo_old[$kfgroup][$kfuid]['user_info'];
  697. if ($infos) {
  698. if (is_array($infos)) {
  699. foreach ($infos as $key => $val) {
  700. if ($val == $client_id) {
  701. $ischange_kf_list = 1;
  702. unset($kefuinfo_old_new[$kfgroup][$kfuid]['user_info'][$key]);
  703. $kefuinfo_old_new[$kfgroup][$kfuid]['task'] = $kefuinfo_old_new[$kfgroup][$kfuid]['task'] - 1;
  704. }
  705. }
  706. }
  707. if ($ischange_kf_list) {
  708. do {
  709. } while (!self::$global->cas('kfList', $kefuinfo_old, $kefuinfo_old_new));
  710. $chat_message = [
  711. 'message_type' => 'userClose',
  712. 'data' => [
  713. 'content' => '用户连接已断开',
  714. 'time' => date('H:i'),
  715. ]
  716. ];
  717. $now = time();
  718. $kf__uid = substr($kfuid, 2);
  719. $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 ";
  720. //echo "客户退出:". $sql ."\n";
  721. self::$db->query($sql);
  722. Gateway::sendToClient($krclient_id, json_encode($chat_message, 256));
  723. }
  724. }
  725. }
  726. }
  727. }
  728. /**
  729. * 客服结束会话
  730. * @param int $client_id 连接id
  731. *
  732. * tips: 当服务端主动退出的时候,会出现 exit status 9.原因是:服务端主动断开之后,连接的客户端会走这个方法,而短时间内进程
  733. * 需要处理这多的逻辑,又有cas操作,导致进程退出会超时,然后会被内核杀死,从而报出错误 9.实际对真正的业务没有任何的影响。
  734. */
  735. public static function serverClose($client_id, $servicelog_id)
  736. {
  737. // 返回.
  738. $chat_message = [
  739. 'message_type' => 'closeBysever',
  740. 'data' => [
  741. 'content' => '客服停止了该会话',
  742. 'time' => date('H:i'),
  743. ]
  744. ];
  745. Gateway::sendToClient($client_id, json_encode($chat_message, 256));
  746. Gateway::closeClient($client_id);
  747. $now = time();
  748. $sql = "update `ws_service_log` set `status`='2',end_time=$now where `servicelog_id`= '$servicelog_id'";
  749. //echo "客户退出:". $sql ."\n";
  750. self::$db->query($sql);
  751. $isServiceUserOut = false;
  752. // 将会员服务信息,从客服的服务列表中移除
  753. $old = $kfList = self::$global->kfList;
  754. foreach ($kfList as $k => $v) {
  755. foreach ($v as $key => $vo) {
  756. if (in_array($client_id, $vo['user_info'])) {
  757. $isServiceUserOut = true;
  758. // 根据client id 去更新会话工单一些信息
  759. self::$db->query("update `ws_service_log` set `end_time` = " . time() . " , `status` = '2' where `client_id`= '" . $client_id . "'");
  760. // 从会员的内存表中检索出该会员的信息,并更新内存
  761. $oldSimple = $simpleList = self::$global->uidSimpleList;
  762. $outUser = [];
  763. foreach ($simpleList as $u => $c) {
  764. if ($c['0'] == $client_id) {
  765. $outUser[] = [
  766. 'user_id' => $u,
  767. 'group_id' => $c['1']
  768. ];
  769. unset($simpleList[$u]);
  770. break;
  771. }
  772. }
  773. while (!self::$global->cas('uidSimpleList', $oldSimple, $simpleList)) {
  774. };
  775. unset($oldSimple, $simpleList);
  776. $outUser = self::$db->query("select `user_id`,`group_id` from `ws_service_log` where `client_id`= '" . $client_id . "'");
  777. // 通知 客服删除退出的用户
  778. if (!empty($outUser)) {
  779. $del_message = [
  780. 'message_type' => 'delUser',
  781. 'data' => [
  782. 'id' => $outUser['0']['user_id']
  783. ]
  784. ];
  785. Gateway::sendToClient($vo['client_id'], json_encode($del_message, 256));
  786. unset($del_message);
  787. // 尝试分配新会员进入服务
  788. self::userOfflineTask($outUser['0']['group_id']);
  789. }
  790. unset($outUser);
  791. // 维护现在的该客服的服务信息
  792. $kfList[$k][$key]['task'] -= 1; // 当前服务的人数 -1
  793. foreach ($vo['user_info'] as $m => $l) {
  794. if ($client_id == $l) {
  795. unset($kfList[$k][$key]['user_info'][$m]);
  796. break;
  797. }
  798. }
  799. // 刷新内存中客服的服务列表
  800. while (!self::$global->cas('kfList', $old, $kfList)) {
  801. };
  802. unset($old, $kfList);
  803. break;
  804. }
  805. }
  806. if ($isServiceUserOut) break;
  807. }
  808. // 尝试从排队的用户中删除退出的客户端
  809. if (false == $isServiceUserOut) {
  810. $old = $userList = self::$global->userList;
  811. foreach (self::$global->userList as $key => $vo) {
  812. if ($client_id == $vo['client_id']) {
  813. $isServiceUserOut = true;
  814. unset($userList[$key]);
  815. break;
  816. }
  817. }
  818. while (!self::$global->cas('userList', $old, $userList)) {
  819. };
  820. // 从会员的内存表中检索出该会员的信息,并更新内存
  821. $oldSimple = $simpleList = self::$global->uidSimpleList;
  822. foreach ($simpleList as $u => $c) {
  823. if ($c['0'] == $client_id) {
  824. unset($simpleList[$u]);
  825. break;
  826. }
  827. }
  828. while (!self::$global->cas('uidSimpleList', $oldSimple, $simpleList)) {
  829. };
  830. unset($oldSimple, $simpleList);
  831. }
  832. // 尝试是否是客服退出
  833. if (false == $isServiceUserOut) {
  834. $old = $kfList = self::$global->kfList;
  835. foreach (self::$global->kfList as $k => $v) {
  836. foreach ($v as $key => $vo) {
  837. // 客服服务列表中无数据,才去删除客服内存信息
  838. if ($client_id == $vo['client_id'] && (0 == count($vo['user_info']))) {
  839. unset($kfList[$k][$key]);
  840. break;
  841. }
  842. }
  843. }
  844. while (!self::$global->cas('kfList', $old, $kfList)) {
  845. };
  846. }
  847. }
  848. /**
  849. * 有人退出
  850. * @param $group
  851. */
  852. private static function userOfflineTask($group)
  853. {
  854. // TODO 此处查询最大的可服务人数,后面可以用其他的方式,存储这个数值,让其更高效的访问
  855. $maxNumber = self::getMaxServiceNum();
  856. $res = self::assignmentTask(self::$global->kfList, self::$global->userList, $group, $maxNumber);
  857. unset($maxNumber);
  858. if (1 == $res['code']) {
  859. while (!self::$global->cas('kfList', self::$global->kfList, $res['data']['4'])) {
  860. }; // 更新客服数据
  861. while (!self::$global->cas('userList', self::$global->userList, $res['data']['5'])) {
  862. }; // 更新会员数据
  863. // 服务信息入库
  864. $serviceLog = [
  865. 'user_id' => $res['data']['3']['id'],
  866. 'client_id' => $res['data']['3']['client_id'],
  867. 'user_name' => $res['data']['3']['name'],
  868. 'user_ip' => $res['data']['3']['ip'],
  869. 'user_avatar' => $res['data']['3']['avatar'],
  870. 'kf_id' => intval(ltrim($res['data']['0'], 'KF')),
  871. 'start_time' => time(),
  872. 'group_id' => $group,
  873. 'website' => $res['data']['3']['website'],
  874. 'system' => $res['data']['3']['system'],
  875. 'browse' => $res['data']['3']['browse'],
  876. 'status' => 1,
  877. 'intime' => $res['data']['3']['intime'],
  878. 'end_time' => 0
  879. ];
  880. $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();
  881. if (!$hisSession) {
  882. $conversationId = self::$db->insert('ws_service_log')->cols($serviceLog)->query();
  883. } else {
  884. self::$db->update('ws_service_log')->cols(['status' => 1])->where('servicelog_id=' . $hisSession['servicelog_id'])->query();
  885. $conversationId = $hisSession['servicelog_id'];
  886. }
  887. unset($serviceLog);
  888. // 通知会员发送信息绑定客服的id
  889. $noticeUser = [
  890. 'message_type' => 'connect',
  891. 'data' => [
  892. 'kf_id' => $res['data']['0'],
  893. 'kf_name' => $res['data']['1'],
  894. 'conversationId' => $conversationId,
  895. 'serverInfo' => self::$global->kfList[$group][$res['data']['0']],
  896. ]
  897. ];
  898. Gateway::sendToClient($res['data']['3']['client_id'], json_encode($noticeUser, 256));
  899. unset($noticeUser);
  900. // 通知客服端绑定会员的信息
  901. $noticeKf = [
  902. 'message_type' => 'connect',
  903. 'data' => [
  904. 'user_info' => $res['data']['3'],
  905. 'conversationId' => $conversationId,
  906. ]
  907. ];
  908. Gateway::sendToClient($res['data']['2'], json_encode($noticeKf, 256));
  909. unset($noticeKf);
  910. // 逐一通知
  911. $number = 1;
  912. foreach (self::$global->userList as $vo) {
  913. $waitMsg = '您前面还有 ' . $number . ' 位会员在等待。';
  914. $waitMessage = [
  915. 'message_type' => 'wait',
  916. 'data' => [
  917. 'content' => $waitMsg,
  918. ]
  919. ];
  920. Gateway::sendToClient($vo['client_id'], json_encode($waitMessage, 256));
  921. $number++;
  922. }
  923. unset($waitMessage, $number);
  924. // 写入接入值
  925. $key = date('Ymd') . 'success_in';
  926. self::$global->$key = 0;
  927. do {
  928. $oldKey = date('Ymd', strtotime('-1 day')); // 删除前一天的统计值
  929. unset(self::$global->$oldKey);
  930. } while (!self::$global->increment($key));
  931. unset($key);
  932. } else {
  933. switch ($res['code']) {
  934. case -1:
  935. $waitMsg = '暂时没有客服上班,请稍后再咨询。';
  936. // 逐一通知
  937. foreach (self::$global->userList as $vo) {
  938. $waitMessage = [
  939. 'message_type' => 'wait',
  940. 'data' => [
  941. 'content' => $waitMsg,
  942. ]
  943. ];
  944. Gateway::sendToClient($vo['client_id'], json_encode($waitMessage, 256));
  945. }
  946. break;
  947. case -2:
  948. break;
  949. case -3:
  950. break;
  951. case -4:
  952. // 逐一通知
  953. $number = 1;
  954. foreach (self::$global->userList as $vo) {
  955. $waitMsg = '您前面还有 ' . $number . ' 位会员在等待。';
  956. $waitMessage = [
  957. 'message_type' => 'wait',
  958. 'data' => [
  959. 'content' => $waitMsg,
  960. ]
  961. ];
  962. Gateway::sendToClient($vo['client_id'], json_encode($waitMessage, 256));
  963. $number++;
  964. }
  965. break;
  966. }
  967. unset($waitMessage, $number);
  968. }
  969. }
  970. /**
  971. * 有人进入执行分配
  972. * @param $client_id
  973. * @param $group
  974. * @param $uid
  975. */
  976. private static function userOnlineTask($client_id, $group, $uid = 0)
  977. {
  978. // TODO 此处查询最大的可服务人数,后面可以用其他的方式,存储这个数值,让其更高效的访问
  979. $maxNumber = self::getMaxServiceNum();
  980. $res = self::assignmentTask(self::$global->kfList, self::$global->userList, $group, $maxNumber, $uid);
  981. unset($maxNumber);
  982. if (1 == $res['code']) {
  983. while (!self::$global->cas('kfList', self::$global->kfList, $res['data']['4'])) {
  984. }; // 更新客服数据
  985. while (!self::$global->cas('userList', self::$global->userList, $res['data']['5'])) {
  986. }; // 更新会员数据
  987. $userToKf = self::$global->userToKf;
  988. $userToKf[$res['data']['3']['id']] = [
  989. $res['data']['3']['id'],
  990. $res['data']['0']
  991. ];
  992. self::$global->userToKf = $userToKf;
  993. // 服务信息入库
  994. $serviceLog = [
  995. 'user_id' => $res['data']['3']['id'],
  996. 'client_id' => $res['data']['3']['client_id'],
  997. 'user_name' => $res['data']['3']['name'],
  998. 'user_ip' => $res['data']['3']['ip'],
  999. 'user_avatar' => $res['data']['3']['avatar'],
  1000. 'kf_id' => intval(ltrim($res['data']['0'], 'KF')),
  1001. 'start_time' => time(),
  1002. 'group_id' => $group,
  1003. 'website' => $res['data']['3']['website'],
  1004. 'system' => $res['data']['3']['system'],
  1005. 'browse' => $res['data']['3']['browse'],
  1006. 'status' => 1,
  1007. 'intime' => $res['data']['3']['intime'],
  1008. 'end_time' => 0
  1009. ];
  1010. $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();
  1011. if (!$hisSession) {
  1012. $conversationId = self::$db->insert('ws_service_log')->cols($serviceLog)->query();
  1013. } else {
  1014. self::$db->update('ws_service_log')->cols(['status' => 1])->where('servicelog_id=' . $hisSession['servicelog_id'])->query();
  1015. $conversationId = $hisSession['servicelog_id'];
  1016. }
  1017. unset($serviceLog);
  1018. // 通知会员发送信息绑定客服的id
  1019. $noticeUser = [
  1020. 'message_type' => 'connect',
  1021. 'data' => [
  1022. 'kf_id' => $res['data']['0'],
  1023. 'conversationId' => $conversationId,
  1024. 'serverInfo' => self::$global->kfList[$group][$res['data']['0']],
  1025. 'kf_name' => $res['data']['1']
  1026. ]
  1027. ];
  1028. Gateway::sendToClient($client_id, json_encode($noticeUser, 256));
  1029. unset($noticeUser);
  1030. // 发送客服欢迎语
  1031. $sayHello = self::$db->query('select `word`,`status` from `ws_reply` where `id` = 2');
  1032. if (!empty($sayHello) && 1 == $sayHello['0']['status']) {
  1033. $chat_message = [
  1034. 'message_type' => 'chatMessage',
  1035. 'data' => [
  1036. 'name' => $res['data']['1'],
  1037. //'avatar' => self::$global->kfList[$group][$res['data']['0']],
  1038. 'id' => $res['data']['0'],
  1039. 'time' => date('H:i'),
  1040. 'content' => htmlspecialchars($sayHello['0']['word'])
  1041. ]
  1042. ];
  1043. Gateway::sendToClient($client_id, json_encode($chat_message, 256));
  1044. unset($chat_message);
  1045. }
  1046. unset($sayHello);
  1047. // 通知客服端绑定会员的信息
  1048. $noticeKf = [
  1049. 'message_type' => 'connect',
  1050. 'data' => [
  1051. 'user_info' => $res['data']['3'],
  1052. 'conversationId' => $conversationId,
  1053. ]
  1054. ];
  1055. Gateway::sendToClient($res['data']['2'], json_encode($noticeKf, 256));
  1056. unset($noticeKf);
  1057. // 写入接入值
  1058. $key = date('Ymd') . 'success_in';
  1059. self::$global->$key = 0;
  1060. do {
  1061. $oldKey = date('Ymd', strtotime('-1 day')); // 删除前一天的统计值
  1062. unset(self::$global->$oldKey);
  1063. } while (!self::$global->increment($key));
  1064. unset($key);
  1065. } else {
  1066. $waitMsg = '';
  1067. switch ($res['code']) {
  1068. case -1:
  1069. $waitMsg = '暂时没有客服上班,请稍后再咨询。';
  1070. break;
  1071. case -2:
  1072. break;
  1073. case -3:
  1074. break;
  1075. case -4:
  1076. $number = count(self::$global->userList);
  1077. $waitMsg = '您前面还有 ' . $number . ' 位会员在等待。';
  1078. break;
  1079. }
  1080. $waitMessage = [
  1081. 'message_type' => 'wait',
  1082. 'data' => [
  1083. 'content' => $waitMsg,
  1084. ]
  1085. ];
  1086. Gateway::sendToClient($client_id, json_encode($waitMessage, 256));
  1087. unset($waitMessage);
  1088. }
  1089. $userlist = self::$global->userList;
  1090. $waitcount = 0;
  1091. if ($userlist) {
  1092. foreach ($userlist as $val) {
  1093. if ($val['group'] == $group) {
  1094. $waitcount++;
  1095. }
  1096. }
  1097. Gateway::sendToGroup('group_' . $group, json_encode(['message_type' => 'kfqueuelength', 'leng' => $waitcount], 256));
  1098. }
  1099. }
  1100. /**
  1101. * 给客服分配会员【均分策略】
  1102. * @param $kfList
  1103. * @param $userList
  1104. * @param $group
  1105. * @param $total
  1106. */
  1107. private static function assignmentTask($kfList, $userList, $group, $total, $uid = 0)
  1108. {
  1109. // 注:修改为已上线(status为1上线status为2不接受分配)
  1110. $onlineKF = [];
  1111. foreach ($kfList as $k => $v) {
  1112. foreach ($v as $ke => $va) {
  1113. if ($va['status'] == 1) {
  1114. $onlineKF[$k][$ke] = $va;
  1115. }
  1116. }
  1117. }
  1118. // 没有客服上线
  1119. if (empty($onlineKF) || empty($onlineKF[$group])) {
  1120. return ['code' => -1];
  1121. }
  1122. // 没有待分配的会员
  1123. if (empty($userList)) {
  1124. return ['code' => -2];
  1125. }
  1126. // 未设置每个客服可以服务多少人
  1127. if (0 == $total) {
  1128. return ['code' => -3];
  1129. }
  1130. // 查看该组的客服是否在线
  1131. if (!isset($onlineKF[$group])) {
  1132. return ['code' => -1];
  1133. }
  1134. //上次用户掉线后,还可以继续上一次 (如果没有关闭) 的会话 --1
  1135. $odltalksession = false;
  1136. $user = $user_first = array_shift($userList);
  1137. if ($uid > 0 && $user['id'] != $uid && count($userList) > 1) {
  1138. $timevalielimit = time() - 60 * 5;
  1139. $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();
  1140. if ($odltalksession) {
  1141. foreach ($userList as $ttkey => $ttval) {
  1142. if ($ttval['id'] == $uid) {
  1143. array_unshift($userList, $user);
  1144. $user = $userList[$ttkey];
  1145. unset($userList[$ttkey]);
  1146. break;
  1147. }
  1148. }
  1149. }
  1150. }
  1151. //上次用户掉线后,还可以继续上一次 (如果没有关闭) 的会话 --2
  1152. if ($odltalksession) {
  1153. $oldkrid = 'KF' . $odltalksession['kf_id'];
  1154. if (isset($onlineKF[$group][$oldkrid])) {
  1155. $kf = $onlineKF[$group][$oldkrid];
  1156. $min = $kf['task'];
  1157. $flag = $kf['id'];
  1158. unset($onlineKF[$group][$oldkrid]);
  1159. } else {
  1160. goto NOSIGNKF;
  1161. }
  1162. } else {
  1163. NOSIGNKF:
  1164. $kf = $onlineKF[$group];
  1165. $kf = array_shift($kf);
  1166. $min = $kf['task'];
  1167. $flag = $kf['id'];
  1168. foreach ($onlineKF[$group] as $key => $vo) {
  1169. if ($vo['task'] < $min) {
  1170. $min = $vo['task'];
  1171. $flag = $key;
  1172. }
  1173. }
  1174. unset($kf);
  1175. }
  1176. // 需要排队了
  1177. if ($onlineKF[$group][$flag]['task'] == $total) {
  1178. array_unshift($userList, $user);
  1179. return ['code' => -4];
  1180. }
  1181. $kfList[$group][$flag]['task'] += 1;
  1182. array_push($kfList[$group][$flag]['user_info'], $user['client_id']); // 被分配的用户信息
  1183. return [
  1184. 'code' => 1,
  1185. 'data' => [
  1186. $onlineKF[$group][$flag]['id'],
  1187. $onlineKF[$group][$flag]['name'],
  1188. $onlineKF[$group][$flag]['client_id'],
  1189. $user,
  1190. $kfList,
  1191. $userList
  1192. ]
  1193. ];
  1194. }
  1195. /**
  1196. * 获取最大的服务人数
  1197. * @return int
  1198. */
  1199. private static function getMaxServiceNum()
  1200. {
  1201. $maxNumber = self::$db->query('select `max_service` from `ws_kf_config` where `id` = 1');
  1202. if (!empty($maxNumber)) {
  1203. $maxNumber = 5;
  1204. } else {
  1205. $maxNumber = $maxNumber['0']['max_service'];
  1206. }
  1207. return $maxNumber;
  1208. }
  1209. /**
  1210. * 将内存中的数据写入统计表
  1211. * @param int $flag
  1212. */
  1213. private static function writeLog($flag = 1)
  1214. {
  1215. // 上午 8点 到 22 点开始统计
  1216. if (date('H') < 8 || date('H') > 22) {
  1217. return;
  1218. }
  1219. // 当前正在接入的人 和 在线客服数
  1220. $kfList = self::$global->kfList;
  1221. $nowTalking = 0;
  1222. $onlineKf = 0;
  1223. if (!empty($kfList)) {
  1224. foreach ($kfList as $key => $vo) {
  1225. $onlineKf += count($vo);
  1226. foreach ($vo as $k => $v) {
  1227. $nowTalking += count($v['user_info']);
  1228. }
  1229. }
  1230. }
  1231. // 在队列中的用户
  1232. $inQueue = count(self::$global->userList);
  1233. $key = date('Ymd') . 'total_in';
  1234. $key2 = date('Ymd') . 'success_in';
  1235. $param = [
  1236. 'is_talking' => $nowTalking,
  1237. 'in_queue' => $inQueue,
  1238. 'online_kf' => $onlineKf,
  1239. 'success_in' => self::$global->$key2,
  1240. 'total_in' => self::$global->$key,
  1241. 'now_date' => date('Y-m-d')
  1242. ];
  1243. self::$db->update('ws_now_data')->cols($param)->where('id=1')->query();
  1244. if (2 == $flag) {
  1245. $param = [
  1246. 'is_talking' => $nowTalking,
  1247. 'in_queue' => $inQueue,
  1248. 'online_kf' => $onlineKf,
  1249. 'success_in' => self::$global->$key2,
  1250. 'total_in' => self::$global->$key,
  1251. 'add_date' => date('Y-m-d'),
  1252. 'add_hour' => date('H'),
  1253. 'add_minute' => date('i'),
  1254. ];
  1255. self::$db->insert('ws_service_data')->cols($param)->query();
  1256. }
  1257. unset($kfList, $nowTalking, $inQueue, $onlineKf, $key, $key2, $param);
  1258. }
  1259. /**
  1260. * 机器人问答
  1261. * @param $client_id 服务ID
  1262. * @param $message 数据
  1263. */
  1264. private static function toRobot($client_id, $message)
  1265. {
  1266. $groups_id = $message['data']['groups_id'];
  1267. $robot_name = $message['data']['robot_name'];
  1268. $robotgroups_id = $message['data']['robotgroups_id'];
  1269. // 查询问题.
  1270. $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 . "'");
  1271. $chat_message = [
  1272. 'message_type' => 'robotMessage',
  1273. //'message_type' => 'chatMessage',
  1274. 'data' => [
  1275. 'name' => '智能助手',
  1276. 'time' => date('H:i'),
  1277. 'content' => $getRobot ? htmlspecialchars($getRobot[0]['robot_content']) : 'error',
  1278. ]
  1279. ];
  1280. sleep(1);
  1281. Gateway::sendToClient($client_id, json_encode($chat_message, 256));
  1282. }
  1283. /**
  1284. * 评价
  1285. * @param $client_id 服务ID
  1286. * @param $message 数据
  1287. */
  1288. private static function evaluate($client_id, $message)
  1289. {
  1290. // 修改数据库.
  1291. $evaluate_id = $message['data']['evaluate_id'];
  1292. $result = self::$db->query("UPDATE `ws_service_log` SET `evaluate_id` = '" . $evaluate_id . "' WHERE `client_id`='" . $client_id . "'");
  1293. if ($result) {
  1294. $chat_message = [
  1295. 'message_type' => 'evaluate',
  1296. 'data' => [
  1297. 'status' => 1,
  1298. 'time' => date('H:i'),
  1299. ]
  1300. ];
  1301. } else {
  1302. $chat_message = [
  1303. 'message_type' => 'evaluate',
  1304. 'data' => [
  1305. 'status' => 2,
  1306. 'time' => date('H:i'),
  1307. ]
  1308. ];
  1309. }
  1310. Gateway::sendToClient($client_id, json_encode($chat_message, 256));
  1311. }
  1312. //获取系统配置
  1313. private static function upsystemconfig()
  1314. {
  1315. $systemConfigData = self::$db->query("SELECT * FROM `ws_systemconfig`");
  1316. $arr = [];
  1317. if ($systemConfigData) {
  1318. foreach ($systemConfigData as $item) {
  1319. $arr[$item['systemconfig_enName']] = $item;
  1320. }
  1321. self::$global->systemconfig = $arr;
  1322. }
  1323. }
  1324. /**
  1325. * 超时
  1326. * @param $client_id 服务ID
  1327. * @param $message 数据
  1328. */
  1329. private static function overTime()
  1330. {
  1331. // 查询对话时效设置.
  1332. $systemConfigData = self::$db->query("SELECT `systemconfig_data`,`systemconfig_enName`,`systemconfig_content` FROM `ws_systemconfig`");
  1333. foreach ($systemConfigData as $k => $v) {
  1334. if ($v['systemconfig_enName'] == 'overtime') {
  1335. self::$global->overtime = $v;
  1336. } elseif ($v['systemconfig_enName'] == 'unoperated') {
  1337. self::$global->unoperated = $v;
  1338. } elseif ($v['systemconfig_enName'] == 'noResponse') {
  1339. self::$global->noResponse = $v;
  1340. }
  1341. }
  1342. // 查询未断开的工单.
  1343. $serviceLog = self::$db->query("SELECT `servicelog_id`,`client_id`,`start_time` FROM `ws_service_log` WHERE `status`='1' OR `status`='3'");
  1344. $whereOr = '1=0';
  1345. foreach ($serviceLog as $k => $v) {
  1346. if ($k == 0) {
  1347. $whereOr = "`servicelog_id`=" . $v['servicelog_id'];
  1348. } else {
  1349. $whereOr .= " OR `servicelog_id`=" . $v['servicelog_id'];
  1350. }
  1351. }
  1352. // 查询最后一次会话.
  1353. //$chatLog = self::$db->query("SELECT `servicelog_id`,MAX(`time_line`) FROM `ws_chat_log` WHERE ".$whereOr." group by `servicelog_id`");
  1354. $chatLog = self::$db->query("
  1355. select * from ws_chat_log as a where time_line=(
  1356. select max(b.time_line) from ws_chat_log as b where a.servicelog_id = b.servicelog_id and (" . $whereOr . ") group by servicelog_id
  1357. )
  1358. ");
  1359. $setOvertime = strtotime('-' . (self::$global->overtime['systemconfig_data'] - 60) . ' second');
  1360. $overtime = strtotime('-' . (self::$global->overtime['systemconfig_data']) . ' second');
  1361. $setUnoperated = strtotime('-' . (self::$global->unoperated['systemconfig_data'] - 60) . ' second');
  1362. $unoperated = strtotime('-' . (self::$global->unoperated['systemconfig_data']) . ' second');
  1363. $noResponse = strtotime('-' . (self::$global->noResponse['systemconfig_data']) . ' second');
  1364. foreach ($serviceLog as $k => $v) {//注意该循环时间
  1365. if (!strlen(array_search($v['servicelog_id'], array_column($chatLog, 'servicelog_id')))) {
  1366. // 如果小于设定时间则关闭会话.
  1367. if ($v['start_time'] <= $unoperated) {
  1368. self::serverClose($v['client_id'], $v['servicelog_id']);
  1369. // 如果小于设定时间前一分钟则给出提示.
  1370. } elseif ($v['start_time'] <= $setUnoperated) {
  1371. $chat_message = [
  1372. 'message_type' => 'overtime',
  1373. 'data' => [
  1374. 'content' => htmlspecialchars(self::$global->unoperated['systemconfig_content']),
  1375. ]
  1376. ];
  1377. Gateway::sendToClient($v['client_id'], json_encode($chat_message, 256));
  1378. }
  1379. }
  1380. }
  1381. // 循环检测会话时效.
  1382. foreach ($chatLog as $k => $v) {
  1383. $toWho = substr($v['to_id'], 0, 2);
  1384. // 如果对话为客服的最后一次对话且时间小于设定时间则结束工单.
  1385. if ($v['time_line'] <= $overtime) {
  1386. $found_key = array_search($v['servicelog_id'], array_column($serviceLog, 'servicelog_id'));
  1387. self::serverClose($serviceLog[$found_key]['client_id'], $v['servicelog_id']);
  1388. // 如果对话为客服的最后一次对话且时间小于设定时间前一分钟则给出提示.
  1389. } elseif ($v['time_line'] <= $setOvertime) {
  1390. $chat_message = [
  1391. 'message_type' => 'overtime',
  1392. 'data' => [
  1393. 'content' => htmlspecialchars(self::$global->overtime['systemconfig_content']),
  1394. ]
  1395. ];
  1396. $found_key = array_search($v['servicelog_id'], array_column($serviceLog, 'servicelog_id'));
  1397. Gateway::sendToClient($serviceLog[$found_key]['client_id'], json_encode($chat_message, 256));
  1398. }
  1399. }
  1400. }
  1401. //客服在线状态写组
  1402. private static function writeLogKfStatus($kf, $status, $flag = 1)
  1403. {
  1404. if ($flag == 1) {
  1405. $status = intval($status);
  1406. if ($status == 0) {
  1407. self::$db->delete('ws_kfonline')->where("uid='$kf'")->query();
  1408. } else {
  1409. $now = date('Y-m-d H:i;s');
  1410. $sql = "insert into ws_kfonline(uid,status,uptime) values('$kf',$status,'$now') ON DUPLICATE KEY UPDATE status=$status,uptime='$now' ";
  1411. self::$db->query($sql);
  1412. }
  1413. } else {
  1414. self::$db->query("delete from ws_kfonline ");
  1415. }
  1416. }
  1417. //用户下线通知
  1418. private static function userCloseNotice($client_id, $cuid, $group)
  1419. {
  1420. }
  1421. //踢掉同一用户的旧用户
  1422. private static function tickOlduser($uid)
  1423. {
  1424. }
  1425. }