Events.php 54 KB

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