Events.php 53 KB

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