Events.php 58 KB

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