Events.php 74 KB

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