Events.php 78 KB

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