Events.php 71 KB

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