Events.php 82 KB

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