Events.php 53 KB

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