Events.php 63 KB

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