Events.php 59 KB

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