Events.php 82 KB

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