Events.php 48 KB

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