Events.php 56 KB

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