Events.php 46 KB

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