Events.php 58 KB

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