Events.php 82 KB

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