Events.php 74 KB

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