Events.php 55 KB

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