Events.php 79 KB

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