Events.php 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327
  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.186', '3306', 'root', '', 'customer_service');
  41. }
  42. if (empty(self::$global)) {
  43. self::$global = new \GlobalData\Client('127.0.0.1:2207');
  44. // 客服列表
  45. if (is_null(self::$global->kfList)) {
  46. self::$global->kfList = [];
  47. }
  48. // 会员列表[动态的,这里面只是目前未被分配的会员信息]
  49. if (is_null(self::$global->userList)) {
  50. self::$global->userList = [];
  51. }
  52. // 会员以 uid 为key的信息简表,只有在用户退出的时候,才去执行修改
  53. if (is_null(self::$global->uidSimpleList)) {
  54. self::$global->uidSimpleList = [];
  55. }
  56. // 当天的累积接入值
  57. $key = date('Ymd') . 'total_in';
  58. if (is_null(self::$global->$key)) {
  59. self::$global->$key = 0;
  60. $oldKey = date('Ymd', strtotime('-1 day')); // 删除前一天的统计值
  61. unset(self::$global->$oldKey);
  62. unset($oldKey, $key);
  63. }
  64. // 成功接入值
  65. $key = date('Ymd') . 'success_in';
  66. if (is_null(self::$global->$key)) {
  67. self::$global->$key = 0;
  68. $oldKey = date('Ymd', strtotime('-1 day')); // 删除前一天的统计值
  69. unset(self::$global->$oldKey);
  70. unset($oldKey, $key);
  71. }
  72. }
  73. // 定时统计数据
  74. if (0 === $worker->id) {
  75. // 1分钟统计一次实时数据
  76. Timer::add(60 * 1, function () {
  77. self::writeLog(1);
  78. });
  79. // 40分钟写一次当前日期点数的log数据
  80. Timer::add(60 * 40, function () {
  81. self::writeLog(2);
  82. });
  83. }
  84. // 检查对话时效给出.
  85. Timer::add(3, function () {
  86. // 查询对话时效设置.
  87. $systemConfigData = self::$db->query("SELECT `systemconfig_data`,`systemconfig_enName`,`systemconfig_content` FROM `ws_systemconfig`");
  88. foreach ($systemConfigData as $k => $v) {
  89. if ($v['systemconfig_enName'] == 'overtime') {
  90. self::$global->overtime = $v;
  91. } elseif ($v['systemconfig_enName'] == 'unoperated') {
  92. self::$global->unoperated = $v;
  93. } elseif ($v['systemconfig_enName'] == 'noResponse') {
  94. self::$global->noResponse = $v;
  95. }
  96. }
  97. // 查询未断开的工单.
  98. $serviceLog = self::$db->query("SELECT `servicelog_id`,`client_id`,`start_time` FROM `ws_service_log` WHERE `status`='1' OR `status`='3'");
  99. $whereOr = '1=0';
  100. foreach ($serviceLog as $k => $v) {
  101. if ($k == 0) {
  102. $whereOr = "`servicelog_id`=".$v['servicelog_id'];
  103. } else {
  104. $whereOr .= " OR `servicelog_id`=".$v['servicelog_id'];
  105. }
  106. }
  107. // 查询最后一次会话.
  108. //$chatLog = self::$db->query("SELECT `servicelog_id`,MAX(`time_line`) FROM `ws_chat_log` WHERE ".$whereOr." group by `servicelog_id`");
  109. $chatLog = self::$db->query("
  110. select * from ws_chat_log as a where time_line=(
  111. select max(b.time_line) from ws_chat_log as b where a.servicelog_id = b.servicelog_id and (".$whereOr.") group by servicelog_id
  112. )
  113. ");
  114. $setOvertime = strtotime('-'.(self::$global->overtime['systemconfig_data']-60).' second');
  115. $overtime = strtotime('-'.(self::$global->overtime['systemconfig_data']).' second');
  116. $setUnoperated = strtotime('-'.(self::$global->unoperated['systemconfig_data']-60).' second');
  117. $unoperated = strtotime('-'.(self::$global->unoperated['systemconfig_data']).' second');
  118. $noResponse = strtotime('-'.(self::$global->noResponse['systemconfig_data']).' second');
  119. foreach ($serviceLog as $k => $v) {//注意该循环时间
  120. if (!strlen(array_search($v['servicelog_id'], array_column($chatLog, 'servicelog_id')))) {
  121. // 如果小于设定时间则关闭会话.
  122. if ($v['start_time'] <= $unoperated) {
  123. self::serverClose($v['client_id']);
  124. // 如果小于设定时间前一分钟则给出提示.
  125. } elseif ($v['start_time'] <= $setUnoperated) {
  126. $chat_message = [
  127. 'message_type' => 'overtime',
  128. 'data' => [
  129. 'content' => htmlspecialchars(self::$global->unoperated['systemconfig_content']),
  130. ]
  131. ];
  132. Gateway::sendToClient($v['client_id'], json_encode($chat_message));
  133. }
  134. }
  135. }
  136. // 循环检测会话时效.
  137. foreach ($chatLog as $k => $v) {
  138. $toWho = substr($v['to_id'],0,2);
  139. // 如果对话为客服的最后一次对话且时间小于设定时间则结束工单.
  140. if ($toWho != 'KF' && $v['time_line'] <= $overtime) {
  141. $found_key = array_search($v['servicelog_id'], array_column($serviceLog, 'servicelog_id'));
  142. self::serverClose($serviceLog[$found_key]['client_id']);
  143. // 如果对话为客服的最后一次对话且时间小于设定时间前一分钟则给出提示.
  144. } elseif ($toWho != 'KF' && $v['time_line'] <= $setOvertime) {
  145. $chat_message = [
  146. 'message_type' => 'overtime',
  147. 'data' => [
  148. 'content' => htmlspecialchars(self::$global->overtime['systemconfig_content']),
  149. ]
  150. ];
  151. $found_key = array_search($v['servicelog_id'], array_column($serviceLog, 'servicelog_id'));
  152. Gateway::sendToClient($serviceLog[$found_key]['client_id'], json_encode($chat_message));
  153. }
  154. }
  155. });
  156. }
  157. /**
  158. * 当客户端连接时触发
  159. * 如果业务不需此回调可以删除onConnect
  160. *
  161. * @param int $client_id 连接id
  162. */
  163. public static function onConnect($client_id)
  164. {
  165. // 检测是否开启自动应答
  166. $sayHello = self::$db->query('select `word`,`status` from `ws_reply` where `id` = 1');
  167. if (!empty($sayHello) && 1 == $sayHello['0']['status']) {
  168. $hello = [
  169. 'message_type' => 'helloMessage',
  170. 'data' => [
  171. 'name' => '智能助手',
  172. 'time' => date('H:i'),
  173. 'content' => htmlspecialchars($sayHello['0']['word'])
  174. ]
  175. ];
  176. Gateway::sendToClient($client_id, json_encode($hello, 256));
  177. unset($hello);
  178. }
  179. unset($sayHello);
  180. }
  181. /**
  182. * 当客户端发来消息时触发
  183. * @param int $client_id 连接id
  184. * @param mixed $message 具体消息
  185. */
  186. public static function onMessage($client_id, $message)
  187. {
  188. if ($message == '{"type":"ping"}') {
  189. Gateway::sendToCurrentClient('{"type":"pong"}');
  190. return;
  191. } else {
  192. /*echo "onMessage: " . $message . "\r\n";
  193. print_r([self::$global->kfList, self::$global->userList, self::$global->uidSimpleList, self::$global->userToKf]);*/
  194. }
  195. $message = json_decode($message, true);
  196. switch ($message['type']) {
  197. // 客服初始化
  198. case 'init':
  199. self::Kfinit($client_id, $message);
  200. break;
  201. // 顾客初始化
  202. case 'userInit';
  203. self::userInitEnt($client_id, $message);
  204. break;
  205. // 聊天
  206. case 'chatMessage':
  207. $client = Gateway::getClientIdByUid($message['data']['to_id']);
  208. if (!empty($client)) {
  209. $chat_message = [
  210. 'message_type' => 'chatMessage',
  211. 'data' => [
  212. 'name' => $message['data']['from_name'],
  213. 'avatar' => $message['data']['from_avatar'],
  214. 'id' => $message['data']['from_id'],
  215. 'time' => date('H:i'),
  216. 'content' => htmlspecialchars($message['data']['content']),
  217. ]
  218. ];
  219. Gateway::sendToClient($client['0'], json_encode($chat_message));
  220. unset($chat_message);
  221. // 聊天信息入库
  222. $serviceLog = [
  223. 'from_id' => $message['data']['from_id'],
  224. 'from_name' => $message['data']['from_name'],
  225. 'from_avatar' => $message['data']['from_avatar'],
  226. 'to_id' => $message['data']['to_id'],
  227. 'to_name' => $message['data']['to_name'],
  228. 'content' => $message['data']['content'],
  229. 'servicelog_id' => $message['data']['conversationId'],
  230. 'time_line' => time()
  231. ];
  232. self::$db->insert('ws_chat_log')->cols($serviceLog)->query();
  233. unset($serviceLog);
  234. }
  235. break;
  236. // 转接
  237. case 'changeGroup':
  238. // 通知客户端转接中
  239. $simpleList = self::$global->uidSimpleList;
  240. if (!isset($simpleList[$message['uid']])) { // 客户已经退出
  241. return;
  242. }
  243. $userClient = $simpleList[$message['uid']]['0'];
  244. $userGroup = $simpleList[$message['uid']]['1']; // 会员原来的分组也是客服的分组
  245. $reLink = [
  246. 'message_type' => 'relinkMessage'
  247. ];
  248. Gateway::sendToClient($userClient, json_encode($reLink));
  249. unset($reLink);
  250. // 记录该客服与该会员的服务结束
  251. self::$db->query("update `ws_service_log` set `end_time` = " . time() . " , `status` = '2' where `client_id`= '" . $userClient . "'");
  252. // 从当前客服的服务表中删除这个会员
  253. $old = $kfList = self::$global->kfList;
  254. if (!isset($kfList[$userGroup])) {
  255. $waitMsg = '暂时没有相关客服上班,请稍后再咨询。';
  256. // 逐一通知
  257. foreach (self::$global->userList as $vo) {
  258. $waitMessage = [
  259. 'message_type' => 'wait',
  260. 'data' => [
  261. 'content' => $waitMsg,
  262. ]
  263. ];
  264. Gateway::sendToClient($userClient, json_encode($waitMessage, 256));
  265. unset($waitMessage);
  266. }
  267. return;
  268. }
  269. $myList = $kfList[$userGroup]; // 该客服分组数组
  270. foreach ($myList as $key => $vo) {
  271. if (in_array($userClient, $vo['user_info'])) {
  272. // 维护现在的该客服的服务信息
  273. $kfList[$userGroup][$key]['task'] -= 1; // 当前服务的人数 -1
  274. foreach ($vo['user_info'] as $k => $v) {
  275. if ($userClient == $v) {
  276. unset($kfList[$userGroup][$key]['user_info'][$k]);
  277. break;
  278. }
  279. }
  280. break;
  281. }
  282. }
  283. while (!self::$global->cas('kfList', $old, $kfList)) {
  284. }; // 刷新内存中客服的服务列表
  285. unset($old, $kfList, $myList);
  286. // 将会员加入队列中
  287. $userList = self::$global->userList;
  288. do {
  289. $NewUserList = $userList;
  290. $NewUserList[$message['uid']] = [
  291. 'id' => $message['uid'],
  292. 'name' => $message['name'],
  293. 'avatar' => $message['avatar'],
  294. 'ip' => $message['ip'],
  295. 'group' => $message['group'], // 指定要链接的分组
  296. 'client_id' => $userClient
  297. ];
  298. } while (!self::$global->cas('userList', $userList, $NewUserList));
  299. unset($NewUserList, $userList);
  300. // 执行会员分配通知双方
  301. self::userOnlineTask($userClient, $message['group']);
  302. unset($userClient, $userGroup);
  303. break;
  304. case 'closeUser':
  305. $userInfo = self::$global->uidSimpleList;
  306. if (isset($userInfo[$message['uid']])) {
  307. $waitMessage = [
  308. 'message_type' => 'wait',
  309. 'data' => [
  310. 'content' => '暂时没有客服上班,请稍后再咨询。',
  311. ]
  312. ];
  313. Gateway::sendToClient($userInfo[$message['uid']]['0'], json_encode($waitMessage, 256));
  314. unset($waitMessage);
  315. }
  316. unset($userInfo);
  317. break;
  318. // 机器人问答.
  319. case 'toRobot':
  320. self::toRobot($client_id, $message);
  321. break;
  322. // 评价.
  323. case 'evaluate':
  324. self::evaluate($client_id, $message);
  325. break;
  326. // 客服关闭会话.
  327. case 'kfCloseUser':
  328. $client = Gateway::getClientIdByUid($message['data']['to_id']);
  329. if (!empty($client)) {
  330. self::serverClose($client['0']);
  331. }
  332. break;
  333. case 'changeOtherhKeFu';
  334. self::changeOtherhKeFu($client_id, $message);
  335. break;
  336. // default:
  337. // Gateway::closeClient($client_id);
  338. }
  339. }
  340. //客户工单内部组转接
  341. public static function changeOtherhKeFu($client_id, $message)
  342. {
  343. $groupid = isset($message['group']) ? intval($message['group']) : 0;
  344. $toukfid = isset($message['toukfuid']) ? intval($message['toukfuid']) : 0;
  345. $fromkfuid = isset($message['fromkfuid']) ? $message['fromkfuid'] : 0;
  346. $uid = isset($message['uid']) ? $message['uid'] : 0;
  347. $word = isset($message['word']) ? $message['word'] : '';
  348. if (empty($groupid) || empty($toukfid) || empty($fromkfuid) || empty($uid) || empty($word) || ($toukfid == $fromkfuid)) {
  349. return false;
  350. }
  351. if (!Gateway::isUidOnline($toukfid) || !Gateway::isUidOnline($uid)) {
  352. return false;
  353. }
  354. $tokfidclientid = Gateway::getClientIdByUid($toukfid);
  355. $tokfidclientid = $tokfidclientid['0'];
  356. $uidclientid = Gateway::getClientIdByUid($uid);
  357. $uidclientid = $uidclientid['0'];
  358. $kfList = $kfList_new = self::$global->kfList;
  359. $userToKf = $userToKf_new = self::$global->userToKf;
  360. if (!isset($kfList[$groupid]) || !isset($kfList[$groupid][$toukfid]) || !isset($kfList[$groupid][$fromkfuid])) {
  361. return false;
  362. }
  363. foreach ($kfList[$groupid] as $key => $val) {
  364. if ($key == $fromkfuid) {
  365. $kfList_new[$groupid][$fromkfuid]['task']--;
  366. foreach ($kfList[$groupid][$key]['user_info'] as $skey => $sval) {
  367. if ($sval == $uidclientid) {
  368. unset($kfList_new[$groupid][$key]['user_info'][$skey]);
  369. }
  370. }
  371. }
  372. if ($key == $toukfid) {
  373. $kfList_new[$groupid][$toukfid]['task']++;
  374. array_push($kfList_new[$groupid][$key]['user_info'], $uidclientid);
  375. }
  376. }
  377. do {
  378. } while (!self::$global->cas('kfList', $kfList, $kfList_new));
  379. if (isset($userToKf[$uid])) {
  380. $userToKf_new[$uid]['1'] = $toukfid;
  381. }
  382. do {
  383. } while (!self::$global->cas('userToKf', $userToKf, $userToKf_new));
  384. /////////取消原有会话,开启新会话
  385. $histarttimelimit = time() - 3600*24 ;
  386. $bindval = ['user_id'=>$uid,'kf_id'=>intval(trim($toukfid,'KF')),'histime'=>$histarttimelimit] ;
  387. $oldlog = self::$db->select('*')->from('ws_service_log')->where('user_id= :user_id and client_id=:client_id and kf_id=:kf_id and status=2 and start_time>=:histime ' )->bindValues($bindval)->row();
  388. if (!$oldlog){ return false; }
  389. self::$db->update('ws_service_log')->cols(['status'=>2,'endtime'=>time()])->where('servicelog_id='.$oldlog['servicelog_id'])->query();
  390. unset($oldlog['servicelog_id']);
  391. $oldlog = array_merge($oldlog,['kf_id'=>intval(trim($toukfid,'KF')),'start_time'=>time(),'end_time'=>0,'status'=>1,'evaluate_id'=>0]);
  392. $new_id = self::$db->insert('ws_service_log')->cols($oldlog)->query();
  393. if (!$new_id){
  394. return false;
  395. }
  396. ///通知消息发送--------------
  397. // 通知会员发送信息绑定客服的id
  398. $noticeUser = [
  399. 'message_type' => 'connect',
  400. 'data' => [
  401. 'kf_id' => $toukfid,
  402. 'kf_name' => Gateway::getSession($toukfid)['name'],
  403. ]
  404. ];
  405. Gateway::sendToClient($uidclientid, json_encode($noticeUser, 256));
  406. unset($noticeUser);
  407. // 通知客服端绑定会员的信息
  408. $noticeKf = [
  409. 'message_type' => 'connect',
  410. 'data' => [
  411. 'user_info' => $uidclientid
  412. ]
  413. ];
  414. Gateway::sendToClient($tokfidclientid, json_encode($noticeKf, 256));
  415. unset($noticeKf);
  416. //回转接人,转接成功
  417. Gateway::sendToCurrentClient(json_encode(['message_type'=>'trunconnect','data'=>['status'=>1],256]));
  418. return ;
  419. }
  420. //客服接入sock,及初始化
  421. public static function Kfinit($client_id, $message)
  422. {
  423. $kfList = self::$global->kfList;
  424. //客服登陆验证 不符合的直接断掉
  425. $logcheck = true; //开发时使用
  426. //$logcheck = self::KfloginChedk($client_id, $message);
  427. if (!$logcheck) {
  428. Gateway::closeCurrentClient();
  429. return true;
  430. }
  431. // 如果该客服未在内存中记录则记录
  432. if (!isset($kfList[$message['group']]) || !array_key_exists($message['uid'], $kfList[$message['group']])) {
  433. do {
  434. $newKfList = $kfList;
  435. $newKfList[$message['group']][$message['uid']] = [
  436. 'id' => $message['uid'],
  437. 'name' => $message['name'],
  438. 'avatar' => $message['avatar'],
  439. 'client_id' => $client_id,
  440. 'task' => 0,
  441. 'user_info' => []
  442. ];
  443. } while (!self::$global->cas('kfList', $kfList, $newKfList));
  444. unset($newKfList, $kfList);
  445. } else if (isset($kfList[$message['group']][$message['uid']])) {
  446. do {
  447. $newKfList = $kfList;
  448. $newKfList[$message['group']][$message['uid']]['client_id'] = $client_id;
  449. } while (!self::$global->cas('kfList', $kfList, $newKfList));
  450. unset($newKfList, $kfList);
  451. }
  452. // 绑定 client_id 和 uid
  453. Gateway::bindUid($client_id, $message['uid']);
  454. $_SESSION['group'] = $message['group'];
  455. $_SESSION['iskefu'] = 1;
  456. $_SESSION['uid'] = $message['uid'];
  457. $_SESSION['name'] = $message['name'];
  458. // TODO 尝试拉取用户来服务 [二期规划]
  459. }
  460. //客服登陆验证
  461. public static function KfloginChedk($client, $messageArray)
  462. {
  463. $uid = isset($messageArray['uid']) ? ($messageArray['uid']) : '';
  464. $token = isset($messageArray['token']) ?   ($messageArray['token']) : '';
  465. if (empty($uid) || empty($token)) {
  466. return false;
  467. }
  468. $expire_time_vali = time() - 60 * 60 * 24 * 3;
  469. $kfid = intval(substr($uid, 2));
  470. $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();
  471. if ($ret) {
  472. self::$db->update('ws_users')->cols(array('online_status' => 1, 'online_connectid' => $client))->where('id=' . $kfid)->query();
  473. return $ret;
  474. }
  475. return false;
  476. }
  477. //用户发送邦定用户事件
  478. public static function userInitEnt($client_id, $message)
  479. {
  480. $userList = self::$global->userList;
  481. // 如果该顾客未在内存中记录则记录
  482. $uidSimpleList = self::$global->uidSimpleList;
  483. if (isset($uidSimpleList[$message['uid']])) {
  484. $uidSimpleList = self::$global->uidSimpleList;
  485. $oldclientid = $uidSimpleList[$message['uid']]['0'];
  486. Gateway::sendToClient($oldclientid, json_encode(['type' => 'reLoginErr', 'msg' => '相同账号登陆,本次退出'], 256));
  487. Gateway::closeClient($oldclientid);
  488. sleep(2);
  489. }
  490. if (!array_key_exists($message['uid'], $userList)) {
  491. do {
  492. $NewUserList = $userList;
  493. $NewUserList[$message['uid']] = [
  494. 'id' => $message['uid'],
  495. 'name' => $message['name'],
  496. 'avatar' => $message['avatar'],
  497. 'website' => $_SESSION['origin'],//$_SERVER['HTTP_ORIGIN'],
  498. 'browse' => Gateway::browse_info(),
  499. 'system' => Gateway::get_os(),
  500. 'ip' => isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '',
  501. 'group' => $message['group'],
  502. 'client_id' => $client_id
  503. ];
  504. } while (!self::$global->cas('userList', $userList, $NewUserList));
  505. unset($NewUserList, $userList);
  506. // 维护 UID对应的client_id 数组
  507. do {
  508. $old = $newList = self::$global->uidSimpleList;
  509. $newList[$message['uid']] = [
  510. $client_id,
  511. $message['group']
  512. ];
  513. } while (!self::$global->cas('uidSimpleList', $old, $newList));
  514. unset($old, $newList);
  515. // 写入接入值
  516. $key = date('Ymd') . 'total_in';
  517. self::$global->$key = 0;
  518. do {
  519. $oldKey = date('Ymd', strtotime('-1 day')); // 删除前一天的统计值
  520. unset(self::$global->$oldKey);
  521. } while (!self::$global->increment($key));
  522. unset($key);
  523. }
  524. // 绑定 client_id 和 uid
  525. Gateway::bindUid($client_id, $message['uid']);
  526. $_SESSION['iskefu'] = 0;
  527. $_SESSION['uid'] = $message['uid'];
  528. // 尝试分配新会员进入服务
  529. self::userOnlineTask($client_id, $message['group'], $message['uid']);
  530. }
  531. /**
  532. * 当用户断开连接时触发
  533. * @param int $client_id 连接id
  534. *
  535. * tips: 当服务端主动退出的时候,会出现 exit status 9.原因是:服务端主动断开之后,连接的客户端会走这个方法,而短时间内进程
  536. * 需要处理这多的逻辑,又有cas操作,导致进程退出会超时,然后会被内核杀死,从而报出错误 9.实际对真正的业务没有任何的影响。
  537. */
  538. public static function onClose($client_id)
  539. {
  540. $isKefuoff = isset($_SESSION['iskefu']) ? $_SESSION['iskefu'] : 0;
  541. $uid = isset($_SESSION['uid']) ? $_SESSION['uid'] : false;
  542. if (empty($uid)) {
  543. return;
  544. }
  545. if ($isKefuoff) {
  546. self::serviceOffline($client_id, $uid);
  547. } else {
  548. self::guestOffline($client_id, $uid);
  549. }
  550. return;
  551. }
  552. //客服下线了
  553. public static function serviceOffline($client_id, $uid)
  554. {
  555. $group = $_SESSION['group'];
  556. $kefuinfo_old = $kefuinfo_old_new = self::$global->kfList;
  557. $user_info = $kefuinfo_old_new[$group][$uid]['user_info'];
  558. $simpliUsers = self::$global->uidSimpleList;
  559. $simpliUsersID_UID_Arr = [];
  560. if (!empty($simpliUsers)) {
  561. foreach ($simpliUsers as $key => $val) {
  562. $simpliUsersID_UID_Arr[$val['0']] = $key;
  563. }
  564. }
  565. $now = time();
  566. if (!empty($user_info)) {
  567. foreach ($user_info as $val) {
  568. Gateway::sendToClient($val, json_encode(['type' => 'serviceoffline', 'msg' => '客户人员下线!'], 256));
  569. if (isset($simpliUsersID_UID_Arr[$val])) {
  570. self::$db->query("update `ws_service_log` set `status` = '2',end_time=$now where `user_id`= '$simpliUsersID_UID_Arr[$val]' and kf_id='$uid' and group_id=$group and `status`!=2 ");
  571. }
  572. Gateway::closeClient($val);
  573. }
  574. }
  575. unset($kefuinfo_old_new[$group][$uid]);
  576. $kfid = intval(substr($uid, 2));
  577. self::$db->update('ws_users')->cols(array('online_status' => 0, 'online_connectid' => ''))->where('id=' . $kfid)->query();
  578. do {
  579. } while (!self::$global->cas('kfList', $kefuinfo_old, $kefuinfo_old_new));
  580. return;
  581. }
  582. //用户下线了
  583. public static function guestOffline($client_id, $uid)
  584. {
  585. $kfuid = -1;
  586. $krclient_id = 0;
  587. $kfgroup = -1;
  588. $userToKf = $userToKfNew = self::$global->userToKf;
  589. if (isset($userToKfNew[$uid])) {
  590. $kfuid = isset($userToKfNew[$uid]['1']) ? $userToKfNew[$uid]['1'] : -1;
  591. $krclient_id = isset(Gateway::getClientIdByUid($kfuid)['0']) ? Gateway::getClientIdByUid($kfuid)['0'] : 0;
  592. unset($userToKfNew[$uid]);
  593. do {
  594. } while (!self::$global->cas('userToKf', $userToKf, $userToKfNew));
  595. }
  596. $uidSimpleList = $uidSimpleListNew = self::$global->uidSimpleList;
  597. if (isset($uidSimpleListNew[$uid])) {
  598. $kfgroup = $uidSimpleListNew[$uid]['1'];
  599. unset($uidSimpleListNew[$uid]);
  600. do {
  601. } while (!self::$global->cas('uidSimpleList', $uidSimpleList, $uidSimpleListNew));
  602. }
  603. $userList = $userListNew = self::$global->userList;
  604. if (!empty($userList)) {
  605. $ischange = 0;
  606. foreach ($userList as $key => $val) {
  607. if ($val['id'] == $uid) {
  608. unset($userListNew[$key]);
  609. $ischange = 1;
  610. break;
  611. }
  612. }
  613. if ($ischange) {
  614. do {
  615. } while (!self::$global->cas('userList', $userList, $userListNew));
  616. }
  617. }
  618. if ($kfuid != -1 && $kfgroup != -1) {
  619. $kefuinfo_old = $kefuinfo_old_new = self::$global->kfList;
  620. $ischange_kf_list = 0;
  621. if (isset($kefuinfo_old[$kfgroup][$kfuid])) {
  622. $infos = $kefuinfo_old[$kfgroup][$kfuid]['user_info'];
  623. if ($infos) {
  624. if (is_array($infos)) {
  625. foreach ($infos as $key => $val) {
  626. if ($val == $client_id) {
  627. $ischange_kf_list = 1;
  628. unset($kefuinfo_old_new[$kfgroup][$kfuid]['user_info'][$key]);
  629. $kefuinfo_old_new[$kfgroup][$kfuid]['task'] = $kefuinfo_old_new[$kfgroup][$kfuid]['task'] - 1;
  630. }
  631. }
  632. }
  633. if ($ischange_kf_list) {
  634. do {
  635. } while (!self::$global->cas('kfList', $kefuinfo_old, $kefuinfo_old_new));
  636. $chat_message = [
  637. 'message_type' => 'userClose',
  638. 'data' => [
  639. 'content' => '用户连接已断开',
  640. 'time' => date('H:i'),
  641. ]
  642. ];
  643. $now = time();
  644. $kf__uid = substr($kfuid, 2);
  645. $sql = "update `ws_service_log` set `status` = '3',end_time=$now where `user_id`= '$uid' and kf_id='$kf__uid' and group_id=$kfgroup and status=1 ";
  646. //echo "客户退出:". $sql ."\n";
  647. self::$db->query($sql);
  648. Gateway::sendToClient($krclient_id, json_encode($chat_message, 256));
  649. }
  650. }
  651. }
  652. }
  653. }
  654. /**
  655. * 客服结束会话
  656. * @param int $client_id 连接id
  657. *
  658. * tips: 当服务端主动退出的时候,会出现 exit status 9.原因是:服务端主动断开之后,连接的客户端会走这个方法,而短时间内进程
  659. * 需要处理这多的逻辑,又有cas操作,导致进程退出会超时,然后会被内核杀死,从而报出错误 9.实际对真正的业务没有任何的影响。
  660. */
  661. public static function serverClose($client_id)
  662. {
  663. // 返回.
  664. $chat_message = [
  665. 'message_type' => 'closeBysever',
  666. 'data' => [
  667. 'content' => '客服停止了该会话',
  668. 'time' => date('H:i'),
  669. ]
  670. ];
  671. Gateway::sendToClient($client_id, json_encode($chat_message, 256));
  672. Gateway::closeClient($client_id);
  673. $isServiceUserOut = false;
  674. // 将会员服务信息,从客服的服务列表中移除
  675. $old = $kfList = self::$global->kfList;
  676. foreach ($kfList as $k => $v) {
  677. foreach ($v as $key => $vo) {
  678. if (in_array($client_id, $vo['user_info'])) {
  679. $isServiceUserOut = true;
  680. // 根据client id 去更新会话工单一些信息
  681. self::$db->query("update `ws_service_log` set `end_time` = " . time() . " , `status` = '2' where `client_id`= '" . $client_id . "'");
  682. // 从会员的内存表中检索出该会员的信息,并更新内存
  683. $oldSimple = $simpleList = self::$global->uidSimpleList;
  684. $outUser = [];
  685. foreach ($simpleList as $u => $c) {
  686. if ($c['0'] == $client_id) {
  687. $outUser[] = [
  688. 'user_id' => $u,
  689. 'group_id' => $c['1']
  690. ];
  691. unset($simpleList[$u]);
  692. break;
  693. }
  694. }
  695. while (!self::$global->cas('uidSimpleList', $oldSimple, $simpleList)) {
  696. };
  697. unset($oldSimple, $simpleList);
  698. $outUser = self::$db->query("select `user_id`,`group_id` from `ws_service_log` where `client_id`= '" . $client_id . "'");
  699. // 通知 客服删除退出的用户
  700. if (!empty($outUser)) {
  701. $del_message = [
  702. 'message_type' => 'delUser',
  703. 'data' => [
  704. 'id' => $outUser['0']['user_id']
  705. ]
  706. ];
  707. Gateway::sendToClient($vo['client_id'], json_encode($del_message, 256));
  708. unset($del_message);
  709. // 尝试分配新会员进入服务
  710. self::userOfflineTask($outUser['0']['group_id']);
  711. }
  712. unset($outUser);
  713. // 维护现在的该客服的服务信息
  714. $kfList[$k][$key]['task'] -= 1; // 当前服务的人数 -1
  715. foreach ($vo['user_info'] as $m => $l) {
  716. if ($client_id == $l) {
  717. unset($kfList[$k][$key]['user_info'][$m]);
  718. break;
  719. }
  720. }
  721. // 刷新内存中客服的服务列表
  722. while (!self::$global->cas('kfList', $old, $kfList)) {
  723. };
  724. unset($old, $kfList);
  725. break;
  726. }
  727. }
  728. if ($isServiceUserOut) break;
  729. }
  730. // 尝试从排队的用户中删除退出的客户端
  731. if (false == $isServiceUserOut) {
  732. $old = $userList = self::$global->userList;
  733. foreach (self::$global->userList as $key => $vo) {
  734. if ($client_id == $vo['client_id']) {
  735. $isServiceUserOut = true;
  736. unset($userList[$key]);
  737. break;
  738. }
  739. }
  740. while (!self::$global->cas('userList', $old, $userList)) {
  741. };
  742. // 从会员的内存表中检索出该会员的信息,并更新内存
  743. $oldSimple = $simpleList = self::$global->uidSimpleList;
  744. foreach ($simpleList as $u => $c) {
  745. if ($c['0'] == $client_id) {
  746. unset($simpleList[$u]);
  747. break;
  748. }
  749. }
  750. while (!self::$global->cas('uidSimpleList', $oldSimple, $simpleList)) {
  751. };
  752. unset($oldSimple, $simpleList);
  753. }
  754. // 尝试是否是客服退出
  755. if (false == $isServiceUserOut) {
  756. $old = $kfList = self::$global->kfList;
  757. foreach (self::$global->kfList as $k => $v) {
  758. foreach ($v as $key => $vo) {
  759. // 客服服务列表中无数据,才去删除客服内存信息
  760. if ($client_id == $vo['client_id'] && (0 == count($vo['user_info']))) {
  761. unset($kfList[$k][$key]);
  762. break;
  763. }
  764. }
  765. }
  766. while (!self::$global->cas('kfList', $old, $kfList)) {
  767. };
  768. }
  769. }
  770. /**
  771. * 有人退出
  772. * @param $group
  773. */
  774. private static function userOfflineTask($group)
  775. {
  776. // TODO 此处查询最大的可服务人数,后面可以用其他的方式,存储这个数值,让其更高效的访问
  777. $maxNumber = self::getMaxServiceNum();
  778. $res = self::assignmentTask(self::$global->kfList, self::$global->userList, $group, $maxNumber);
  779. unset($maxNumber);
  780. if (1 == $res['code']) {
  781. while (!self::$global->cas('kfList', self::$global->kfList, $res['data']['4'])) {
  782. }; // 更新客服数据
  783. while (!self::$global->cas('userList', self::$global->userList, $res['data']['5'])) {
  784. }; // 更新会员数据
  785. // 通知会员发送信息绑定客服的id
  786. $noticeUser = [
  787. 'message_type' => 'connect',
  788. 'data' => [
  789. 'kf_id' => $res['data']['0'],
  790. 'kf_name' => $res['data']['1']
  791. ]
  792. ];
  793. Gateway::sendToClient($res['data']['3']['client_id'], json_encode($noticeUser, 256));
  794. unset($noticeUser);
  795. // 通知客服端绑定会员的信息
  796. $noticeKf = [
  797. 'message_type' => 'connect',
  798. 'data' => [
  799. 'user_info' => $res['data']['3']
  800. ]
  801. ];
  802. Gateway::sendToClient($res['data']['2'], json_encode($noticeKf, 256));
  803. unset($noticeKf);
  804. // 逐一通知
  805. $number = 1;
  806. foreach (self::$global->userList as $vo) {
  807. $waitMsg = '您前面还有 ' . $number . ' 位会员在等待。';
  808. $waitMessage = [
  809. 'message_type' => 'wait',
  810. 'data' => [
  811. 'content' => $waitMsg,
  812. ]
  813. ];
  814. Gateway::sendToClient($vo['client_id'], json_encode($waitMessage, 256));
  815. $number++;
  816. }
  817. unset($waitMessage, $number);
  818. // 写入接入值
  819. $key = date('Ymd') . 'success_in';
  820. self::$global->$key = 0;
  821. do {
  822. $oldKey = date('Ymd', strtotime('-1 day')); // 删除前一天的统计值
  823. unset(self::$global->$oldKey);
  824. } while (!self::$global->increment($key));
  825. unset($key);
  826. } else {
  827. switch ($res['code']) {
  828. case -1:
  829. $waitMsg = '暂时没有客服上班,请稍后再咨询。';
  830. // 逐一通知
  831. foreach (self::$global->userList as $vo) {
  832. $waitMessage = [
  833. 'message_type' => 'wait',
  834. 'data' => [
  835. 'content' => $waitMsg,
  836. ]
  837. ];
  838. Gateway::sendToClient($vo['client_id'], json_encode($waitMessage, 256));
  839. }
  840. break;
  841. case -2:
  842. break;
  843. case -3:
  844. break;
  845. case -4:
  846. // 逐一通知
  847. $number = 1;
  848. foreach (self::$global->userList as $vo) {
  849. $waitMsg = '您前面还有 ' . $number . ' 位会员在等待。';
  850. $waitMessage = [
  851. 'message_type' => 'wait',
  852. 'data' => [
  853. 'content' => $waitMsg,
  854. ]
  855. ];
  856. Gateway::sendToClient($vo['client_id'], json_encode($waitMessage, 256));
  857. $number++;
  858. }
  859. break;
  860. }
  861. unset($waitMessage, $number);
  862. }
  863. }
  864. /**
  865. * 有人进入执行分配
  866. * @param $client_id
  867. * @param $group
  868. * @param $uid
  869. */
  870. private static function userOnlineTask($client_id, $group, $uid = 0)
  871. {
  872. // TODO 此处查询最大的可服务人数,后面可以用其他的方式,存储这个数值,让其更高效的访问
  873. $maxNumber = self::getMaxServiceNum();
  874. $res = self::assignmentTask(self::$global->kfList, self::$global->userList, $group, $maxNumber, $uid);
  875. unset($maxNumber);
  876. if (1 == $res['code']) {
  877. while (!self::$global->cas('kfList', self::$global->kfList, $res['data']['4'])) {
  878. }; // 更新客服数据
  879. while (!self::$global->cas('userList', self::$global->userList, $res['data']['5'])) {
  880. }; // 更新会员数据
  881. $userToKf = self::$global->userToKf;
  882. $userToKf[$res['data']['3']['id']] = [
  883. $res['data']['3']['id'],
  884. $res['data']['0']
  885. ];
  886. self::$global->userToKf = $userToKf;
  887. // 服务信息入库
  888. $serviceLog = [
  889. 'user_id' => $res['data']['3']['id'],
  890. 'client_id' => $res['data']['3']['client_id'],
  891. 'user_name' => $res['data']['3']['name'],
  892. 'user_ip' => $res['data']['3']['ip'],
  893. 'user_avatar' => $res['data']['3']['avatar'],
  894. 'kf_id' => intval(ltrim($res['data']['0'], 'KF')),
  895. 'start_time' => time(),
  896. 'group_id' => $group,
  897. 'website' => $res['data']['3']['website'],
  898. 'system' => $res['data']['3']['system'],
  899. 'browse' => $res['data']['3']['browse'],
  900. 'status' => 1,
  901. 'end_time' => 0
  902. ];
  903. $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();
  904. if (!$hisSession) {
  905. $conversationId = self::$db->insert('ws_service_log')->cols($serviceLog)->query();
  906. } else {
  907. self::$db->update('ws_service_log')->cols(['status' => 1])->where('servicelog_id=' . $hisSession['servicelog_id'])->query();
  908. $conversationId = $hisSession['servicelog_id'];
  909. }
  910. unset($serviceLog);
  911. // 通知会员发送信息绑定客服的id
  912. $noticeUser = [
  913. 'message_type' => 'connect',
  914. 'data' => [
  915. 'kf_id' => $res['data']['0'],
  916. 'conversationId' => $conversationId,
  917. 'kf_name' => $res['data']['1']
  918. ]
  919. ];
  920. Gateway::sendToClient($client_id, json_encode($noticeUser, 256));
  921. unset($noticeUser);
  922. // 通知客服端绑定会员的信息
  923. $noticeKf = [
  924. 'message_type' => 'connect',
  925. 'data' => [
  926. 'user_info' => $res['data']['3'],
  927. 'conversationId' => $conversationId,
  928. ]
  929. ];
  930. Gateway::sendToClient($res['data']['2'], json_encode($noticeKf, 256));
  931. unset($noticeKf);
  932. // 写入接入值
  933. $key = date('Ymd') . 'success_in';
  934. self::$global->$key = 0;
  935. do {
  936. $oldKey = date('Ymd', strtotime('-1 day')); // 删除前一天的统计值
  937. unset(self::$global->$oldKey);
  938. } while (!self::$global->increment($key));
  939. unset($key);
  940. } else {
  941. $waitMsg = '';
  942. switch ($res['code']) {
  943. case -1:
  944. $waitMsg = '暂时没有客服上班,请稍后再咨询。';
  945. break;
  946. case -2:
  947. break;
  948. case -3:
  949. break;
  950. case -4:
  951. $number = count(self::$global->userList);
  952. $waitMsg = '您前面还有 ' . $number . ' 位会员在等待。';
  953. break;
  954. }
  955. $waitMessage = [
  956. 'message_type' => 'wait',
  957. 'data' => [
  958. 'content' => $waitMsg,
  959. ]
  960. ];
  961. Gateway::sendToClient($client_id, json_encode($waitMessage, 256));
  962. unset($waitMessage);
  963. }
  964. }
  965. /**
  966. * 给客服分配会员【均分策略】
  967. * @param $kfList
  968. * @param $userList
  969. * @param $group
  970. * @param $total
  971. */
  972. private static function assignmentTask($kfList, $userList, $group, $total, $uid = 0)
  973. {
  974. // 没有客服上线
  975. if (empty($kfList) || empty($kfList[$group])) {
  976. return ['code' => -1];
  977. }
  978. // 没有待分配的会员
  979. if (empty($userList)) {
  980. return ['code' => -2];
  981. }
  982. // 未设置每个客服可以服务多少人
  983. if (0 == $total) {
  984. return ['code' => -3];
  985. }
  986. // 查看该组的客服是否在线
  987. if (!isset($kfList[$group])) {
  988. return ['code' => -1];
  989. }
  990. //上次用户掉线后,还可以继续上一次 (如果没有关闭) 的会话 --1
  991. $odltalksession = false;
  992. $user = $user_first = array_shift($userList);
  993. if ($uid > 0 && $user['id'] != $uid && count($userList) > 1) {
  994. $timevalielimit = time() - 60 * 5;
  995. $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();
  996. if ($odltalksession) {
  997. foreach ($userList as $ttkey => $ttval) {
  998. if ($ttval['id'] == $uid) {
  999. array_unshift($userList, $user);
  1000. $user = $userList[$ttkey];
  1001. unset($userList[$ttkey]);
  1002. break;
  1003. }
  1004. }
  1005. }
  1006. }
  1007. //上次用户掉线后,还可以继续上一次 (如果没有关闭) 的会话 --2
  1008. if ($odltalksession) {
  1009. $oldkrid = 'KF' . $odltalksession['kf_id'];
  1010. if (isset($kfList[$group][$oldkrid])) {
  1011. $kf = $kfList[$group][$oldkrid];
  1012. $min = $kf['task'];
  1013. $flag = $kf['id'];
  1014. unset($kfList[$group][$oldkrid]);
  1015. } else {
  1016. goto NOSIGNKF;
  1017. }
  1018. } else {
  1019. NOSIGNKF:
  1020. $kf = $kfList[$group];
  1021. $kf = array_shift($kf);
  1022. $min = $kf['task'];
  1023. $flag = $kf['id'];
  1024. foreach ($kfList[$group] as $key => $vo) {
  1025. if ($vo['task'] < $min) {
  1026. $min = $vo['task'];
  1027. $flag = $key;
  1028. }
  1029. }
  1030. unset($kf);
  1031. }
  1032. // 需要排队了
  1033. if ($kfList[$group][$flag]['task'] == $total) {
  1034. return ['code' => -4];
  1035. }
  1036. $kfList[$group][$flag]['task'] += 1;
  1037. array_push($kfList[$group][$flag]['user_info'], $user['client_id']); // 被分配的用户信息
  1038. return [
  1039. 'code' => 1,
  1040. 'data' => [
  1041. $kfList[$group][$flag]['id'],
  1042. $kfList[$group][$flag]['name'],
  1043. $kfList[$group][$flag]['client_id'],
  1044. $user,
  1045. $kfList,
  1046. $userList
  1047. ]
  1048. ];
  1049. }
  1050. /**
  1051. * 获取最大的服务人数
  1052. * @return int
  1053. */
  1054. private static function getMaxServiceNum()
  1055. {
  1056. $maxNumber = self::$db->query('select `max_service` from `ws_kf_config` where `id` = 1');
  1057. if (!empty($maxNumber)) {
  1058. $maxNumber = 5;
  1059. } else {
  1060. $maxNumber = $maxNumber['0']['max_service'];
  1061. }
  1062. return $maxNumber;
  1063. }
  1064. /**
  1065. * 将内存中的数据写入统计表
  1066. * @param int $flag
  1067. */
  1068. private static function writeLog($flag = 1)
  1069. {
  1070. // 上午 8点 到 22 点开始统计
  1071. if (date('H') < 8 || date('H') > 22) {
  1072. return;
  1073. }
  1074. // 当前正在接入的人 和 在线客服数
  1075. $kfList = self::$global->kfList;
  1076. $nowTalking = 0;
  1077. $onlineKf = 0;
  1078. if (!empty($kfList)) {
  1079. foreach ($kfList as $key => $vo) {
  1080. $onlineKf += count($vo);
  1081. foreach ($vo as $k => $v) {
  1082. $nowTalking += count($v['user_info']);
  1083. }
  1084. }
  1085. }
  1086. // 在队列中的用户
  1087. $inQueue = count(self::$global->userList);
  1088. $key = date('Ymd') . 'total_in';
  1089. $key2 = date('Ymd') . 'success_in';
  1090. $param = [
  1091. 'is_talking' => $nowTalking,
  1092. 'in_queue' => $inQueue,
  1093. 'online_kf' => $onlineKf,
  1094. 'success_in' => self::$global->$key2,
  1095. 'total_in' => self::$global->$key,
  1096. 'now_date' => date('Y-m-d')
  1097. ];
  1098. self::$db->update('ws_now_data')->cols($param)->where('id=1')->query();
  1099. if (2 == $flag) {
  1100. $param = [
  1101. 'is_talking' => $nowTalking,
  1102. 'in_queue' => $inQueue,
  1103. 'online_kf' => $onlineKf,
  1104. 'success_in' => self::$global->$key2,
  1105. 'total_in' => self::$global->$key,
  1106. 'add_date' => date('Y-m-d'),
  1107. 'add_hour' => date('H'),
  1108. 'add_minute' => date('i'),
  1109. ];
  1110. self::$db->insert('ws_service_data')->cols($param)->query();
  1111. }
  1112. unset($kfList, $nowTalking, $inQueue, $onlineKf, $key, $key2, $param);
  1113. }
  1114. /**
  1115. * 机器人问答
  1116. * @param $client_id 服务ID
  1117. * @param $message 数据
  1118. */
  1119. private static function toRobot($client_id, $message)
  1120. {
  1121. $groups_id = $message['data']['groups_id'];
  1122. $robot_name = $message['data']['robot_name'];
  1123. $robotgroups_id = $message['data']['robotgroups_id'];
  1124. // 查询问题.
  1125. $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 . "'");
  1126. $chat_message = [
  1127. 'message_type' => 'chatMessage',
  1128. 'data' => [
  1129. 'name' => '智能助手',
  1130. 'time' => date('H:i'),
  1131. 'content' => $getRobot ? htmlspecialchars($getRobot[0]['robot_content']) : 'error',
  1132. ]
  1133. ];
  1134. Gateway::sendToClient($client_id, json_encode($chat_message, 256));
  1135. }
  1136. /**
  1137. * 评价
  1138. * @param $client_id 服务ID
  1139. * @param $message 数据
  1140. */
  1141. private static function evaluate($client_id, $message)
  1142. {
  1143. // 修改数据库.
  1144. $evaluate_id = $message['data']['evaluate_id'];
  1145. $result = self::$db->query("UPDATE `ws_service_log` SET `evaluate_id` = '" . $evaluate_id . "' WHERE `client_id`='" . $client_id . "'");
  1146. if ($result) {
  1147. $chat_message = [
  1148. 'message_type' => 'evaluate',
  1149. 'data' => [
  1150. 'status' => 1,
  1151. 'time' => date('H:i'),
  1152. ]
  1153. ];
  1154. } else {
  1155. $chat_message = [
  1156. 'message_type' => 'evaluate',
  1157. 'data' => [
  1158. 'status' => 2,
  1159. 'time' => date('H:i'),
  1160. ]
  1161. ];
  1162. }
  1163. Gateway::sendToClient($client_id, json_encode($chat_message));
  1164. }
  1165. //踢掉同一用户的旧用户
  1166. private static function tickOlduser($uid)
  1167. {
  1168. }
  1169. }