Events.php 72 KB

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