Events.php 54 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543
  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::$global->replay['1'];
  82. if (!empty($sayHello) && 1 == $sayHello['status']) {
  83. $hello = [
  84. 'message_type' => 'helloMessage',
  85. 'data' => [
  86. 'name' => '智能助手',
  87. 'time' => date('H:i'),
  88. 'content' => $sayHello['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. self::$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. self::$global->increment($key);
  444. // 绑定 client_id 和 uid
  445. Gateway::bindUid($client_id, $uid);
  446. $_SESSION['iskefu'] = 0;
  447. $_SESSION['uid'] = $message['uid'];
  448. // 尝试分配新会员进入服务
  449. self::userOnlineTask($group, $uid);
  450. }
  451. /**
  452. * 当用户断开连接时触发
  453. * @param int $client_id 连接id
  454. *
  455. * tips: 当服务端主动退出的时候,会出现 exit status 9.原因是:服务端主动断开之后,连接的客户端会走这个方法,而短时间内进程
  456. * 需要处理这多的逻辑,又有cas操作,导致进程退出会超时,然后会被内核杀死,从而报出错误 9.实际对真正的业务没有任何的影响。
  457. */
  458. public static function onClose($client_id)
  459. {
  460. $isKefuoff = isset($_SESSION['iskefu']) ? $_SESSION['iskefu'] : 0;
  461. $uid = isset($_SESSION['uid']) ? $_SESSION['uid'] : false;
  462. echo "下线:uid: $uid - cid: $client_id - iskf: $isKefuoff \n";
  463. $adminList = self::$global->adminList ?? [];
  464. $key = array_search($client_id, $adminList);
  465. if (strlen($key)) {
  466. array_splice($adminList, $key, 1);
  467. self::$global->adminList = $adminList;
  468. }
  469. if (empty($uid)) {
  470. return;
  471. }
  472. if ($isKefuoff) {
  473. self::serviceOffline($client_id, $uid);
  474. } else {
  475. self::guestOffline($client_id, $uid);
  476. }
  477. return;
  478. }
  479. //客服下线了 系统调用,不能手动调用
  480. public static function serviceOffline($client_id, $uid)
  481. {
  482. $group = $_SESSION['group'];
  483. $uinfo = self::$redis->hget(self::KFINFOKEY, $uid);
  484. $uinfo = json_decode($uinfo, true);
  485. $user_info = $uinfo['user_info'];
  486. $kfid = self::getkfid($uid);
  487. $now = time();
  488. $starttime = $now - 86400 * 7;
  489. self::$redis->hset('loginTmp:' . $uid, 'uid', time());
  490. self::$redis->expire('loginTmp:' . $uid, 5);
  491. if (!empty($user_info)) {
  492. foreach ($user_info as $val => $serverid) {
  493. self::$redis->hdel(self::SERVICELOG, intval($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 "客服退出: " . $uid . "\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. self::$redis->hdel(self::KFINFOKEY, $uid);
  504. return;
  505. }
  506. //用户下线了 系统调用,不能手动调用
  507. public static function guestOffline($client_id, $uid)
  508. {
  509. self::$redis->hset('loginTmp:' . $uid, 'uid', time());
  510. self::$redis->expire('loginTmp:' . $uid, 3);
  511. $uid = intval($uid);
  512. $krclient_id = 0;
  513. $data = self::$redis->hget(self::USERINFOKEY, $uid);
  514. if (empty($data)) {
  515. return;
  516. }
  517. $info = json_decode($data, true);
  518. self::$redis->hdel(self::USERLIST, $uid);
  519. self::$redis->hdel(self::USERINFOKEY, $uid);
  520. if (!empty($info['kfuid'])) {
  521. $kfinfo = self::$redis->hget(self::KFINFOKEY, $info['kfuid']);
  522. if (!empty($kfinfo)) {
  523. $kfinfoArr = json_decode($kfinfo, true);
  524. $krclient_id = $kfinfoArr['client_id'];
  525. $kfinfoArr['user_info'] = self::ArrayDataopt($kfinfoArr['user_info'], $client_id, 0);
  526. $kfinfoArr['task'] = count($kfinfoArr['user_info']);
  527. self::$redis->hset(self::KFINFOKEY, $info['kfuid'], json_encode($kfinfoArr, 256));
  528. }
  529. }
  530. $chat_message = [
  531. 'message_type' => 'userClose',
  532. 'data' => [
  533. 'content' => '用户连接已断开',
  534. 'id' => $uid,
  535. 'time' => date('H:i'),
  536. ]
  537. ];
  538. $now = time();
  539. $serverid = intval($info['serverid']);
  540. if ($serverid) {
  541. $sql = "update `ws_service_log` set `status` = '3' where servicelog_id=$serverid ";
  542. self::$db->query($sql);
  543. }
  544. if ($krclient_id) {
  545. Gateway::sendToClient($krclient_id, json_encode($chat_message, 256));
  546. }
  547. return;
  548. }
  549. /**
  550. * 客服结束会话
  551. *
  552. * tips: 未有$client_id的关闭
  553. */
  554. public static function closeUser($servicelog_id, $userId, $kf_id, $groupId)
  555. {
  556. }
  557. /**
  558. * 工单结束
  559. * @param int $client_id 连接id
  560. *
  561. * tips: 当服务端主动退出的时候,会出现 exit status 9.原因是:服务端主动断开之后,连接的客户端会走这个方法,而短时间内进程
  562. * 需要处理这多的逻辑,又有cas操作,导致进程退出会超时,然后会被内核杀死,从而报出错误 9.实际对真正的业务没有任何的影响。
  563. */
  564. public static function serverClose($servicelogId)
  565. {
  566. // 获取当前工单数据.
  567. $data = json_decode(self::$redis->HGET('SERVICELOG', $servicelogId), true);
  568. // 获取当前工单数据.
  569. $kfInfo = json_decode(self::$redis->HGET('KFINFO', 'KF' . $data['kf_id']), true);
  570. // 删除当前工单.
  571. //self::$redis->hdel('SERVICELOG', $servicelogId);
  572. // 当前服务客服删除当前人员.
  573. $kfUserList = self::ArrayDataopt($kfInfo['user_info'], $data['client_id'], 0);
  574. return;
  575. if (isset($kfInfo)) {
  576. print_r([$kfInfo, $servicelogId]);
  577. die;
  578. }
  579. // 当前客服所接待人员.
  580. $kfInfo['user_info'] = $kfUserList;
  581. $kfInfo['task'] = count($kfUserList);
  582. // 存入客服信息.
  583. $redis->HSET('KFINFO', 'KF' . $data['kf_id'], $kfInfo);
  584. // 将数据存入数据库.
  585. }
  586. /**
  587. * 有人退出
  588. * @param $group
  589. */
  590. private static function userOfflineTask($group)
  591. {
  592. }
  593. /**
  594. * 有人进入执行分配
  595. * @param $client_id
  596. * @param $group
  597. * @param $uid
  598. */
  599. private static function userOnlineTask($group = 0, $uid = 0)
  600. {
  601. $allusergkarr = self::getUserListData();
  602. if (empty($allusergkarr)) {
  603. return;
  604. }
  605. $allkfgkarr = self::getWorkKfData();
  606. if (empty($allkfgkarr)) {
  607. return;
  608. }
  609. $maxset = (self::$global->systemconfig)['KFMaxServices'] ?? 5;
  610. $maxset = intval($maxset);
  611. if ($group && $uid) {
  612. // 指定用指定组 [可能存在断线重连的情况] 如果存在旧的会话,直接连线客服和用户
  613. //否则按先到后到以及客服最大服务数限制
  614. $last = self::UserHasOldTalk($uid);
  615. if ($last) {
  616. self::BeginTalk(self::getkfuid($last['kf_id']), $uid, $last['group_id'], $last['servicelog_id']);
  617. return;
  618. }
  619. }
  620. //系统定时调用时,无组,无用户
  621. foreach ($allusergkarr as $group => $gusersArr) {
  622. if (!isset($allkfgkarr[$group]) || count($allkfgkarr[$group]) <= 0) {
  623. //所属客服组无人在线
  624. continue;
  625. }
  626. $nowkfs = $allkfgkarr[$group];
  627. $count = count($nowkfs);
  628. $i = 0;
  629. foreach ($gusersArr as $user) {
  630. if ($nowkfs[$i]['task'] > $maxset) {
  631. break;
  632. }
  633. $nowkfs[$i]['task']++;
  634. self::BeginTalk($nowkfs[$i]['id'], $user['id'], $group, 0, $user);
  635. self::$redis->hdel(self::USERLIST, $user['id']);
  636. $i++;
  637. if ($i >= $count) {
  638. $i = 0;
  639. }
  640. }
  641. }
  642. return;
  643. }
  644. //开启一个会话
  645. private static function BeginTalk($kfuid, $uid, $group, $serviceid = 0, $userInfo = false)
  646. {
  647. $serviceid = intval($serviceid);
  648. if (!$userInfo) {
  649. $userInfo = json_decode(self::$redis->hget(self::USERINFOKEY, $uid), true);
  650. }
  651. $kfinfo = json_decode(self::$redis->hget(self::KFINFOKEY, $kfuid), true);
  652. if (empty($userInfo) || empty($kfinfo)) {
  653. return false;
  654. }
  655. $server = [];
  656. $armarr = [];
  657. if ($serviceid) {
  658. $server = self::$db->select('*')->from('ws_service_log')->where("servicelog_id=$serviceid ")->row();
  659. if ($server) {
  660. $armarr = self::$db->select('*')->from('ws_alarm')->where("servicelog_id=$serviceid ")->row();
  661. }
  662. }
  663. if (empty($server)) {
  664. $array = [
  665. 'user_id' => $uid,
  666. 'client_id' => $userInfo['client_id'],
  667. 'user_name' => $userInfo['name'],
  668. 'user_avatar' => $userInfo['avatar'],
  669. 'user_ip' => $userInfo['ip'],
  670. 'kf_id' => self::getkfid($kfuid),
  671. 'start_time' => time(),
  672. 'group_id' => $userInfo['group'],
  673. 'website' => $userInfo['website'],
  674. 'system' => $userInfo['system'],
  675. 'browse' => $userInfo['browse'],
  676. 'intime' => $userInfo['intime'],
  677. 'status' => 1,
  678. 'evaluate_id' => 0,
  679. 'servicelog_close_type' => 0
  680. ];
  681. $serviceid = self::$db->insert('ws_service_log')->cols($array)->query();
  682. $server = array_merge(['servicelog_id' => $serviceid], $array);
  683. $armid = self::$db->insert('ws_alarm')->cols(['servicelog_id' => $serviceid])->query();
  684. $armarr = self::$db->select('*')->from('ws_alarm')->where("alarm_id=$armid")->row();
  685. }
  686. $redisData = array_merge($server, $armarr, ['kf_client_id' => $kfinfo['client_id']]);
  687. self::$redis->hset(self::SERVICELOG, $serviceid, json_encode($redisData, 256));
  688. $kfinfo['user_info'] = array_merge($kfinfo['user_info'], [$userInfo['client_id'] => $serviceid]);
  689. $kfinfo['task'] = count($kfinfo['user_info']);
  690. self::$redis->hset(self::KFINFOKEY, $kfuid, json_encode($kfinfo, 256));
  691. $userInfo['serverid'] = $serviceid;
  692. $userInfo['kfuid'] = $kfuid;
  693. self::$redis->hset(self::USERINFOKEY, $uid, json_encode($userInfo, 256));
  694. // 通知会员发送信息绑定客服的id
  695. $noticeUser = [
  696. 'message_type' => 'connect',
  697. 'data' => [
  698. 'kf_id' => $kfuid,
  699. 'conversationId' => $serviceid,
  700. 'serverInfo' => $kfinfo,
  701. 'kf_name' => $kfinfo['job_name']
  702. ]
  703. ];
  704. self::MySendMsg($userInfo['client_id'], json_encode($noticeUser, 256));
  705. $sayHello = (self::$global->replay)['2'];
  706. if (!empty($sayHello) && 1 == $sayHello['status']) {
  707. $chat_message = [
  708. 'message_type' => 'chatMessage',
  709. 'data' => [
  710. 'id' => self::getkfuid($kfinfo['id']),
  711. 'name' => $kfinfo['name'],
  712. 'time' => date('H:i'),
  713. 'content' => $sayHello['word']
  714. ]
  715. ];
  716. self::MySendMsg($userInfo['client_id'], json_encode($chat_message, 256));
  717. unset($chat_message);
  718. }
  719. $noticeKf = [
  720. 'message_type' => 'connect',
  721. 'data' => [
  722. 'user_info' => $userInfo,
  723. 'conversationId' => $serviceid,
  724. ]
  725. ];
  726. self::MySendMsg($kfinfo['client_id'], json_encode($noticeKf, 256));
  727. unset($noticeKf);
  728. $key = date('Ymd') . 'success_in';
  729. $oldKey = date('Ymd', strtotime('-1 day')); // 删除前一天的统计值
  730. unset(self::$global->$oldKey);
  731. self::$global->increment($key);
  732. return;
  733. }
  734. //用户排队数据 按组
  735. private static function getUserListData()
  736. {
  737. $alluser = self::$redis->hgetall(self::USERLIST);
  738. if (empty($alluser)) {
  739. return false;
  740. }
  741. $allusergkarr = [];
  742. foreach ($alluser as $val) {
  743. $now = json_decode($val, true);
  744. if ($now) {
  745. //用户分组后的数组
  746. $allusergkarr[$now['group']][] = $now;
  747. }
  748. }
  749. foreach ($allusergkarr as $group => $nowgroups) {
  750. usort($allusergkarr[$group], function ($a, $b) {
  751. if ($a['intime'] == $b['intime']) {
  752. return 0;
  753. }
  754. return ($a['intime'] > $b['intime']) ? 1 : -1;
  755. });
  756. }
  757. if (!$allusergkarr) {
  758. return false;
  759. }
  760. unset($alluser);
  761. return $allusergkarr;
  762. }
  763. //找到可以接工单的客服 按组
  764. private static function getWorkKfData()
  765. {
  766. $allkfs = self::$redis->hgetall(self::KFINFOKEY);
  767. if (empty($allkfs)) {
  768. return false;
  769. }
  770. $allkfgkarr = [];
  771. foreach ($allkfs as $val) {
  772. $now = json_decode($val, true);
  773. if ($now && $now['status'] == 1) {
  774. //客分组后的数组
  775. $allkfgkarr[$now['group']][] = $now;
  776. }
  777. }
  778. if (!$allkfgkarr) {
  779. return false;
  780. }
  781. //客服每组按任务数由小到大排序 任务相同时按时间先后顺序
  782. foreach ($allkfgkarr as $group => $nowgroups) {
  783. usort($allkfgkarr[$group], function ($a, $b) {
  784. if ($a['task'] == $b['task']) {
  785. if ($a['intime'] == $b['intime']) {
  786. return 0;
  787. }
  788. return ($a['intime'] > $b['intime']) ? 1 : -1;
  789. }
  790. return ($a['task'] > $b['task']) ? 1 : -1;
  791. });
  792. }
  793. unset($allkfs);
  794. return $allkfgkarr;
  795. }
  796. //找到用户是否有一条未关闭的会话
  797. private static function UserHasOldTalk($uid)
  798. {
  799. $uid = intval($uid);
  800. $start_time = time() - 86400;
  801. $ret = self::$db->select('*')->from('ws_service_log')->where("start_time>=$start_time and user_id=$uid and status!=2 ")->orderByDESC(['servicelog_id'])->row();
  802. return $ret;
  803. }
  804. //今天排序累加
  805. private static function todayqueuelength()
  806. {
  807. $dtype = 'user.queue.day.length';
  808. $today = date("Y-m-d");
  809. $sret = self::$db->select('*')->from('ws_countmidtable')->where('dtype=:dtype and mdate=:mdate')->bindValues(array('dtype' => $dtype, 'mdate' => $today))->row();
  810. if ($sret) {
  811. self::$db->update('ws_countmidtable')->cols(array('dcontent' => intval($sret['dcontent']) + 1))->where('id=' . $sret['id'])->query();
  812. } else {
  813. self::$db->insert('ws_countmidtable')->cols(array(
  814. 'dtype' => $dtype,
  815. 'mdate' => $today,
  816. 'datatype' => 1,
  817. 'dcontent' => 1))->query();
  818. }
  819. }
  820. //客服工单转单
  821. private static function servicetrutoother($type, $owen, $otherkfid, $serverid, $clientuid)
  822. {
  823. $owen = intval(substr($owen, 2));
  824. $otherkfid = intval(substr($otherkfid, 2));
  825. self::$db->insert('ws_serviceturn_log')->cols(array(
  826. 'stype' => $type,
  827. 'uid' => $owen,
  828. 'tuid' => $otherkfid,
  829. 'serverid' => $serverid,
  830. 'guestuid' => $clientuid
  831. ))->query();
  832. }
  833. /**
  834. * 给客服分配会员【均分策略】
  835. * @param $kfList
  836. * @param $userList
  837. * @param $group
  838. * @param $total
  839. */
  840. private static function assignmentTask($kfList, $userList, $group, $total, $uid = 0)
  841. {
  842. }
  843. /**
  844. * 获取最大的服务人数
  845. * @return int
  846. */
  847. private static function getMaxServiceNum()
  848. {
  849. $maxNumber = self::$db->query('select `max_service` from `ws_kf_config` where `id` = 1');
  850. if (!empty($maxNumber)) {
  851. $maxNumber = 5;
  852. } else {
  853. $maxNumber = $maxNumber['0']['max_service'];
  854. }
  855. return $maxNumber;
  856. }
  857. /**
  858. * 将内存中的数据写入统计表
  859. * @param int $flag
  860. */
  861. private static function writeLog($flag = 1)
  862. {
  863. }
  864. /**
  865. * 机器人问答
  866. * @param $client_id 服务ID
  867. * @param $message 数据
  868. */
  869. private static function toRobot($client_id, $message)
  870. {
  871. $groups_id = $message['data']['groups_id'];
  872. $robot_name = $message['data']['robot_name'];
  873. $robotgroups_id = $message['data']['robotgroups_id'];
  874. // 查询问题.
  875. $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 . "'");
  876. $chat_message = [
  877. 'message_type' => 'robotMessage',
  878. //'message_type' => 'chatMessage',
  879. 'data' => [
  880. 'name' => '智能助手',
  881. 'time' => date('H:i'),
  882. 'content' => $getRobot ? $getRobot[0]['robot_content'] : 'error',
  883. ]
  884. ];
  885. Gateway::sendToClient($client_id, json_encode($chat_message, 256));
  886. }
  887. /**
  888. * 评价
  889. * @param $client_id 服务ID
  890. * @param $message 数据
  891. */
  892. private static function evaluate($client_id, $message)
  893. {
  894. // 修改数据库.
  895. $evaluate_id = $message['data']['evaluate_id'];
  896. $result = self::$db->query("UPDATE `ws_service_log` SET `evaluate_id` = '" . $evaluate_id . "' WHERE `client_id`='" . $client_id . "'");
  897. if ($result) {
  898. $chat_message = [
  899. 'message_type' => 'evaluate',
  900. 'data' => [
  901. 'status' => 1,
  902. 'time' => date('H:i'),
  903. ]
  904. ];
  905. } else {
  906. $chat_message = [
  907. 'message_type' => 'evaluate',
  908. 'data' => [
  909. 'status' => 2,
  910. 'time' => date('H:i'),
  911. ]
  912. ];
  913. }
  914. Gateway::sendToClient($client_id, json_encode($chat_message, 256));
  915. }
  916. //获取系统配置
  917. private static function upsystemconfig()
  918. {
  919. $systemConfigData = self::$db->query("SELECT * FROM `ws_systemconfig`");
  920. $arr = [];
  921. if ($systemConfigData) {
  922. foreach ($systemConfigData as $item) {
  923. $arr[$item['systemconfig_enName']] = $item;
  924. }
  925. self::$global->systemconfig = $arr;
  926. }
  927. $group = self::$db->query("SELECT * FROM `ws_groups`");
  928. $arr = [];
  929. if ($group) {
  930. foreach ($group as $val) {
  931. $arr[$val['id']] = $val['name'];
  932. }
  933. self::$global->groupmap = $arr;
  934. }
  935. $arr = [];
  936. $replay = self::$db->query('select * from `ws_reply`');
  937. if ($replay) {
  938. foreach ($replay as $val) {
  939. $arr[$val['id']] = $val;
  940. }
  941. self::$global->replay = $arr;
  942. }
  943. }
  944. /**
  945. * 超时
  946. * @param $client_id 服务ID
  947. * @param $message 数据
  948. */
  949. private static function overTime()
  950. {
  951. // 查询对话时效设置.
  952. $systemConfigData = self::$db->query("SELECT `systemconfig_data`,`systemconfig_enName`,`systemconfig_content` FROM `ws_systemconfig`");
  953. foreach ($systemConfigData as $k => $v) {
  954. if ($v['systemconfig_enName'] == 'overtime') {
  955. $configOvertime = $v;
  956. } elseif ($v['systemconfig_enName'] == 'unoperated') {
  957. $configUnoperated = $v;
  958. }
  959. }
  960. // 查询未断开的工单.
  961. $serviceLog = self::$redis->hGetall('SERVICELOG');
  962. $setOvertime = strtotime('-' . ($configOvertime['systemconfig_data'] - 60) . ' second');
  963. $overtime = strtotime('-' . ($configOvertime['systemconfig_data']) . ' second');
  964. $setUnoperated = strtotime('-' . ($configUnoperated['systemconfig_data'] - 60) . ' second');
  965. $unoperated = strtotime('-' . ($configUnoperated['systemconfig_data']) . ' second');
  966. foreach ($serviceLog as $k => $v) {
  967. // 无效会话关闭.如果没有说一句话.
  968. $data = json_decode($v, true);
  969. if (!isset($data['userLastTime'])) {
  970. if ($data['start_time'] <= $unoperated) {
  971. self::serverClose($k);
  972. // 如果小于设定时间前一分钟则给出提示.
  973. } elseif ($data['start_time'] <= $setUnoperated) {
  974. $chat_message = [
  975. 'message_type' => 'overtime',
  976. 'data' => [
  977. 'content' => self::$global->unoperated['systemconfig_content'],
  978. ]
  979. ];
  980. Gateway::sendToClient($data['client_id'], json_encode($chat_message, 256));
  981. }
  982. // 双方静默超时.
  983. } elseif ($data['userLastTime'] <= $overtime && $data['serverLastTime'] <= $overtime) {
  984. self::serverClose($k);
  985. // 如果小于设定时间前一分钟则给出提示.
  986. } elseif ($data['userLastTime'] <= $setOvertime && $data['serverLastTime'] <= $setOvertime) {
  987. $chat_message = [
  988. 'message_type' => 'overtime',
  989. 'data' => [
  990. 'content' => self::$global->overtime['systemconfig_content'],
  991. ]
  992. ];
  993. Gateway::sendToClient($data['client_id'], json_encode($chat_message, 256));
  994. }
  995. }
  996. }
  997. /**
  998. * 系统监控
  999. * @param $message 数据
  1000. */
  1001. private static function systemMonitoring($adminList)
  1002. {
  1003. // 查询正进行的工单.
  1004. $serviceLog = self::$redis->hGetall('SERVICELOG');
  1005. // 查询系统设置表.
  1006. $systemconfig = self::$db->query("SELECT `systemconfig_data`,`systemconfig_enName` FROM `ws_systemconfig` WHERE `systemconfig_enName`='verifyReturnTime' or `systemconfig_enName`='verifyAllTime'");
  1007. // 质检会话响应时长.
  1008. $returnTimeKey = array_search('verifyReturnTime', array_column($systemconfig, 'systemconfig_enName'));
  1009. $verifyReturnTime = $systemconfig[$returnTimeKey]['systemconfig_data'];
  1010. // 质检会话时长.
  1011. $allTimeKey = array_search('verifyAllTime', array_column($systemconfig, 'systemconfig_enName'));
  1012. $verifyAllTime = $systemconfig[$allTimeKey]['systemconfig_data'];
  1013. $evaluateCount = 0; // 差评总次数.
  1014. $overtimeNumber = 0; // 会话超时总次数.
  1015. $overtimeTime = []; // 每次会话超时时间.
  1016. $userSensitive = 0; // 用户敏感词报警总次数.
  1017. $serverSensitive = 0; // 客服敏感词报警总次数.
  1018. $csdNumber = 0; // 响应超时总次数.
  1019. $csdTime = []; // 每次响应超时时间.
  1020. foreach ($serviceLog as $k => $v) {
  1021. $data = json_decode($v, true);
  1022. // 工单报警次数.
  1023. $allCount = 0;
  1024. if ($data['evaluate_id'] == 3) {
  1025. $evaluateCount++; // 差评次数.
  1026. $allCount++; // 工单报警次数.
  1027. }
  1028. // 会话超时.
  1029. $duration = time() - $data['start_time'];
  1030. if ($duration > $verifyAllTime) {
  1031. $overtimeNumber++; // 会话超时总次数.
  1032. $allCount++; // 工单报警次数.
  1033. $overtimeTime[] = $duration; // 响应超时时间.
  1034. }
  1035. // 敏感词报警.
  1036. $userSensitive += $data['alarm_userSensitive'];
  1037. $allCount += $data['alarm_userSensitive'];
  1038. $serverSensitive += $data['alarm_serverSensitive'];
  1039. $allCount += $data['alarm_serverSensitive'];
  1040. // 响应超时.
  1041. if ($data['alarm_corresponding'] > $verifyReturnTime) {
  1042. $csdTime[] = $data['alarm_corresponding']; // 响应超时时间.
  1043. $csdNumber++; // 响应超时总次数.
  1044. $allCount++; // 工单报警次数.
  1045. }
  1046. $serviceLog[$k] = $data;
  1047. $serviceLog[$k]['allCount'] = $allCount; // 工单报警次数.
  1048. }
  1049. self::DebugOut([$serviceLog, $csdTime, $verifyReturnTime], 'systemMonitoring');
  1050. // 查询对话时效设置.
  1051. foreach ($adminList as $v) {
  1052. $chat_message = [
  1053. 'message_type' => 'monitor',
  1054. 'data' => [
  1055. 'cvtList' => $serviceLog,
  1056. 'userSensitive' => $userSensitive,
  1057. 'serverSensitive' => $serverSensitive,
  1058. 'csdNumber' => $csdNumber,
  1059. 'csdTime' => $csdTime,
  1060. 'overtimeNumber' => $overtimeNumber,
  1061. 'overtimeTime' => $overtimeTime,
  1062. 'evaluateCount' => $evaluateCount,
  1063. ]
  1064. ];
  1065. Gateway::sendToClient($v, json_encode($chat_message, 256));
  1066. }
  1067. }
  1068. //客户工单内部组转接
  1069. public static function changeOtherhKeFu($client_id, $smessage)
  1070. {
  1071. $message = $smessage['data'];
  1072. $groupid = isset($message['fromgroup']) ? intval($message['fromgroup']) : 0;
  1073. $groupidto = isset($message['togroup']) ? intval($message['togroup']) : 0;
  1074. $toukfid = isset($message['toukfuid']) ? $message['toukfuid'] : 0;
  1075. $fromkfuid = isset($message['fromkfuid']) ? $message['fromkfuid'] : 0;
  1076. $uid = isset($message['uid']) ? intval($message['uid']) : 0;
  1077. $word = isset($message['word']) ? $message['word'] : '';
  1078. if (empty($groupid) || empty($groupidto) || empty($toukfid) || empty($fromkfuid) || empty($uid) || ($toukfid == $fromkfuid)) {
  1079. self::DebugOut('changeOtherhKeFu exit1...');
  1080. return false;
  1081. }
  1082. if (!Gateway::isUidOnline($toukfid) || !Gateway::isUidOnline($uid)) {
  1083. self::DebugOut('changeOtherhKeFu exit2...');
  1084. return false;
  1085. }
  1086. $kf_info_from = json_decode(self::$redis->hget(self::KFINFOKEY, $fromkfuid), true);
  1087. $kf_info_to = json_decode(self::$redis->hget(self::KFINFOKEY, $toukfid), true);
  1088. $user_info = json_decode(self::$redis->hget(self::USERINFOKEY, $uid), true);
  1089. $serviceid = intval($user_info['serverid']);
  1090. if (empty($kf_info_from) || empty($kf_info_to) || empty($user_info) || empty($serviceid)) {
  1091. self::DebugOut('changeOtherhKeFu exit23...');
  1092. return false;
  1093. }
  1094. if ($kf_info_to['status'] != 1) {
  1095. self::DebugOut('changeOtherhKeFu exit4...');
  1096. return false;
  1097. }
  1098. /////////取消原有会话,开启新会话
  1099. $oldlog = self::$db->select('*')->from('ws_service_log')->where('servicelog_id=:servicelog_id ')->bindValues(['servicelog_id' => $serviceid])->orderByDESC(['servicelog_id'])->row();
  1100. if (!$oldlog) {
  1101. self::DebugOut('changeOtherhKeFu exit5...');
  1102. return false;
  1103. }
  1104. self::$db->update('ws_service_log')->cols(['servicelog_close_type' => 5, 'status' => 2, 'end_time' => time()])->where("servicelog_id=$serviceid")->query();
  1105. self::$redis->hdel(self::SERVICELOG, $serviceid);
  1106. unset($oldlog['servicelog_id']);
  1107. $oldlog = array_merge($oldlog, ['kf_id' => self::getkfid($toukfid), 'start_time' => time(), 'end_time' => 0, 'status' => 1, 'evaluate_id' => 0]);
  1108. $new_id = self::$db->insert('ws_service_log')->cols($oldlog)->query();
  1109. if (!$new_id) {
  1110. self::DebugOut('changeOtherhKeFu exit6...');
  1111. return false;
  1112. }
  1113. ///更新redis数据
  1114. $kf_info_from['user_info'] = self::ArrayDataopt($kf_info_from['user_info'], $user_info['client_id'], 0);
  1115. $kf_info_from['task'] = count($kf_info_from['user_info']);
  1116. self::$redis->hset(self::KFINFOKEY, $fromkfuid, json_encode($kf_info_from, 256));
  1117. $kf_info_to['user_info'] = self::ArrayDataopt($kf_info_to['user_info'], $user_info['client_id'], 1, $new_id);
  1118. $kf_info_to['task'] = count($kf_info_to['user_info']);
  1119. self::$redis->hset(self::KFINFOKEY, $toukfid, json_encode($kf_info_to, 256));
  1120. $user_info['kfuid'] = $toukfid;
  1121. $user_info['serverid'] = $new_id;
  1122. self::$redis->hset(self::USERINFOKEY, $uid, json_encode($user_info, 256));
  1123. unset($kf_info_to['user_info']);
  1124. ///通知消息发送--------------
  1125. // 通知会员发送信息绑定客服的id
  1126. $noticeUser = [
  1127. 'message_type' => 'connect',
  1128. 'data' => [
  1129. 'kf_id' => $toukfid,
  1130. 'conversationId' => $new_id,
  1131. 'kf_name' => $kf_info_to['name'],
  1132. 'serverInfo' => $kf_info_to,
  1133. ]
  1134. ];
  1135. Gateway::sendToClient($user_info['client_id'], json_encode($noticeUser, 256));
  1136. unset($noticeUser);
  1137. // 通知客服端绑定会员的信息
  1138. $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']];
  1139. $noticeKf = [
  1140. 'message_type' => 'connect',
  1141. 'data' => [
  1142. 'user_info' => $userinfoarr,
  1143. 'conversationId' => $new_id,
  1144. ]
  1145. ];
  1146. Gateway::sendToClient($kf_info_to['client_id'], json_encode($noticeKf, 256));
  1147. unset($noticeKf);
  1148. self::servicetrutoother('OUT', $fromkfuid, $toukfid, $serviceid, $uid);
  1149. self::servicetrutoother('IN', $toukfid, $fromkfuid, $new_id, $uid);
  1150. //回转接人,转接成功
  1151. Gateway::sendToCurrentClient(json_encode(['message_type' => 'trunconnect', 'data' => ['status' => 1]], 256));
  1152. self::DebugOut('changekf 转换成功!');
  1153. return;
  1154. }
  1155. //客服在线状态写组
  1156. private static function writeLogKfStatus($kf, $status, $flag = 1)
  1157. {
  1158. if ($flag == 1) {
  1159. $status = intval($status);
  1160. if ($status == 0) {
  1161. self::$db->delete('ws_kfonline')->where("uid='$kf'")->query();
  1162. } else {
  1163. $now = date('Y-m-d H:i;s');
  1164. $ip = isset($_SESSION['remotip']) ? $_SESSION['remotip'] : '';
  1165. $sql = "insert into ws_kfonline(uid,status,uptime,ip) values('$kf',$status,'$now','$ip') ON DUPLICATE KEY UPDATE status=$status,uptime='$now' ";
  1166. self::$db->query($sql);
  1167. }
  1168. } else {
  1169. self::$db->query("delete from ws_kfonline ");
  1170. }
  1171. }
  1172. public static function resetServiceLog($kfid = 0)
  1173. {
  1174. $t = time() - 24 * 3600 * 7;
  1175. $now = time();
  1176. if ($kfid) {
  1177. if ((substr($kfid, 0, 2) == 'KF')) {
  1178. $kfid = intval(substr($kfid, 2));
  1179. }
  1180. $kfid = intval($kfid);
  1181. self::$db->query("update ws_service_log set status=2,end_time=$now where start_time>=$t and kf_id=$kfid and status!=2");
  1182. self::$redis->hdel(self::KFINFOKEY, 'KF' . $kfid);
  1183. } else {
  1184. self::$redis->del(self::KFINFOKEY);
  1185. self::$redis->del(self::USERLIST);
  1186. self::$redis->del(self::USERINFOKEY);
  1187. self::$db->query("update ws_service_log set status=2,end_time=$now where start_time>=$t and status!=2");
  1188. }
  1189. }
  1190. public static function onWorkerStop($businessWorker)
  1191. {
  1192. if ($businessWorker->worker_id == 1) {
  1193. self::resetServiceLog();
  1194. }
  1195. }
  1196. //用户下线通知
  1197. private static function userCloseNotice($client_id, $cuid, $group)
  1198. {
  1199. }
  1200. //踢掉同一用户的旧用户
  1201. private static function tickOlduser($uid)
  1202. {
  1203. }
  1204. private static function DebugOut($msg, $title = '', $type = 'info')
  1205. {
  1206. $config = self::$global->systemconfig;
  1207. if (!isset($config['isdebug']) || empty($config['isdebug']['systemconfig_data'])) {
  1208. return;
  1209. }
  1210. if (!is_string($msg)) {
  1211. $msg = json_encode([$msg], 256);
  1212. }
  1213. $msg = date("Y-m-d H:i:s") . ' - ' . $type . ' - ' . $title . ' - ' . $msg . "\n";
  1214. echo $msg;
  1215. }
  1216. //定时器相关
  1217. private static function TimerThing($worker)
  1218. {
  1219. // 当天的累积接入值
  1220. $key = date('Ymd') . 'total_in';
  1221. if (is_null(self::$global->$key)) {
  1222. self::$global->$key = 0;
  1223. $oldKey = date('Ymd', strtotime('-1 day')); // 删除前一天的统计值
  1224. unset(self::$global->$oldKey);
  1225. unset($oldKey, $key);
  1226. }
  1227. // 成功接入值
  1228. $key = date('Ymd') . 'success_in';
  1229. if (is_null(self::$global->$key)) {
  1230. self::$global->$key = 0;
  1231. $oldKey = date('Ymd', strtotime('-1 day')); // 删除前一天的统计值
  1232. unset(self::$global->$oldKey);
  1233. unset($oldKey, $key);
  1234. }
  1235. // 定时统计数据
  1236. if (0 == $worker->id) {
  1237. self::writeLogKfStatus(0, 0, 0);
  1238. //每5分钟更新一次系统配置文件
  1239. Timer::add(5, function () {
  1240. self::userOnlineTask();
  1241. });
  1242. //初始化.....
  1243. self::upsystemconfig();
  1244. //每3分钟更新一次系统配置文件
  1245. Timer::add(60 * 3, function () {
  1246. self::upsystemconfig();
  1247. });
  1248. // 删除前一天的统计值
  1249. Timer::add(60 * 60 * 12, function () {
  1250. $oldKey = date('Ymd', strtotime('-1 day'));
  1251. unset(self::$global->$oldKey);
  1252. });
  1253. self::resetServiceLog();
  1254. }
  1255. }
  1256. //调试使用
  1257. public static function mydebug($client_id, $message)
  1258. {
  1259. }
  1260. public static function MySendMsg($clientId, $msg)
  1261. {
  1262. Gateway::sendToClient($clientId, $msg);
  1263. }
  1264. //得到客服的UID字符值
  1265. public static function getkfuid($uid)
  1266. {
  1267. if (substr($uid, 0, 2) == 'KF') {
  1268. return $uid;
  1269. } else {
  1270. return 'KF' . intval($uid);
  1271. }
  1272. }
  1273. //得到客服的ID整数值
  1274. public static function getkfid($id)
  1275. {
  1276. if (strtolower(substr($id, 0, 2)) == 'kf') {
  1277. return intval(substr($id, 2));
  1278. }
  1279. return intval($id);
  1280. }
  1281. //从数组中获取参数
  1282. public static function getPars($array, $key, $default = '')
  1283. {
  1284. if (isset($array[$key])) {
  1285. return $array[$key];
  1286. }
  1287. return $default;
  1288. }
  1289. //获取在线客服信息
  1290. public static function getOnlineKfData($group = 0, $status = 0)
  1291. {
  1292. $all = self::$redis->hgetall(self::KFINFOKEY);
  1293. if (!$all) {
  1294. return false;
  1295. }
  1296. $return = [];
  1297. foreach ($all as $val) {
  1298. $now = json_decode($val, true);
  1299. if ($group) {
  1300. if ($now['group'] != $group) {
  1301. continue;
  1302. }
  1303. }
  1304. if ($status) {
  1305. if ($now['status'] != $status) {
  1306. continue;
  1307. }
  1308. }
  1309. $return[$now['id']] = $now;
  1310. }
  1311. return $return;
  1312. }
  1313. //找到在排队的用户按时间先后顺序
  1314. public static function getUselistData($group)
  1315. {
  1316. $all = self::$redis->hgetall(self::USERLIST);
  1317. if (!$all) {
  1318. return false;
  1319. }
  1320. $return = [];
  1321. foreach ($all as $val) {
  1322. $now = json_decode($val, true);
  1323. if ($group == $now['group']) {
  1324. $return[] = $now;
  1325. }
  1326. }
  1327. usort($return, function ($a, $b) {
  1328. if ($a['intime'] == $b['intime']) {
  1329. return 0;
  1330. }
  1331. return $a['intime'] > $b['intime'] ? 1 : -1;
  1332. });
  1333. return $return;
  1334. }
  1335. //对客服的用户user_info数组进行加减操作 $clientid用户连接号 opt=1添加 0删除 $serverid服务工单号
  1336. public static function ArrayDataopt($array, $clientid, $opt, $serverid = 0)
  1337. {
  1338. if (!is_array($array)) {
  1339. return [];
  1340. }
  1341. if ($opt == 0) {
  1342. if (isset($array[$clientid])) {
  1343. unset($array[$clientid]);
  1344. }
  1345. return $array;
  1346. } else {
  1347. $array[$clientid] = $serverid;
  1348. return $array;
  1349. }
  1350. }
  1351. }