Events.php 54 KB

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