Events.php 79 KB

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