Events.php 63 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766
  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. use Workerman\Worker;
  23. /**
  24. * 主逻辑
  25. * 主要是处理 onConnect onMessage onClose 三个方法
  26. * onConnect 和 onClose 如果不需要可以不用实现并删除
  27. */
  28. class Events
  29. {
  30. /**
  31. * 新建一个类的静态成员,用来保存数据库实例
  32. */
  33. public static $db = null;
  34. public static $global = null;
  35. public static $redis = null;
  36. public static $logic = null;
  37. const KFINFOKEY = 'KFINFO'; //客服信息hash表
  38. const USERINFOKEY = 'USERINFO'; //用户信息hash表
  39. const USERLIST = 'USERLIST'; //用户排队表
  40. const SERVICELOG = 'SERVICELOG'; //工单信息
  41. const WEBSOCKALLUSER = 'WEBSOCKALLUSER'; //所有连接
  42. /**
  43. * 进程启动后初始化数据库连接
  44. */
  45. public static function onWorkerStart($worker)
  46. {
  47. include_once(__DIR__ . DIRECTORY_SEPARATOR . "Mlogic.php");
  48. self::$logic = Mlogic::GetInstance();
  49. self::$db = self::$logic->getDb();
  50. self::$redis = self::$logic->getRedis();
  51. self::$global = self::$logic->getGlbData();
  52. self::TimerThing($worker);
  53. }
  54. /**
  55. * 每分钟定时向客服发送一次排队情况
  56. */
  57. public static function lineup()
  58. {
  59. $group = self::$global->groupmap;
  60. foreach ($group as $groupid => $gname) {
  61. $users = self::getUselistData($groupid);
  62. if (!empty($users)) {
  63. Gateway::sendToGroup('group_' . $groupid, json_encode(['type' => 'lineupCount', count($users)], 256));
  64. }
  65. }
  66. }
  67. /**
  68. * 当客户端连接时触发
  69. * 如果业务不需此回调可以删除onConnect
  70. *
  71. * @param int $client_id 连接id
  72. */
  73. public static function onConnect($client_id)
  74. {
  75. // 检测是否开启自动应答
  76. $sayHello = self::$global->replay['1'];
  77. if (!empty($sayHello) && 1 == $sayHello['status']) {
  78. $hello = [
  79. 'message_type' => 'helloMessage',
  80. 'data' => [
  81. 'name' => '智能助手',
  82. 'time' => date('H:i'),
  83. 'content' => $sayHello['word']
  84. ]
  85. ];
  86. Gateway::sendToClient($client_id, json_encode($hello, 256));
  87. unset($hello);
  88. }
  89. unset($sayHello);
  90. // 检测是否开启广告
  91. $advertisement = self::$db->query('select * from `ws_advertisement` where `advertisement_status` = 1');
  92. if (!empty($advertisement)) {
  93. $chat_message = [
  94. 'message_type' => 'advertisement',
  95. 'data' => $advertisement
  96. ];
  97. Gateway::sendToClient($client_id, json_encode($chat_message, 256));
  98. unset($chat_message);
  99. }
  100. unset($advertisement);
  101. self::$redis->hset(self::WEBSOCKALLUSER, $client_id, json_encode(array_merge($_SERVER, ['time' => date('H:i:s')])));
  102. }
  103. /**
  104. * 当客户端发来消息时触发
  105. * @param int $client_id 连接id
  106. * @param mixed $message 具体消息
  107. */
  108. public static function onMessage($client_id, $message)
  109. {
  110. if ($message == '{"type":"ping"}') {
  111. Gateway::sendToCurrentClient('{"type":"pong"}');
  112. return;
  113. } else {
  114. self::DebugOut($message, "OnMessage");
  115. }
  116. //echo(Gateway::getAllClientCount());
  117. $message = json_decode($message, true);
  118. if (isset($message['type'])) {
  119. switch ($message['type']) {
  120. case 'mydebug':
  121. self::mydebug($client_id, $message['data']);
  122. break;
  123. // 管理员初始化
  124. case 'adminInit':
  125. $token = $message['token'];
  126. self::adminInit($client_id, $token);
  127. break;
  128. // 客服初始化
  129. case 'init':
  130. $data = $message['data'];
  131. self::Kfinit($client_id, $data);
  132. break;
  133. // 顾客初始化
  134. case 'userInit';
  135. $data = $message['data'];
  136. self::userInitEnt($client_id, $data);
  137. break;
  138. //在线客服信息
  139. case 'getkfonlines':
  140. Gateway::sendToCurrentClient(json_encode(self::getkfonlines(), 256));
  141. break;
  142. //客服获取用户详细信息
  143. case 'kfgetuserinfo':
  144. $tmp_id = isset($message['data']['id']) ? $message['data']['id'] : 0;
  145. self::kfgetuserinfo($client_id, intval($tmp_id));
  146. break;
  147. // 客服聊天
  148. case 'chatMessage':
  149. self::chatMessage($message['data']);
  150. break;
  151. // 机器人问答.
  152. case 'toRobot':
  153. self::toRobot($client_id, $message);
  154. break;
  155. // 评价.
  156. case 'evaluate':
  157. self::evaluate($message['data']);
  158. break;
  159. // 客服关闭会话.
  160. case 'kfCloseUser':
  161. self::serverClose($message['data']['conversationId'], 3);
  162. break;
  163. // 客服更改状态.
  164. case 'kfOnline':
  165. self::KFStatusCg($client_id, $message);
  166. break;
  167. case 'changeOtherhKeFu';
  168. self::changeOtherhKeFu($client_id, $message);
  169. break;
  170. // 弹出评价.
  171. case 'getEvaluate';
  172. self::getEvaluate($message['data']);
  173. break;
  174. }
  175. }
  176. return true;
  177. }
  178. // 弹出评价.
  179. public static function getEvaluate($message)
  180. {
  181. // 获取当前会话工单.
  182. $data = json_decode(self::$redis->HGET('SERVICELOG', $message['conversationId']), true);
  183. if (empty($data)) {
  184. return;
  185. }
  186. $chat_message = [
  187. 'message_type' => 'getEvaluate',
  188. 'data' => [
  189. 'content' => '欢迎你的咨询,请对我们的服务做出评价',
  190. ]
  191. ];
  192. Gateway::sendToClient($data['client_id'], json_encode($chat_message, 256));
  193. }
  194. //客服聊天
  195. public static function chatMessage($message)
  196. {
  197. // 获取当前会话工单.
  198. $data = json_decode(self::$redis->HGET('SERVICELOG', $message['conversationId']), true);
  199. if (empty($data)) {
  200. return;
  201. }
  202. $chat_message = [
  203. 'message_type' => 'chatMessage',
  204. 'data' => [
  205. 'name' => $message['from_name'],
  206. 'id' => $message['from_id'],
  207. 'time' => date('H:i'),
  208. 'content' => $message['content'],
  209. ]
  210. ];
  211. // 是否为第一次回复.
  212. if (isset($message['isFirst']) && $message['isFirst']) {
  213. $data['alarm_corresponding'] = time() - $data['start_time'];
  214. $data['alarm_respond'] = 2;
  215. }
  216. // 发送消息.
  217. if (substr($message['from_id'], 0, 2) === 'KF') {
  218. // 统计敏感词.
  219. $data['alarm_serverSensitive'] += $message['sensitiveNumber'];
  220. $data['serverLastTime'] = time();
  221. Gateway::sendToClient($data['client_id'], json_encode($chat_message, 256));
  222. } else {
  223. // 统计敏感词.
  224. $data['alarm_userSensitive'] += $message['sensitiveNumber'];
  225. $data['userLastTime'] = time();
  226. Gateway::sendToClient($data['kf_client_id'], json_encode($chat_message, 256));
  227. }
  228. // 返回当前时间
  229. $chat_message = [
  230. 'message_type' => 'webTime',
  231. 'data' => [
  232. 'webTime' => date('H:i'),
  233. ]
  234. ];
  235. Gateway::sendToCurrentClient(json_encode($chat_message, 256));
  236. // 保存修改后的工单信息.
  237. self::$redis->HSET('SERVICELOG', $message['conversationId'], json_encode($data, 256));
  238. // 聊天信息入库
  239. $insertChatData = [
  240. 'from_id' => $message['from_id'],
  241. 'from_name' => $message['from_name'],
  242. 'to_id' => $message['to_id'],
  243. 'to_name' => $message['to_name'],
  244. 'content' => $message['content'],
  245. 'servicelog_id' => $message['conversationId'],
  246. 'time_line' => time()
  247. ];
  248. self::$db->insert('ws_chat_log')->cols($insertChatData)->query();
  249. }
  250. //得到一个用户详细信息
  251. public static function kfgetuserinfo($clientid, $id)
  252. {
  253. $ret = self::$db->select('*')->from('ws_account')->where('id=:id')->bindValues(['id' => $id])->row();
  254. Gateway::sendToClient($clientid, json_encode(['message_type' => 'userdetailinfo', 'data' => $ret]));
  255. return;
  256. }
  257. //获取在线客服列表
  258. public static function getkfonlines()
  259. {
  260. $return = [
  261. 'message_type' => 'onlinekfs',
  262. 'data' => [],
  263. ];
  264. $nowkfid = isset($_SESSION['uid']) ? $_SESSION['uid'] : 0;
  265. $fromgrouupid = isset($_SESSION['group']) ? $_SESSION['group'] : 0;
  266. if (empty($fromgrouupid) || empty($nowkfid)) {
  267. return $return;
  268. }
  269. $online = self::getOnlineKfData(0, 1);
  270. if (empty($online)) {
  271. return $return;
  272. }
  273. $groupnamemap = self::$global->groupmap;
  274. $ret = [];
  275. foreach ($online as $uinfo) {
  276. if ($nowkfid == $uinfo['id']) {
  277. continue;
  278. }
  279. $ret[] = ['groupid' => $uinfo['group'], 'groupname' => $groupnamemap[$uinfo['group']], 'kfuid' => $uinfo['id'], 'kfname' => $uinfo['name'], 'kfjobname' => $uinfo['job_name']];
  280. }
  281. $return['data'] = $ret;
  282. return $return;
  283. }
  284. public static function KFStatusCg($client_id, $message)
  285. {
  286. if (!isset($_SESSION['iskefu']) || $_SESSION['iskefu'] != 1) {
  287. return;
  288. }
  289. $userId = $message['data']['uid'];
  290. $status = intval($message['data']['status']);
  291. if (!in_array($status, [1, 2, 3])) {
  292. return false;
  293. }
  294. $oldstatus = '';
  295. $kfinfo = self::$redis->hget(self::KFINFOKEY, $userId);
  296. if (empty($kfinfo)) {
  297. return false;
  298. }
  299. $kfinfo = json_decode($kfinfo, true);
  300. if (!$kfinfo) {
  301. return false;
  302. }
  303. if ($kfinfo['status'] != $status) {
  304. $oldstatus = $kfinfo['status'];
  305. $kfinfo['status'] = $status;
  306. self::$redis->hset(self::KFINFOKEY, $userId, json_encode($kfinfo, 256));
  307. }
  308. self::writeLogKfStatus($userId, $status);
  309. Gateway::sendToCurrentClient(json_encode(['message_type' => 'cgstatus', 'data' => ['new_status' => $status, 'old_status' => $oldstatus]]));
  310. return;
  311. }
  312. //获取某个用户全部信息
  313. public static function getClientIndo($id)
  314. {
  315. $ret = self::$db->from('ws_accounts')->select("*")->where(['id' => $id])->row();
  316. return $ret;
  317. }
  318. //客服接入sock,及初始化
  319. public static function Kfinit($client_id, $message)
  320. {
  321. $uid = self::getPars($message, 'uid');
  322. $group = intval(self::getPars($message, 'group', 0));
  323. if (empty($uid) || empty($group) || !isset(self::$global->groupmap[$group])) {
  324. self::MySendMsg($client_id, json_encode(["message_type" => 'checkfalse', 'data' => "客服登陆参数错误"], 256));
  325. Gateway::closeCurrentClient();
  326. return;
  327. }
  328. $loginstate = self::$logic->userIsLogin($client_id, $uid, $group);
  329. if ($loginstate == 1) {
  330. self::MySendMsg($client_id, (json_encode(['message_type' => 'reLoginErr', 'msg' => '正在登陆中,请稍后...'], 256)));
  331. Gateway::closeClient($client_id);
  332. return;
  333. }
  334. //客服登陆验证 不符合的直接断掉
  335. $kfinfo = self::KfloginCheck($client_id, $message);
  336. if (empty($kfinfo)) {
  337. self::MySendMsg($client_id, json_encode(["message_type" => 'checkfalse', 'data' => "验证失败"], 256));
  338. Gateway::closeCurrentClient();
  339. return true;
  340. } elseif ($kfinfo['status'] != 1) {
  341. self::MySendMsg($client_id, json_encode(["message_type" => 'checkfalse', 'data' => "禁用中..."], 256));
  342. Gateway::closeCurrentClient();
  343. return true;
  344. }
  345. if ($loginstate == 2) {
  346. $oldcontids = Gateway::getClientIdByUid($uid);
  347. Gateway::sendToClient($oldcontids['0'], (json_encode(['message_type' => 'reLoginErr', 'msg' => '你的账号在其它登陆,本次下线'], 256)));
  348. Gateway::closeClient($oldcontids['0']);
  349. sleep(2);
  350. }
  351. self::$redis->hset('loginTmp:' . $uid, 'uid', time());
  352. self::$redis->expire('loginTmp:' . $uid, 5);
  353. $newinfo =
  354. [
  355. 'id' => 'KF' . $kfinfo['id'],
  356. 'name' => $kfinfo['user_name'],
  357. 'job_name' => $kfinfo['user_job_number'],
  358. 'avatar' => $kfinfo['user_avatar'],
  359. 'group' => $group,
  360. 'client_id' => $client_id,
  361. 'task' => 0,
  362. 'intime' => time(),
  363. 'signature' => $kfinfo['signature'],
  364. 'status' => 2, // 1为在线(接收分配、接收消息)2为隐身(不接收分配、只接收消息)3、休息
  365. 'user_info' => [], //在会话的用户cid key为clientid ,值为工单号
  366. ];
  367. self::$redis->hset(self::KFINFOKEY, $uid, json_encode($newinfo, 256));
  368. $_SESSION['info'] = $newinfo;
  369. // 绑定 client_id 和 uid
  370. Gateway::bindUid($client_id, $message['uid']);
  371. $_SESSION['group'] = $message['group'];
  372. $_SESSION['iskefu'] = 1;
  373. $_SESSION['uid'] = $message['uid'];
  374. $_SESSION['name'] = $message['name'];
  375. Gateway::joinGroup($client_id, 'group_' . $message['group']);
  376. $chat_message = [
  377. 'message_type' => 'loginSuccess',
  378. ];
  379. self::MySendMsg($client_id, json_encode($chat_message, 256));
  380. unset($chat_message);
  381. self::writeLogKfStatus($message['uid'], 2);
  382. return;
  383. }
  384. /**
  385. * 管理员登陆验证
  386. * @param $client_id 服务ID
  387. * @param $message 数据
  388. */
  389. public static function adminInit($client_id, $token)
  390. {
  391. // 查询token是否存在.
  392. $systemConfigData = self::$db->query("SELECT `id` FROM `ws_admins` where `token`= '$token'");
  393. if ($systemConfigData) {
  394. self::$redis->sadd('adminList', $client_id);
  395. self::systemMonitoring([$client_id]);
  396. } else {
  397. $chat_message = [
  398. 'message_type' => 'tips',
  399. 'data' => '管理员不存在'
  400. ];
  401. Gateway::sendToClient($client_id, json_encode($chat_message, 256));
  402. Gateway::closeClient($client_id);
  403. }
  404. }
  405. //客服登陆验证
  406. public static function KfloginCheck($client, $messageArray)
  407. {
  408. $uid = isset($messageArray['uid']) ? $messageArray['uid'] : '';
  409. $token = isset($messageArray['token']) ? $messageArray['token'] : '';
  410. if (empty($uid) || empty($token)) {
  411. return false;
  412. }
  413. $expire_time_vali = time() - 60 * 60 * 24;
  414. $kfid = intval(substr($uid, 2));
  415. $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();
  416. if ($ret) {
  417. self::$db->update('ws_users')->cols(array('online_status' => 1, 'online_connectid' => $client))->where('id=' . $kfid)->query();
  418. return $ret;
  419. }
  420. return false;
  421. }
  422. //用户发送邦定用户事件
  423. public static function userInitEnt($client_id, $message)
  424. {
  425. $uid = intval($message['uid']);
  426. $group = intval($message['group']);
  427. if (!isset(self::$global->groupmap[$group])) {
  428. self::MySendMsg($client_id, (json_encode(['message_type' => 'reLoginErr', 'msg' => '不存在客服组....'], 256)));
  429. return true;
  430. //Gateway::closeCurrentClient();
  431. }
  432. $loginstate = self::$logic->userIsLogin($client_id, $uid, $group);
  433. if ($loginstate == 1) {
  434. self::MySendMsg($client_id, (json_encode(['message_type' => 'reLoginErr', 'msg' => '正在登陆中,请稍后...'], 256)));
  435. Gateway::closeCurrentClient();
  436. return;
  437. }
  438. $hisdata = self::$redis->hget(self::USERINFOKEY, $uid);
  439. if ($hisdata) {
  440. $hisdata = json_decode($hisdata, true);
  441. $oldclientid = $hisdata['client_id'];
  442. self::MySendMsg($oldclientid, json_encode(['type' => 'reLoginErr', 'msg' => '相同账号登陆,本次退出'], 256));
  443. self::MySendMsg($client_id, json_encode(['type' => 'reLoginErr', 'msg' => '相同账号登陆,本次退出'], 256));
  444. Gateway::closeClient($oldclientid);
  445. Gateway::closeCurrentClient();
  446. return;
  447. }
  448. $last = self::UserHasOldTalk($uid);
  449. $onlinekf = self::getOnlineKfData($group, 1);
  450. if (empty($onlinekf)&&empty($last)) {
  451. Gateway::sendToClient($client_id, json_encode(['message_type' => 'notice', 'content' => '暂时没有客服上班,请稍后再咨询。'], 256));
  452. //Gateway::closeClient($client_id);
  453. return;
  454. }
  455. self::$redis->hset('loginTmp:' . $uid, 'uid', time());
  456. self::$redis->expire('loginTmp:' . $uid, 5);
  457. $data = [
  458. 'id' => $uid,
  459. 'name' => $message['name'],
  460. 'avatar' => $message['avatar'],
  461. 'website' => $_SESSION['origin'],//$message['website'],
  462. 'browse' => Gateway::browse_info(),
  463. 'system' => Gateway::get_os(),//$message['system'],
  464. 'ip' => isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '',//message['ip'],
  465. 'group' => $message['group'],
  466. 'intime' => time(),
  467. 'kfuid' => '',
  468. 'ip' => $_SESSION['remotip'],
  469. 'serverid' => 0,
  470. 'client_id' => $client_id
  471. ];
  472. self::$redis->hset(self::USERLIST, $uid, json_encode($data, 256));
  473. self::$redis->hset(self::USERINFOKEY, $uid, json_encode($data, 256));
  474. // 写入接入值
  475. $key = date('Ymd') . 'total_in';
  476. self::$global->increment($key);
  477. // 绑定 client_id 和 uid
  478. Gateway::bindUid($client_id, $uid);
  479. $_SESSION['iskefu'] = 0;
  480. $_SESSION['uid'] = $message['uid'];
  481. // 尝试分配新会员进入服务
  482. self::userOnlineTask($group, $uid, $last, $client_id);
  483. }
  484. /**
  485. * 当用户断开连接时触发
  486. * @param int $client_id 连接id
  487. *
  488. * tips: 当服务端主动退出的时候,会出现 exit status 9.原因是:服务端主动断开之后,连接的客户端会走这个方法,而短时间内进程
  489. * 需要处理这多的逻辑,又有cas操作,导致进程退出会超时,然后会被内核杀死,从而报出错误 9.实际对真正的业务没有任何的影响。
  490. */
  491. public static function onClose($client_id)
  492. {
  493. self::$redis->hdel(self::WEBSOCKALLUSER, $client_id);
  494. $isKefuoff = isset($_SESSION['iskefu']) ? $_SESSION['iskefu'] : 0;
  495. $uid = isset($_SESSION['uid']) ? $_SESSION['uid'] : false;
  496. echo "下线:uid: $uid - cid: $client_id - iskf: $isKefuoff \n";
  497. $isAdmin = self::$redis->sismember('adminList', $client_id);
  498. if ($isAdmin) {
  499. self::$redis->srem('adminList', $client_id);
  500. }
  501. if (empty($uid)) {
  502. return true;
  503. }
  504. if ($isKefuoff) {
  505. self::serviceOffline($client_id, $uid);
  506. } else {
  507. self::guestOffline($client_id, $uid);
  508. }
  509. return true;
  510. }
  511. //客服下线了 系统调用,不能手动调用
  512. public static function serviceOffline($client_id, $uid)
  513. {
  514. $group = $_SESSION['group'];
  515. $uinfo = self::$redis->hget(self::KFINFOKEY, $uid);
  516. self::$redis->hdel(self::KFINFOKEY, $uid);
  517. $uinfo = json_decode($uinfo, true);
  518. if (empty($uinfo)) {
  519. echo "客服发生异常退出\n";
  520. return;
  521. }
  522. $user_info = $uinfo['user_info'];
  523. $kfid = self::getkfid($uid);
  524. $now = time();
  525. $starttime = $now - 86400 * 7;
  526. self::$redis->hset('loginTmp:' . $uid, 'uid', time());
  527. self::$redis->expire('loginTmp:' . $uid, 5);
  528. if (!empty($user_info)) {
  529. foreach ($user_info as $val => $serverid) {
  530. self::insertServerLog($serverid, 4);
  531. self::$redis->hdel(self::SERVICELOG, intval($serverid));
  532. self::MySendMsg($val, json_encode(['message_type' => 'serviceoffline', 'msg' => '客户人员下线!'], 256));
  533. Gateway::closeClient($val);
  534. }
  535. }
  536. $sql = "update `ws_service_log` set `status` = '2',end_time=$now,`servicelog_close_type` = 4 where start_time>=$starttime and kf_id=$kfid and group_id=$group and `status`!=2 ";
  537. echo "客服退出: " . $uid . "\n";
  538. self::$db->query($sql);
  539. self::$db->update('ws_users')->cols(array('online_status' => 0, 'online_connectid' => ''))->where('id=' . $kfid)->query();
  540. self::writeLogKfStatus($uid, 0);
  541. return;
  542. }
  543. //用户下线了 系统调用,不能手动调用
  544. public static function guestOffline($client_id, $uid)
  545. {
  546. self::$redis->hset('loginTmp:' . $uid, 'uid', time());
  547. self::$redis->expire('loginTmp:' . $uid, 3);
  548. $uid = intval($uid);
  549. $krclient_id = 0;
  550. $data = self::$redis->hget(self::USERINFOKEY, $uid);
  551. if (empty($data)) {
  552. return;
  553. }
  554. $info = json_decode($data, true);
  555. self::$redis->hdel(self::USERLIST, $uid);
  556. self::$redis->hdel(self::USERINFOKEY, $uid);
  557. if (!empty($info['kfuid'])) {
  558. $kfinfo = self::$redis->hget(self::KFINFOKEY, $info['kfuid']);
  559. if (!empty($kfinfo)) {
  560. $kfinfoArr = json_decode($kfinfo, true);
  561. $krclient_id = $kfinfoArr['client_id'];
  562. /*$kfinfoArr['user_info'] = self::ArrayDataopt($kfinfoArr['user_info'], $client_id, 0);
  563. $kfinfoArr['task'] = count($kfinfoArr['user_info']);
  564. self::$redis->hset(self::KFINFOKEY, $info['kfuid'], json_encode($kfinfoArr, 256));*/
  565. }
  566. }
  567. $chat_message = [
  568. 'message_type' => 'userClose',
  569. 'data' => [
  570. 'content' => '用户连接已断开',
  571. 'id' => $uid,
  572. 'time' => date('H:i'),
  573. ]
  574. ];
  575. $now = time();
  576. $serverid = intval($info['serverid']);
  577. if ($serverid) {
  578. $sql = "update `ws_service_log` set `status` = '3' where servicelog_id=$serverid and `status` !=2 ";
  579. self::$db->query($sql);
  580. }
  581. if ($krclient_id) {
  582. Gateway::sendToClient($krclient_id, json_encode($chat_message, 256));
  583. }
  584. return;
  585. }
  586. /**
  587. * 客服结束会话
  588. *
  589. * tips: 未有$client_id的关闭
  590. */
  591. public static function closeUser($servicelog_id, $userId, $kf_id, $groupId)
  592. {
  593. }
  594. /**
  595. * 工单结束
  596. * @param int $client_id 连接id
  597. *
  598. * tips: 当服务端主动退出的时候,会出现 exit status 9.原因是:服务端主动断开之后,连接的客户端会走这个方法,而短时间内进程
  599. * 需要处理这多的逻辑,又有cas操作,导致进程退出会超时,然后会被内核杀死,从而报出错误 9.实际对真正的业务没有任何的影响。
  600. */
  601. public static function serverClose($servicelogId, $closeBy = 0)
  602. {
  603. // 获取当前工单数据.
  604. $data = json_decode(self::$redis->HGET('SERVICELOG', $servicelogId), true);
  605. if (empty($data)) {
  606. return;
  607. }
  608. // 获取当前客服.
  609. $kfInfo = json_decode(self::$redis->HGET('KFINFO', 'KF' . $data['kf_id']), true);
  610. if (empty($kfInfo)) {
  611. return;
  612. }
  613. // 删除当前工单.
  614. self::$redis->hdel('SERVICELOG', $servicelogId);
  615. // 当前服务客服删除当前人员.
  616. $kfUserList = self::ArrayDataopt($kfInfo['user_info'], $data['client_id'], 0);
  617. // 删除当前人员信息.
  618. self::$redis->hdel('USERINFO', $data['user_id']);
  619. // 当前客服所接待人员.
  620. $kfInfo['user_info'] = $kfUserList;
  621. $kfInfo['task'] = count($kfUserList);
  622. // 存入客服信息.
  623. self::$redis->HSET('KFINFO', 'KF' . $data['kf_id'], json_encode($kfInfo, 256));
  624. // 发送消息给用户.
  625. $chat_message = [
  626. 'message_type' => 'closeBysever',
  627. 'data' => [
  628. 'content' => '客服停止了该会话',
  629. 'time' => date('H:i'),
  630. ]
  631. ];
  632. Gateway::sendToClient($data['client_id'], json_encode($chat_message, 256));
  633. // 关闭用户连接.
  634. Gateway::closeClient($data['client_id']);
  635. // 发送消息给客服.
  636. $del_message = [
  637. 'message_type' => 'delUser',
  638. 'data' => [
  639. 'id' => $data['user_id']
  640. ]
  641. ];
  642. Gateway::sendToClient($data['kf_client_id'], json_encode($del_message, 256));
  643. // 查询工单会话总数.
  644. $chatCount = self::$db->select('count(*) as count')->from('ws_chat_log')->where("servicelog_id=$servicelogId")->row();
  645. // 将数据存入数据库.
  646. $updateServiceLogData = [
  647. 'status' => 2,
  648. 'evaluate_id' => isset($data['evaluate_id']) ? $data['evaluate_id'] : 0,
  649. 'evaluate_content' => isset($data['evaluate_content']) ? $data['evaluate_content'] : '',
  650. 'servicelog_close_type' => $closeBy,
  651. 'end_time' => time(),
  652. ];
  653. $updataAlarmData = [
  654. 'alarm_userSensitive' => $data['alarm_userSensitive'],
  655. 'alarm_serverSensitive' => $data['alarm_serverSensitive'],
  656. 'alarm_corresponding' => $data['alarm_corresponding'],
  657. 'alarm_cvtOvertime' => time() - $data['start_time'],
  658. 'alarm_respond' => $data['alarm_respond'],
  659. 'alarm_lineTime' => $data['start_time'] - $data['intime'],
  660. 'alarm_count' => $chatCount['count'],
  661. ];
  662. self::$db->update('ws_service_log')->cols($updateServiceLogData)->where("servicelog_id=$servicelogId")->query();
  663. self::$db->update('ws_alarm')->cols($updataAlarmData)->where("servicelog_id=$servicelogId")->query();
  664. }
  665. /**
  666. * 修改工单数据库数据
  667. * @param int $client_id 连接id
  668. *
  669. * tips: 当服务端主动退出的时候,会出现 exit status 9.原因是:服务端主动断开之后,连接的客户端会走这个方法,而短时间内进程
  670. * 需要处理这多的逻辑,又有cas操作,导致进程退出会超时,然后会被内核杀死,从而报出错误 9.实际对真正的业务没有任何的影响。
  671. */
  672. public static function insertServerLog($servicelogId, $closeBy = 0)
  673. {
  674. // 获取当前工单数据.
  675. $data = json_decode(self::$redis->HGET('SERVICELOG', $servicelogId), true);
  676. if (empty($data)) {
  677. return;
  678. }
  679. // 查询工单会话总数.
  680. $chatCount = self::$db->select('count(*) as count')->from('ws_chat_log')->where("servicelog_id=$servicelogId")->row();
  681. // 将数据存入数据库.
  682. $updateServiceLogData = [
  683. 'status' => 2,
  684. 'evaluate_id' => isset($data['evaluate_id']) ? $data['evaluate_id'] : 0,
  685. 'evaluate_content' => isset($data['evaluate_content']) ? $data['evaluate_content'] : '',
  686. 'servicelog_close_type' => $closeBy,
  687. 'end_time' => time(),
  688. ];
  689. $updataAlarmData = [
  690. 'alarm_userSensitive' => $data['alarm_userSensitive'],
  691. 'alarm_serverSensitive' => $data['alarm_serverSensitive'],
  692. 'alarm_corresponding' => $data['alarm_corresponding'],
  693. 'alarm_cvtOvertime' => time() - $data['start_time'],
  694. 'alarm_respond' => $data['alarm_respond'],
  695. 'alarm_lineTime' => $data['start_time'] - $data['intime'],
  696. 'alarm_count' => $chatCount['count'],
  697. ];
  698. self::$db->update('ws_service_log')->cols($updateServiceLogData)->where("servicelog_id=$servicelogId")->query();
  699. self::$db->update('ws_alarm')->cols($updataAlarmData)->where("servicelog_id=$servicelogId")->query();
  700. }
  701. /**
  702. * 有人退出
  703. * @param $group
  704. */
  705. private static function userOfflineTask($group)
  706. {
  707. }
  708. /**
  709. * 有人进入执行分配
  710. * @param $client_id
  711. * @param $group
  712. * @param $uid
  713. */
  714. private static function userOnlineTask($group = 0, $uid = 0, $last=[], $client_id='')
  715. {
  716. $allusergkarr = self::getUserListData();
  717. if (empty($allusergkarr)) {
  718. return;
  719. }
  720. $allkfgkarr = self::getWorkKfData();
  721. if (empty($allkfgkarr)) {
  722. return;
  723. }
  724. $maxset = (self::$global->systemconfig)['KFMaxServices'] ?? 5;
  725. $maxset = intval($maxset);
  726. if ($group && $uid) {
  727. // 指定用指定组 [可能存在断线重连的情况] 如果存在旧的会话,直接连线客服和用户
  728. //否则按先到后到以及客服最大服务数限制
  729. if ($last) {
  730. self::BeginOldTalk(self::getkfuid($last['kf_id']), $uid, $last['group_id'], $last['servicelog_id']);
  731. $toOld_message = [
  732. 'message_type' => 'toOld',
  733. 'data' => [
  734. 'content' => '接入至未结束的会话'
  735. ]
  736. ];
  737. Gateway::sendToCurrentClient(json_encode($toOld_message, 256));
  738. return;
  739. } else {
  740. //系统定时调用时,无组,无用户
  741. foreach ($allusergkarr as $group => $gusersArr) {
  742. if (!isset($allkfgkarr[$group]) || count($allkfgkarr[$group]) <= 0) {
  743. //所属客服组无人在线
  744. continue;
  745. }
  746. $nowkfs = $allkfgkarr[$group];
  747. $count = count($nowkfs);
  748. $i = 0;
  749. foreach ($gusersArr as $user) {
  750. if ($nowkfs[$i]['task'] > $maxset) {
  751. break;
  752. }
  753. $nowkfs[$i]['task']++;
  754. self::BeginTalk($nowkfs[$i]['id'], $user['id'], $group, 0, $user);
  755. self::$redis->hdel(self::USERLIST, $user['id']);
  756. $i++;
  757. if ($i >= $count) {
  758. $i = 0;
  759. }
  760. }
  761. }
  762. return;
  763. }
  764. }
  765. }
  766. //开启一个会话
  767. private static function BeginTalk($kfuid, $uid, $group, $serviceid = 0, $userInfo = false)
  768. {
  769. $serviceid = intval($serviceid);
  770. if (!$userInfo) {
  771. $userInfo = json_decode(self::$redis->hget(self::USERINFOKEY, $uid), true);
  772. }
  773. $kfinfo = json_decode(self::$redis->hget(self::KFINFOKEY, $kfuid), true);
  774. if (empty($userInfo) || empty($kfinfo)) {
  775. return false;
  776. }
  777. $server = [];
  778. $armarr = [];
  779. if ($serviceid) {
  780. $server = self::$db->select('*')->from('ws_service_log')->where("servicelog_id=$serviceid ")->row();
  781. if ($server) {
  782. $armarr = self::$db->select('*')->from('ws_alarm')->where("servicelog_id=$serviceid ")->row();
  783. }
  784. }
  785. if (empty($server)) {
  786. $array = [
  787. 'user_id' => intval($uid),
  788. 'client_id' => $userInfo['client_id'],
  789. 'user_name' => $userInfo['name'],
  790. 'user_avatar' => $userInfo['avatar'],
  791. 'user_ip' => $userInfo['ip'],
  792. 'kf_id' => self::getkfid($kfuid),
  793. 'start_time' => time(),
  794. 'group_id' => $group ? $group : $userInfo['group'],
  795. 'website' => $userInfo['website'],
  796. 'system' => $userInfo['system'],
  797. 'browse' => $userInfo['browse'],
  798. 'intime' => $userInfo['intime'],
  799. 'status' => 1,
  800. 'evaluate_id' => 0,
  801. 'servicelog_close_type' => 0
  802. ];
  803. $serviceid = self::$db->insert('ws_service_log')->cols($array)->query();
  804. $server = array_merge(['servicelog_id' => $serviceid], $array);
  805. $armid = self::$db->insert('ws_alarm')->cols(['servicelog_id' => $serviceid])->query();
  806. $armarr = self::$db->select('*')->from('ws_alarm')->where("alarm_id=$armid")->row();
  807. }
  808. $redisData = array_merge($server, $armarr, ['kf_client_id' => $kfinfo['client_id'], 'server_name' => $kfinfo['name']]);
  809. self::$redis->hset(self::SERVICELOG, $serviceid, json_encode($redisData, 256));
  810. $kfinfo['user_info'] = array_merge($kfinfo['user_info'], [$userInfo['client_id'] => $serviceid]);
  811. $kfinfo['task'] = count($kfinfo['user_info']);
  812. self::$redis->hset(self::KFINFOKEY, $kfuid, json_encode($kfinfo, 256));
  813. $userInfo['serverid'] = $serviceid;
  814. $userInfo['kfuid'] = $kfuid;
  815. self::$redis->hset(self::USERINFOKEY, $uid, json_encode($userInfo, 256));
  816. // 通知会员发送信息绑定客服的id
  817. $noticeUser = [
  818. 'message_type' => 'connect',
  819. 'data' => [
  820. 'kf_id' => $kfuid,
  821. 'conversationId' => $serviceid,
  822. 'serverInfo' => $kfinfo,
  823. 'kf_name' => $kfinfo['job_name']
  824. ]
  825. ];
  826. self::MySendMsg($userInfo['client_id'], json_encode($noticeUser, 256));
  827. $sayHello = (self::$global->replay)['2'];
  828. if (!empty($sayHello) && 1 == $sayHello['status']) {
  829. $chat_message = [
  830. 'message_type' => 'chatMessage',
  831. 'data' => [
  832. 'id' => self::getkfuid($kfinfo['id']),
  833. 'name' => $kfinfo['name'],
  834. 'time' => date('H:i'),
  835. 'content' => $sayHello['word']
  836. ]
  837. ];
  838. self::MySendMsg($userInfo['client_id'], json_encode($chat_message, 256));
  839. unset($chat_message);
  840. }
  841. $noticeKf = [
  842. 'message_type' => 'connect',
  843. 'data' => [
  844. 'user_info' => $userInfo,
  845. 'conversationId' => $serviceid,
  846. ]
  847. ];
  848. self::MySendMsg($kfinfo['client_id'], json_encode($noticeKf, 256));
  849. unset($noticeKf);
  850. $key = date('Ymd') . 'success_in';
  851. self::$global->increment($key);
  852. return;
  853. }
  854. //连接至上一个会话
  855. private static function BeginOldTalk($kfuid, $uid, $group, $serviceid = 0, $userInfo = false)
  856. {
  857. $serviceid = intval($serviceid);
  858. $userInfo = json_decode(self::$redis->hget(self::USERINFOKEY, $uid), true);
  859. $kfinfo = json_decode(self::$redis->hget(self::KFINFOKEY, $kfuid), true);
  860. if (empty($userInfo) || empty($kfinfo)) {
  861. return false;
  862. }
  863. // 获取旧工单信息.
  864. $data = json_decode(self::$redis->HGET('SERVICELOG', $last['servicelog_id']), true);
  865. // 修改工单数据.
  866. $data['user_avatar'] = $userInfo['avatar'];
  867. $data['client_id'] = $userInfo['client_id'];
  868. $data['user_ip'] = $userInfo['ip'];
  869. $data['website'] = $userInfo['website'];
  870. $data['system'] = $userInfo['system'];
  871. $data['browse'] = $userInfo['browse'];
  872. $data['status'] = $userInfo['status'];
  873. self::$redis->hset(self::SERVICELOG, $serviceid, json_encode($data, 256));
  874. // 更改用户连接客服信息
  875. $userInfo['serverid'] = $serviceid;
  876. $userInfo['kfuid'] = $kfuid;
  877. self::$redis->hset(self::USERINFOKEY, $uid, json_encode($userInfo, 256));
  878. // 更改客服连接信息.
  879. $kfinfo = json_decode(self::$redis->hget(self::KFINFOKEY, $kfuid), true);
  880. $kfUsers = json_decode($kfinfo['user_info'], true);
  881. foreach ($kfUsers as $key => $value) {
  882. if ($value == $uid) {
  883. // 删除之前的当前用户连接
  884. unset($kfUsers[$key]);
  885. }
  886. }
  887. // 增加现在用户的连接到客服
  888. $kfUsers[$userInfo['client_id']] = $uid;
  889. $kfinfo['user_info'] = $kfUsers;
  890. // 将数据存入redis
  891. self::$redis->hset('KFINFO', $kfuid, json_encode($kfinfo, 256));
  892. // 通知会员发送信息绑定客服的id
  893. $noticeUser = [
  894. 'message_type' => 'connect',
  895. 'data' => [
  896. 'kf_id' => $kfuid,
  897. 'conversationId' => $serviceid,
  898. 'serverInfo' => $kfinfo,
  899. 'kf_name' => $kfinfo['job_name']
  900. ]
  901. ];
  902. self::MySendMsg($userInfo['client_id'], json_encode($noticeUser, 256));
  903. // 发送给客服用户信息.
  904. $noticeKf = [
  905. 'message_type' => 'connect',
  906. 'data' => [
  907. 'user_info' => $userInfo,
  908. 'conversationId' => $serviceid,
  909. ]
  910. ];
  911. self::MySendMsg($kfinfo['client_id'], json_encode($noticeKf, 256));
  912. unset($noticeKf);
  913. $key = date('Ymd') . 'success_in';
  914. self::$global->increment($key);
  915. return;
  916. }
  917. //用户排队数据 按组
  918. private static function getUserListData()
  919. {
  920. $alluser = self::$redis->hgetall(self::USERLIST);
  921. if (empty($alluser)) {
  922. return false;
  923. }
  924. $allusergkarr = [];
  925. foreach ($alluser as $val) {
  926. $now = json_decode($val, true);
  927. if ($now) {
  928. //用户分组后的数组
  929. $allusergkarr[$now['group']][] = $now;
  930. }
  931. }
  932. foreach ($allusergkarr as $group => $nowgroups) {
  933. usort($allusergkarr[$group], function ($a, $b) {
  934. if ($a['intime'] == $b['intime']) {
  935. return 0;
  936. }
  937. return ($a['intime'] > $b['intime']) ? 1 : -1;
  938. });
  939. }
  940. if (!$allusergkarr) {
  941. return false;
  942. }
  943. unset($alluser);
  944. return $allusergkarr;
  945. }
  946. //找到可以接工单的客服 按组
  947. private static function getWorkKfData()
  948. {
  949. $allkfs = self::$redis->hgetall(self::KFINFOKEY);
  950. if (empty($allkfs)) {
  951. return false;
  952. }
  953. $allkfgkarr = [];
  954. foreach ($allkfs as $val) {
  955. $now = json_decode($val, true);
  956. if ($now && $now['status'] == 1) {
  957. //客分组后的数组
  958. $allkfgkarr[$now['group']][] = $now;
  959. }
  960. }
  961. if (!$allkfgkarr) {
  962. return false;
  963. }
  964. //客服每组按任务数由小到大排序 任务相同时按时间先后顺序
  965. foreach ($allkfgkarr as $group => $nowgroups) {
  966. usort($allkfgkarr[$group], function ($a, $b) {
  967. if ($a['task'] == $b['task']) {
  968. if ($a['intime'] == $b['intime']) {
  969. return 0;
  970. }
  971. return ($a['intime'] > $b['intime']) ? 1 : -1;
  972. }
  973. return ($a['task'] > $b['task']) ? 1 : -1;
  974. });
  975. }
  976. unset($allkfs);
  977. return $allkfgkarr;
  978. }
  979. //找到用户是否有一条未关闭的会话
  980. private static function UserHasOldTalk($uid)
  981. {
  982. $uid = intval($uid);
  983. $start_time = time() - 86400;
  984. $ret = self::$db->select('*')->from('ws_service_log')->where("start_time>=$start_time and user_id=$uid and status!=2 ")->orderByDESC(['servicelog_id'])->row();
  985. return $ret;
  986. }
  987. //今天排序累加
  988. private static function todayqueuelength()
  989. {
  990. $dtype = 'user.queue.day.length';
  991. $today = date("Y-m-d");
  992. $sret = self::$db->select('*')->from('ws_countmidtable')->where('dtype=:dtype and mdate=:mdate')->bindValues(array('dtype' => $dtype, 'mdate' => $today))->row();
  993. if ($sret) {
  994. self::$db->update('ws_countmidtable')->cols(array('dcontent' => intval($sret['dcontent']) + 1))->where('id=' . $sret['id'])->query();
  995. } else {
  996. self::$db->insert('ws_countmidtable')->cols(array(
  997. 'dtype' => $dtype,
  998. 'mdate' => $today,
  999. 'datatype' => 1,
  1000. 'dcontent' => 1))->query();
  1001. }
  1002. }
  1003. //客服工单转单
  1004. private static function servicetrutoother($type, $owen, $otherkfid, $serverid, $clientuid)
  1005. {
  1006. $owen = intval(substr($owen, 2));
  1007. $otherkfid = intval(substr($otherkfid, 2));
  1008. self::$db->insert('ws_serviceturn_log')->cols(array(
  1009. 'stype' => $type,
  1010. 'uid' => $owen,
  1011. 'tuid' => $otherkfid,
  1012. 'serverid' => $serverid,
  1013. 'guestuid' => $clientuid
  1014. ))->query();
  1015. }
  1016. /**
  1017. * 给客服分配会员【均分策略】
  1018. * @param $kfList
  1019. * @param $userList
  1020. * @param $group
  1021. * @param $total
  1022. */
  1023. private static function assignmentTask($kfList, $userList, $group, $total, $uid = 0)
  1024. {
  1025. }
  1026. /**
  1027. * 获取最大的服务人数
  1028. * @return int
  1029. */
  1030. private static function getMaxServiceNum()
  1031. {
  1032. $maxNumber = self::$db->query('select `max_service` from `ws_kf_config` where `id` = 1');
  1033. if (!empty($maxNumber)) {
  1034. $maxNumber = 5;
  1035. } else {
  1036. $maxNumber = $maxNumber['0']['max_service'];
  1037. }
  1038. return $maxNumber;
  1039. }
  1040. /**
  1041. * 将内存中的数据写入统计表
  1042. * @param int $flag
  1043. */
  1044. private static function writeLog($flag = 1)
  1045. {
  1046. // 上午 8点 到 22 点开始统计
  1047. if (date('H') < 8 || date('H') > 22) {
  1048. return;
  1049. }
  1050. $inQueue_1 = self::$redis->hgetall(self::USERLIST);
  1051. $inQueue = empty($inQueue_1) ? 0 : count($inQueue_1);
  1052. $allkf = self::$redis->hgetall(self::KFINFOKEY);
  1053. $nowTalking = $onlineKf = 0;
  1054. if (!empty($allkf)) {
  1055. foreach ($allkf as $kfuid => $val) {
  1056. $tmp = json_decode($val, true);
  1057. $onlineKf++;
  1058. $nowTalking += count($tmp['user_info']);
  1059. }
  1060. }
  1061. $key = date('Ymd') . 'total_in';
  1062. $key2 = date('Ymd') . 'success_in';
  1063. $param = [
  1064. 'is_talking' => $nowTalking,
  1065. 'in_queue' => $inQueue,
  1066. 'online_kf' => $onlineKf,
  1067. 'success_in' => self::$global->$key2,
  1068. 'total_in' => self::$global->$key,
  1069. 'now_date' => date('Y-m-d')
  1070. ];
  1071. self::$db->update('ws_now_data')->cols($param)->where('id=1')->query();
  1072. if (2 == $flag) {
  1073. $param = [
  1074. 'is_talking' => $nowTalking,
  1075. 'in_queue' => $inQueue,
  1076. 'online_kf' => $onlineKf,
  1077. 'success_in' => self::$global->$key2,
  1078. 'total_in' => self::$global->$key,
  1079. 'add_date' => date('Y-m-d'),
  1080. 'add_hour' => date('H'),
  1081. 'add_minute' => date('i'),
  1082. ];
  1083. self::$db->insert('ws_service_data')->cols($param)->query();
  1084. }
  1085. unset($allkf, $nowTalking, $inQueue, $onlineKf, $key, $key2, $param);
  1086. }
  1087. /**
  1088. * 机器人问答
  1089. * @param $client_id 服务ID
  1090. * @param $message 数据
  1091. */
  1092. private static function toRobot($client_id, $message)
  1093. {
  1094. $groups_id = $message['data']['groups_id'];
  1095. $robot_name = $message['data']['robot_name'];
  1096. $robotgroups_id = $message['data']['robotgroups_id'];
  1097. // 查询问题.
  1098. $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 . "'");
  1099. $chat_message = [
  1100. 'message_type' => 'robotMessage',
  1101. //'message_type' => 'chatMessage',
  1102. 'data' => [
  1103. 'name' => '智能助手',
  1104. 'time' => date('H:i'),
  1105. 'content' => $getRobot ? $getRobot[0]['robot_content'] : 'error',
  1106. ]
  1107. ];
  1108. Gateway::sendToClient($client_id, json_encode($chat_message, 256));
  1109. }
  1110. /**
  1111. * 评价
  1112. * @param $client_id 服务ID
  1113. * @param $message 数据
  1114. */
  1115. private static function evaluate($message)
  1116. {
  1117. // 获取当前会话工单.
  1118. $data = json_decode(self::$redis->HGET('SERVICELOG', $message['conversationId']), true);
  1119. if (empty($data)) {
  1120. return;
  1121. }
  1122. $data['evaluate_id'] = $message['evaluate_id'];
  1123. $data['evaluate_content'] = $message['evaluate_content'];
  1124. self::$redis->HSET('SERVICELOG', $data['client_id'], json_encode($data, 256));
  1125. $chat_message = [
  1126. 'message_type' => 'evaluate',
  1127. 'data' => [
  1128. 'status' => 1,
  1129. 'time' => date('H:i'),
  1130. ]
  1131. ];
  1132. Gateway::sendToClient($message['client_id'], json_encode($chat_message, 256));
  1133. }
  1134. //获取系统配置
  1135. private static function upsystemconfig()
  1136. {
  1137. $systemConfigData = self::$db->query("SELECT * FROM `ws_systemconfig`");
  1138. $arr = [];
  1139. if ($systemConfigData) {
  1140. foreach ($systemConfigData as $item) {
  1141. $arr[$item['systemconfig_enName']] = $item;
  1142. }
  1143. self::$global->systemconfig = $arr;
  1144. }
  1145. $group = self::$db->query("SELECT * FROM `ws_groups`");
  1146. $arr = [];
  1147. if ($group) {
  1148. foreach ($group as $val) {
  1149. $arr[$val['id']] = $val['name'];
  1150. }
  1151. self::$global->groupmap = $arr;
  1152. }
  1153. $arr = [];
  1154. $replay = self::$db->query('select * from `ws_reply`');
  1155. if ($replay) {
  1156. foreach ($replay as $val) {
  1157. $arr[$val['id']] = $val;
  1158. }
  1159. self::$global->replay = $arr;
  1160. }
  1161. }
  1162. /**
  1163. * 超时
  1164. * @param $client_id 服务ID
  1165. * @param $message 数据
  1166. */
  1167. private static function overTime()
  1168. {
  1169. // 查询对话时效设置.
  1170. $systemConfigData = self::$db->query("SELECT `systemconfig_data`,`systemconfig_enName`,`systemconfig_content` FROM `ws_systemconfig`");
  1171. foreach ($systemConfigData as $k => $v) {
  1172. if ($v['systemconfig_enName'] == 'overtime') {
  1173. $configOvertime = $v;
  1174. } elseif ($v['systemconfig_enName'] == 'unoperated') {
  1175. $configUnoperated = $v;
  1176. }
  1177. }
  1178. // 查询未断开的工单.
  1179. $serviceLog = self::$redis->hGetall('SERVICELOG');
  1180. $setOvertime = strtotime('-' . ($configOvertime['systemconfig_data'] - 60) . ' second');
  1181. $overtime = strtotime('-' . ($configOvertime['systemconfig_data']) . ' second');
  1182. $setUnoperated = strtotime('-' . ($configUnoperated['systemconfig_data'] - 60) . ' second');
  1183. $unoperated = strtotime('-' . ($configUnoperated['systemconfig_data']) . ' second');
  1184. foreach ($serviceLog as $k => $v) {
  1185. // 无效会话关闭.如果没有说一句话.
  1186. $data = json_decode($v, true);
  1187. if (!isset($data['userLastTime'])) {
  1188. if ($data['start_time'] <= $unoperated) {
  1189. self::serverClose($k, 1);
  1190. // 如果小于设定时间前一分钟则给出提示.
  1191. } elseif ($data['start_time'] <= $setUnoperated) {
  1192. $chat_message = [
  1193. 'message_type' => 'overtime',
  1194. 'data' => [
  1195. 'content' => $configUnoperated['systemconfig_content'],
  1196. ]
  1197. ];
  1198. Gateway::sendToClient($data['client_id'], json_encode($chat_message, 256));
  1199. }
  1200. // 双方静默超时.
  1201. } elseif ($data['userLastTime'] <= $overtime && $data['serverLastTime'] <= $overtime) {
  1202. self::serverClose($k, 2);
  1203. // 如果小于设定时间前一分钟则给出提示.
  1204. } elseif ($data['userLastTime'] <= $setOvertime && $data['serverLastTime'] <= $setOvertime) {
  1205. $chat_message = [
  1206. 'message_type' => 'overtime',
  1207. 'data' => [
  1208. 'content' => $configOvertime['systemconfig_content'],
  1209. ]
  1210. ];
  1211. Gateway::sendToClient($data['client_id'], json_encode($chat_message, 256));
  1212. }
  1213. }
  1214. }
  1215. /**
  1216. * 系统监控
  1217. * @param $message 数据
  1218. */
  1219. private static function systemMonitoring($adminList)
  1220. {
  1221. // 查询正进行的工单.
  1222. $serviceLog = self::$redis->hGetall('SERVICELOG');
  1223. // 查询系统设置表.
  1224. $systemconfig = self::$db->query("SELECT `systemconfig_data`,`systemconfig_enName` FROM `ws_systemconfig` WHERE `systemconfig_enName`='verifyReturnTime' or `systemconfig_enName`='verifyAllTime'");
  1225. // 质检会话响应时长.
  1226. $returnTimeKey = array_search('verifyReturnTime', array_column($systemconfig, 'systemconfig_enName'));
  1227. $verifyReturnTime = $systemconfig[$returnTimeKey]['systemconfig_data'];
  1228. // 质检会话时长.
  1229. $allTimeKey = array_search('verifyAllTime', array_column($systemconfig, 'systemconfig_enName'));
  1230. $verifyAllTime = $systemconfig[$allTimeKey]['systemconfig_data'];
  1231. $evaluateCount = 0; // 差评总次数.
  1232. $overtimeNumber = 0; // 会话超时总次数.
  1233. $overtimeTime = []; // 每次会话超时时间.
  1234. $userSensitive = 0; // 用户敏感词报警总次数.
  1235. $serverSensitive = 0; // 客服敏感词报警总次数.
  1236. $csdNumber = 0; // 响应超时总次数.
  1237. $csdTime = []; // 每次响应超时时间.
  1238. foreach ($serviceLog as $k => $v) {
  1239. $data = json_decode($v, true);
  1240. // 工单报警次数.
  1241. $allCount = 0;
  1242. if ($data['evaluate_id'] == 3) {
  1243. $evaluateCount++; // 差评次数.
  1244. $allCount++; // 工单报警次数.
  1245. }
  1246. // 会话超时.
  1247. $duration = time() - $data['start_time'];
  1248. if ($duration > $verifyAllTime) {
  1249. $overtimeNumber++; // 会话超时总次数.
  1250. $allCount++; // 工单报警次数.
  1251. $overtimeTime[] = $duration; // 响应超时时间.
  1252. }
  1253. // 敏感词报警.
  1254. $userSensitive += $data['alarm_userSensitive'];
  1255. $allCount += $data['alarm_userSensitive'];
  1256. $serverSensitive += $data['alarm_serverSensitive'];
  1257. $allCount += $data['alarm_serverSensitive'];
  1258. // 响应超时.
  1259. if ($data['alarm_corresponding'] > $verifyReturnTime) {
  1260. $csdTime[] = $data['alarm_corresponding']; // 响应超时时间.
  1261. $csdNumber++; // 响应超时总次数.
  1262. $allCount++; // 工单报警次数.
  1263. }
  1264. $serviceLog[$k] = $data;
  1265. $serviceLog[$k]['allCount'] = $allCount; // 工单报警次数.
  1266. }
  1267. self::DebugOut([$serviceLog, $csdTime, $verifyReturnTime], 'systemMonitoring');
  1268. $chat_message = [
  1269. 'message_type' => 'monitor',
  1270. 'data' => [
  1271. 'cvtList' => $serviceLog,
  1272. 'userSensitive' => $userSensitive,
  1273. 'serverSensitive' => $serverSensitive,
  1274. 'csdNumber' => $csdNumber,
  1275. 'csdTime' => $csdTime,
  1276. 'overtimeNumber' => $overtimeNumber,
  1277. 'overtimeTime' => $overtimeTime,
  1278. 'evaluateCount' => $evaluateCount,
  1279. ]
  1280. ];
  1281. // 查询对话时效设置.
  1282. foreach ($adminList as $v) {
  1283. Gateway::sendToClient($v, json_encode($chat_message, 256));
  1284. }
  1285. }
  1286. //客户工单内部组转接
  1287. public static function changeOtherhKeFu($client_id, $smessage)
  1288. {
  1289. $message = $smessage['data'];
  1290. $groupid = isset($message['fromgroup']) ? intval($message['fromgroup']) : 0;
  1291. $groupidto = isset($message['togroup']) ? intval($message['togroup']) : 0;
  1292. $toukfid = isset($message['toukfuid']) ? $message['toukfuid'] : 0;
  1293. $fromkfuid = isset($message['fromkfuid']) ? $message['fromkfuid'] : 0;
  1294. $uid = isset($message['uid']) ? intval($message['uid']) : 0;
  1295. $word = isset($message['word']) ? $message['word'] : '';
  1296. if (empty($groupid) || empty($groupidto) || empty($toukfid) || empty($fromkfuid) || empty($uid) || ($toukfid == $fromkfuid)) {
  1297. self::DebugOut('changeOtherhKeFu exit1...');
  1298. return false;
  1299. }
  1300. if (!Gateway::isUidOnline($toukfid) || !Gateway::isUidOnline($uid)) {
  1301. self::DebugOut('changeOtherhKeFu exit2...');
  1302. return false;
  1303. }
  1304. $kf_info_from = json_decode(self::$redis->hget(self::KFINFOKEY, $fromkfuid), true);
  1305. $kf_info_to = json_decode(self::$redis->hget(self::KFINFOKEY, $toukfid), true);
  1306. $user_info = json_decode(self::$redis->hget(self::USERINFOKEY, $uid), true);
  1307. $serviceid = intval($user_info['serverid']);
  1308. if (empty($kf_info_from) || empty($kf_info_to) || empty($user_info) || empty($serviceid)) {
  1309. self::DebugOut('changeOtherhKeFu exit23...');
  1310. return false;
  1311. }
  1312. if ($kf_info_to['status'] != 1) {
  1313. self::DebugOut('changeOtherhKeFu exit4...');
  1314. return false;
  1315. }
  1316. /////////取消原有会话,开启新会话
  1317. $oldlog = self::$db->select('*')->from('ws_service_log')->where('servicelog_id=:servicelog_id ')->bindValues(['servicelog_id' => $serviceid])->orderByDESC(['servicelog_id'])->row();
  1318. if (!$oldlog) {
  1319. self::DebugOut('changeOtherhKeFu exit5...');
  1320. return false;
  1321. }
  1322. self::insertServerLog($serviceid, 5);
  1323. self::$redis->hdel(self::SERVICELOG, $serviceid);
  1324. unset($oldlog['servicelog_id']);
  1325. ///更新redis数据
  1326. $kf_info_from['user_info'] = self::ArrayDataopt($kf_info_from['user_info'], $user_info['client_id'], 0);
  1327. $kf_info_from['task'] = count($kf_info_from['user_info']);
  1328. self::$redis->hset(self::KFINFOKEY, $fromkfuid, json_encode($kf_info_from, 256));
  1329. ///////旧工单部分数据更新回库
  1330. /// 查询工单会话总数.
  1331. self:: BeginTalk($toukfid, $uid, $groupidto, 0, $user_info);
  1332. self::servicetrutoother('OUT', $fromkfuid, $toukfid, $serviceid, $uid);
  1333. $newUserInfo = json_decode(self::$redis->hget(self::USERINFOKEY, $uid), true);
  1334. self::servicetrutoother('IN', $toukfid, $fromkfuid, $newUserInfo['serverid'], $uid);
  1335. //回转接人,转接成功
  1336. Gateway::sendToCurrentClient(json_encode(['message_type' => 'trunconnect', 'data' => ['status' => 1]], 256));
  1337. // 发送给用户转接消息
  1338. Gateway::sendToClient($user_info['client_id'], json_encode(['message_type' => 'changeKeFuSuccess', 'data' => ['content' => "会话转接成功"]], 256));
  1339. self::DebugOut('changekf 转换成功!');
  1340. return;
  1341. }
  1342. //客服在线状态写组
  1343. private static function writeLogKfStatus($kf, $status, $flag = 1)
  1344. {
  1345. if ($flag == 1) {
  1346. $status = intval($status);
  1347. if ($status == 0) {
  1348. self::$db->delete('ws_kfonline')->where("uid='$kf'")->query();
  1349. } else {
  1350. $now = date('Y-m-d H:i;s');
  1351. $ip = isset($_SESSION['remotip']) ? $_SESSION['remotip'] : '';
  1352. $sql = "insert into ws_kfonline(uid,status,uptime,ip) values('$kf',$status,'$now','$ip') ON DUPLICATE KEY UPDATE status=$status,uptime='$now' ";
  1353. self::$db->query($sql);
  1354. }
  1355. } else {
  1356. self::$db->query("delete from ws_kfonline ");
  1357. }
  1358. }
  1359. public static function resetServiceLog($kfid = 0)
  1360. {
  1361. $t = time() - 24 * 3600 * 7;
  1362. $now = time();
  1363. if ($kfid) {
  1364. if ((substr($kfid, 0, 2) == 'KF')) {
  1365. $kfid = intval(substr($kfid, 2));
  1366. }
  1367. $kfid = intval($kfid);
  1368. self::$db->query("update ws_service_log set status=2,end_time=$now where start_time>=$t and kf_id=$kfid and status!=2");
  1369. self::$redis->hdel(self::KFINFOKEY, 'KF' . $kfid);
  1370. } else {
  1371. self::$redis->del(self::KFINFOKEY);
  1372. self::$redis->del(self::USERLIST);
  1373. self::$redis->del(self::USERINFOKEY);
  1374. self::$redis->del('adminList');
  1375. self::$redis->del(self::WEBSOCKALLUSER);
  1376. self::$redis->del('SERVICELOG');
  1377. self::$db->query("update ws_service_log set status=2,end_time=$now where start_time>=$t and status!=2");
  1378. }
  1379. }
  1380. public static function onWorkerStop($businessWorker)
  1381. {
  1382. if ($businessWorker->id == 1) {
  1383. self::resetServiceLog();
  1384. }
  1385. }
  1386. //用户下线通知
  1387. private static function userCloseNotice($client_id, $cuid, $group)
  1388. {
  1389. }
  1390. //踢掉同一用户的旧用户
  1391. private static function tickOlduser($uid)
  1392. {
  1393. }
  1394. private static function DebugOut($msg, $title = '', $type = 'info')
  1395. {
  1396. $config = self::$global->systemconfig;
  1397. if (!isset($config['isdebug']) || empty($config['isdebug']['systemconfig_data'])) {
  1398. return;
  1399. }
  1400. if (!is_string($msg)) {
  1401. $msg = json_encode([$msg], 256);
  1402. }
  1403. $msg = date("Y-m-d H:i:s") . ' - ' . $type . ' - ' . $title . ' - ' . $msg . "\n";
  1404. echo $msg;
  1405. }
  1406. //定时器相关
  1407. private static function TimerThing($worker)
  1408. {
  1409. // 当天的累积接入值
  1410. $key = date('Ymd') . 'total_in';
  1411. if (is_null(self::$global->$key)) {
  1412. self::$global->$key = 0;
  1413. $oldKey = date('Ymd', strtotime('-1 day')); // 删除前一天的统计值
  1414. unset(self::$global->$oldKey);
  1415. unset($oldKey, $key);
  1416. }
  1417. // 成功接入值
  1418. $key = date('Ymd') . 'success_in';
  1419. if (is_null(self::$global->$key)) {
  1420. self::$global->$key = 0;
  1421. $oldKey = date('Ymd', strtotime('-1 day')); // 删除前一天的统计值
  1422. unset(self::$global->$oldKey);
  1423. unset($oldKey, $key);
  1424. }
  1425. // 定时统计数据
  1426. if (0 == $worker->id) {
  1427. self::writeLogKfStatus(0, 0, 0);
  1428. //每5秒更新进行一次人员分配
  1429. Timer::add(5, function () {
  1430. self::userOnlineTask();
  1431. });
  1432. //每1分钟报告一次本组排列人员(如果有人排队)
  1433. Timer::add(60, function () {
  1434. self::lineup();
  1435. });
  1436. // 1分钟统计一次实时数据
  1437. Timer::add(60 * 1, function () {
  1438. self::writeLog(1);
  1439. });
  1440. // 40分钟写一次当前日期点数的log数据
  1441. Timer::add(60 * 40, function () {
  1442. self::writeLog(2);
  1443. });
  1444. //初始化.....
  1445. self::upsystemconfig();
  1446. //每3分钟更新一次系统配置文件
  1447. Timer::add(60 * 3, function () {
  1448. self::upsystemconfig();
  1449. });
  1450. // 删除前一天的统计值
  1451. Timer::add(60 * 60 * 12, function () {
  1452. $oldKey = date('Ymd', strtotime('-1 day'));
  1453. unset(self::$global->$oldKey);
  1454. });
  1455. // 管理员实时监控.
  1456. Timer::add(20, function () {
  1457. // 获取在线管理员
  1458. $adminList = self::$redis->smembers('adminList');
  1459. if ($adminList) {
  1460. self::systemMonitoring($adminList);
  1461. }
  1462. });
  1463. // 检查对话时效给出.
  1464. Timer::add(40, function () {
  1465. self::overTime();
  1466. });
  1467. self::resetServiceLog();
  1468. }
  1469. }
  1470. //调试使用
  1471. public static function mydebug($client_id, $message)
  1472. {
  1473. }
  1474. public static function MySendMsg($clientId, $msg)
  1475. {
  1476. Gateway::sendToClient($clientId, $msg);
  1477. }
  1478. //得到客服的UID字符值
  1479. public static function getkfuid($uid)
  1480. {
  1481. if (substr($uid, 0, 2) == 'KF') {
  1482. return $uid;
  1483. } else {
  1484. return 'KF' . intval($uid);
  1485. }
  1486. }
  1487. //得到客服的ID整数值
  1488. public static function getkfid($id)
  1489. {
  1490. if (strtolower(substr($id, 0, 2)) == 'kf') {
  1491. return intval(substr($id, 2));
  1492. }
  1493. return intval($id);
  1494. }
  1495. //从数组中获取参数
  1496. public static function getPars($array, $key, $default = '')
  1497. {
  1498. if (isset($array[$key])) {
  1499. return $array[$key];
  1500. }
  1501. return $default;
  1502. }
  1503. //获取在线客服信息
  1504. public static function getOnlineKfData($group = 0, $status = 0)
  1505. {
  1506. $all = self::$redis->hgetall(self::KFINFOKEY);
  1507. if (!$all) {
  1508. return false;
  1509. }
  1510. $return = [];
  1511. foreach ($all as $val) {
  1512. $now = json_decode($val, true);
  1513. if ($group) {
  1514. if ($now['group'] != $group) {
  1515. continue;
  1516. }
  1517. }
  1518. if ($status) {
  1519. if ($now['status'] != $status) {
  1520. continue;
  1521. }
  1522. }
  1523. $return[$now['id']] = $now;
  1524. }
  1525. return $return;
  1526. }
  1527. //找到在排队的用户按时间先后顺序
  1528. public static function getUselistData($group)
  1529. {
  1530. $all = self::$redis->hgetall(self::USERLIST);
  1531. if (!$all) {
  1532. return false;
  1533. }
  1534. $return = [];
  1535. foreach ($all as $val) {
  1536. $now = json_decode($val, true);
  1537. if ($group == $now['group']) {
  1538. $return[] = $now;
  1539. }
  1540. }
  1541. usort($return, function ($a, $b) {
  1542. if ($a['intime'] == $b['intime']) {
  1543. return 0;
  1544. }
  1545. return $a['intime'] > $b['intime'] ? 1 : -1;
  1546. });
  1547. return $return;
  1548. }
  1549. //对客服的用户user_info数组进行加减操作 $clientid用户连接号 opt=1添加 0删除 $serverid服务工单号
  1550. public static function ArrayDataopt($array, $clientid, $opt, $serverid = 0)
  1551. {
  1552. if (!is_array($array)) {
  1553. return [];
  1554. }
  1555. if ($opt == 0) {
  1556. if (isset($array[$clientid])) {
  1557. unset($array[$clientid]);
  1558. }
  1559. return $array;
  1560. } else {
  1561. $array[$clientid] = $serverid;
  1562. return $array;
  1563. }
  1564. }
  1565. }