Events.php 59 KB

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