Events.php 42 KB

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