Events.php 74 KB

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