Events.php 52 KB

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