Events.php 56 KB

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