Events.php 82 KB

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