Events.php 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333
  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){
  389. self::$db->update('ws_service_log')->cols(['status'=>2,'endtime'=>time()])->where('servicelog_id='.$oldlog['servicelog_id'])->query();
  390. }
  391. unset($oldlog['servicelog_id']);
  392. $oldlog['kf_id'] = intval(trim($toukfid,'KF'));
  393. $oldlog['start_time'] = time();
  394. $oldlog['end_time'] = 0 ;
  395. $oldlog['status'] = 1 ;
  396. $oldlog['evaluate_id'] = 0 ;
  397. $new_id = self::$db->insert('ws_service_log')->cols($oldlog)->query();
  398. if (!$new_id){
  399. return false;
  400. }
  401. ///通知消息发送--------------
  402. // 通知会员发送信息绑定客服的id
  403. $noticeUser = [
  404. 'message_type' => 'connect',
  405. 'data' => [
  406. 'kf_id' => $toukfid,
  407. 'kf_name' => Gateway::getSession($toukfid)['name'],
  408. ]
  409. ];
  410. Gateway::sendToClient($uidclientid, json_encode($noticeUser, 256));
  411. unset($noticeUser);
  412. // 通知客服端绑定会员的信息
  413. $noticeKf = [
  414. 'message_type' => 'connect',
  415. 'data' => [
  416. 'user_info' => $uidclientid
  417. ]
  418. ];
  419. Gateway::sendToClient($tokfidclientid, json_encode($noticeKf, 256));
  420. unset($noticeKf);
  421. //回转接人,转接成功
  422. Gateway::sendToCurrentClient(json_encode(['message_type'=>'trunconnect','data'=>['status'=>1],256]));
  423. return ;
  424. }
  425. //客服接入sock,及初始化
  426. public static function Kfinit($client_id, $message)
  427. {
  428. $kfList = self::$global->kfList;
  429. //客服登陆验证 不符合的直接断掉
  430. $logcheck = true; //开发时使用
  431. //$logcheck = self::KfloginChedk($client_id, $message);
  432. if (!$logcheck) {
  433. Gateway::closeCurrentClient();
  434. return true;
  435. }
  436. // 如果该客服未在内存中记录则记录
  437. if (!isset($kfList[$message['group']]) || !array_key_exists($message['uid'], $kfList[$message['group']])) {
  438. do {
  439. $newKfList = $kfList;
  440. $newKfList[$message['group']][$message['uid']] = [
  441. 'id' => $message['uid'],
  442. 'name' => $message['name'],
  443. 'avatar' => $message['avatar'],
  444. 'client_id' => $client_id,
  445. 'task' => 0,
  446. 'user_info' => []
  447. ];
  448. } while (!self::$global->cas('kfList', $kfList, $newKfList));
  449. unset($newKfList, $kfList);
  450. } else if (isset($kfList[$message['group']][$message['uid']])) {
  451. do {
  452. $newKfList = $kfList;
  453. $newKfList[$message['group']][$message['uid']]['client_id'] = $client_id;
  454. } while (!self::$global->cas('kfList', $kfList, $newKfList));
  455. unset($newKfList, $kfList);
  456. }
  457. // 绑定 client_id 和 uid
  458. Gateway::bindUid($client_id, $message['uid']);
  459. $_SESSION['group'] = $message['group'];
  460. $_SESSION['iskefu'] = 1;
  461. $_SESSION['uid'] = $message['uid'];
  462. $_SESSION['name'] = $message['name'];
  463. // TODO 尝试拉取用户来服务 [二期规划]
  464. }
  465. //客服登陆验证
  466. public static function KfloginChedk($client, $messageArray)
  467. {
  468. $uid = isset($messageArray['uid']) ? ($messageArray['uid']) : '';
  469. $token = isset($messageArray['token']) ?   ($messageArray['token']) : '';
  470. if (empty($uid) || empty($token)) {
  471. return false;
  472. }
  473. $expire_time_vali = time() - 60 * 60 * 24 * 3;
  474. $kfid = intval(substr($uid, 2));
  475. $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();
  476. if ($ret) {
  477. self::$db->update('ws_users')->cols(array('online_status' => 1, 'online_connectid' => $client))->where('id=' . $kfid)->query();
  478. return $ret;
  479. }
  480. return false;
  481. }
  482. //用户发送邦定用户事件
  483. public static function userInitEnt($client_id, $message)
  484. {
  485. $userList = self::$global->userList;
  486. // 如果该顾客未在内存中记录则记录
  487. $uidSimpleList = self::$global->uidSimpleList;
  488. if (isset($uidSimpleList[$message['uid']])) {
  489. $uidSimpleList = self::$global->uidSimpleList;
  490. $oldclientid = $uidSimpleList[$message['uid']]['0'];
  491. Gateway::sendToClient($oldclientid, json_encode(['type' => 'reLoginErr', 'msg' => '相同账号登陆,本次退出'], 256));
  492. Gateway::closeClient($oldclientid);
  493. sleep(2);
  494. }
  495. if (!array_key_exists($message['uid'], $userList)) {
  496. do {
  497. $NewUserList = $userList;
  498. $NewUserList[$message['uid']] = [
  499. 'id' => $message['uid'],
  500. 'name' => $message['name'],
  501. 'avatar' => $message['avatar'],
  502. 'website' => $_SESSION['origin'],//$_SERVER['HTTP_ORIGIN'],
  503. 'browse' => Gateway::browse_info(),
  504. 'system' => Gateway::get_os(),
  505. 'ip' => isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '',
  506. 'group' => $message['group'],
  507. 'client_id' => $client_id
  508. ];
  509. } while (!self::$global->cas('userList', $userList, $NewUserList));
  510. unset($NewUserList, $userList);
  511. // 维护 UID对应的client_id 数组
  512. do {
  513. $old = $newList = self::$global->uidSimpleList;
  514. $newList[$message['uid']] = [
  515. $client_id,
  516. $message['group']
  517. ];
  518. } while (!self::$global->cas('uidSimpleList', $old, $newList));
  519. unset($old, $newList);
  520. // 写入接入值
  521. $key = date('Ymd') . 'total_in';
  522. self::$global->$key = 0;
  523. do {
  524. $oldKey = date('Ymd', strtotime('-1 day')); // 删除前一天的统计值
  525. unset(self::$global->$oldKey);
  526. } while (!self::$global->increment($key));
  527. unset($key);
  528. }
  529. // 绑定 client_id 和 uid
  530. Gateway::bindUid($client_id, $message['uid']);
  531. $_SESSION['iskefu'] = 0;
  532. $_SESSION['uid'] = $message['uid'];
  533. // 尝试分配新会员进入服务
  534. self::userOnlineTask($client_id, $message['group'], $message['uid']);
  535. }
  536. /**
  537. * 当用户断开连接时触发
  538. * @param int $client_id 连接id
  539. *
  540. * tips: 当服务端主动退出的时候,会出现 exit status 9.原因是:服务端主动断开之后,连接的客户端会走这个方法,而短时间内进程
  541. * 需要处理这多的逻辑,又有cas操作,导致进程退出会超时,然后会被内核杀死,从而报出错误 9.实际对真正的业务没有任何的影响。
  542. */
  543. public static function onClose($client_id)
  544. {
  545. $isKefuoff = isset($_SESSION['iskefu']) ? $_SESSION['iskefu'] : 0;
  546. $uid = isset($_SESSION['uid']) ? $_SESSION['uid'] : false;
  547. if (empty($uid)) {
  548. return;
  549. }
  550. if ($isKefuoff) {
  551. self::serviceOffline($client_id, $uid);
  552. } else {
  553. self::guestOffline($client_id, $uid);
  554. }
  555. return;
  556. }
  557. //客服下线了
  558. public static function serviceOffline($client_id, $uid)
  559. {
  560. $group = $_SESSION['group'];
  561. $kefuinfo_old = $kefuinfo_old_new = self::$global->kfList;
  562. $user_info = $kefuinfo_old_new[$group][$uid]['user_info'];
  563. $simpliUsers = self::$global->uidSimpleList;
  564. $simpliUsersID_UID_Arr = [];
  565. if (!empty($simpliUsers)) {
  566. foreach ($simpliUsers as $key => $val) {
  567. $simpliUsersID_UID_Arr[$val['0']] = $key;
  568. }
  569. }
  570. $now = time();
  571. if (!empty($user_info)) {
  572. foreach ($user_info as $val) {
  573. Gateway::sendToClient($val, json_encode(['type' => 'serviceoffline', 'msg' => '客户人员下线!'], 256));
  574. if (isset($simpliUsersID_UID_Arr[$val])) {
  575. 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 ");
  576. }
  577. Gateway::closeClient($val);
  578. }
  579. }
  580. unset($kefuinfo_old_new[$group][$uid]);
  581. $kfid = intval(substr($uid, 2));
  582. self::$db->update('ws_users')->cols(array('online_status' => 0, 'online_connectid' => ''))->where('id=' . $kfid)->query();
  583. do {
  584. } while (!self::$global->cas('kfList', $kefuinfo_old, $kefuinfo_old_new));
  585. return;
  586. }
  587. //用户下线了
  588. public static function guestOffline($client_id, $uid)
  589. {
  590. $kfuid = -1;
  591. $krclient_id = 0;
  592. $kfgroup = -1;
  593. $userToKf = $userToKfNew = self::$global->userToKf;
  594. if (isset($userToKfNew[$uid])) {
  595. $kfuid = isset($userToKfNew[$uid]['1']) ? $userToKfNew[$uid]['1'] : -1;
  596. $krclient_id = isset(Gateway::getClientIdByUid($kfuid)['0']) ? Gateway::getClientIdByUid($kfuid)['0'] : 0;
  597. unset($userToKfNew[$uid]);
  598. do {
  599. } while (!self::$global->cas('userToKf', $userToKf, $userToKfNew));
  600. }
  601. $uidSimpleList = $uidSimpleListNew = self::$global->uidSimpleList;
  602. if (isset($uidSimpleListNew[$uid])) {
  603. $kfgroup = $uidSimpleListNew[$uid]['1'];
  604. unset($uidSimpleListNew[$uid]);
  605. do {
  606. } while (!self::$global->cas('uidSimpleList', $uidSimpleList, $uidSimpleListNew));
  607. }
  608. $userList = $userListNew = self::$global->userList;
  609. if (!empty($userList)) {
  610. $ischange = 0;
  611. foreach ($userList as $key => $val) {
  612. if ($val['id'] == $uid) {
  613. unset($userListNew[$key]);
  614. $ischange = 1;
  615. break;
  616. }
  617. }
  618. if ($ischange) {
  619. do {
  620. } while (!self::$global->cas('userList', $userList, $userListNew));
  621. }
  622. }
  623. if ($kfuid != -1 && $kfgroup != -1) {
  624. $kefuinfo_old = $kefuinfo_old_new = self::$global->kfList;
  625. $ischange_kf_list = 0;
  626. if (isset($kefuinfo_old[$kfgroup][$kfuid])) {
  627. $infos = $kefuinfo_old[$kfgroup][$kfuid]['user_info'];
  628. if ($infos) {
  629. if (is_array($infos)) {
  630. foreach ($infos as $key => $val) {
  631. if ($val == $client_id) {
  632. $ischange_kf_list = 1;
  633. unset($kefuinfo_old_new[$kfgroup][$kfuid]['user_info'][$key]);
  634. $kefuinfo_old_new[$kfgroup][$kfuid]['task'] = $kefuinfo_old_new[$kfgroup][$kfuid]['task'] - 1;
  635. }
  636. }
  637. }
  638. if ($ischange_kf_list) {
  639. do {
  640. } while (!self::$global->cas('kfList', $kefuinfo_old, $kefuinfo_old_new));
  641. $chat_message = [
  642. 'message_type' => 'userClose',
  643. 'data' => [
  644. 'content' => '用户连接已断开',
  645. 'time' => date('H:i'),
  646. ]
  647. ];
  648. $now = time();
  649. $kf__uid = substr($kfuid, 2);
  650. $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 ";
  651. //echo "客户退出:". $sql ."\n";
  652. self::$db->query($sql);
  653. Gateway::sendToClient($krclient_id, json_encode($chat_message, 256));
  654. }
  655. }
  656. }
  657. }
  658. }
  659. /**
  660. * 客服结束会话
  661. * @param int $client_id 连接id
  662. *
  663. * tips: 当服务端主动退出的时候,会出现 exit status 9.原因是:服务端主动断开之后,连接的客户端会走这个方法,而短时间内进程
  664. * 需要处理这多的逻辑,又有cas操作,导致进程退出会超时,然后会被内核杀死,从而报出错误 9.实际对真正的业务没有任何的影响。
  665. */
  666. public static function serverClose($client_id)
  667. {
  668. // 返回.
  669. $chat_message = [
  670. 'message_type' => 'closeBysever',
  671. 'data' => [
  672. 'content' => '客服停止了该会话',
  673. 'time' => date('H:i'),
  674. ]
  675. ];
  676. Gateway::sendToClient($client_id, json_encode($chat_message, 256));
  677. Gateway::closeClient($client_id);
  678. $isServiceUserOut = false;
  679. // 将会员服务信息,从客服的服务列表中移除
  680. $old = $kfList = self::$global->kfList;
  681. foreach ($kfList as $k => $v) {
  682. foreach ($v as $key => $vo) {
  683. if (in_array($client_id, $vo['user_info'])) {
  684. $isServiceUserOut = true;
  685. // 根据client id 去更新会话工单一些信息
  686. self::$db->query("update `ws_service_log` set `end_time` = " . time() . " , `status` = '2' where `client_id`= '" . $client_id . "'");
  687. // 从会员的内存表中检索出该会员的信息,并更新内存
  688. $oldSimple = $simpleList = self::$global->uidSimpleList;
  689. $outUser = [];
  690. foreach ($simpleList as $u => $c) {
  691. if ($c['0'] == $client_id) {
  692. $outUser[] = [
  693. 'user_id' => $u,
  694. 'group_id' => $c['1']
  695. ];
  696. unset($simpleList[$u]);
  697. break;
  698. }
  699. }
  700. while (!self::$global->cas('uidSimpleList', $oldSimple, $simpleList)) {
  701. };
  702. unset($oldSimple, $simpleList);
  703. $outUser = self::$db->query("select `user_id`,`group_id` from `ws_service_log` where `client_id`= '" . $client_id . "'");
  704. // 通知 客服删除退出的用户
  705. if (!empty($outUser)) {
  706. $del_message = [
  707. 'message_type' => 'delUser',
  708. 'data' => [
  709. 'id' => $outUser['0']['user_id']
  710. ]
  711. ];
  712. Gateway::sendToClient($vo['client_id'], json_encode($del_message, 256));
  713. unset($del_message);
  714. // 尝试分配新会员进入服务
  715. self::userOfflineTask($outUser['0']['group_id']);
  716. }
  717. unset($outUser);
  718. // 维护现在的该客服的服务信息
  719. $kfList[$k][$key]['task'] -= 1; // 当前服务的人数 -1
  720. foreach ($vo['user_info'] as $m => $l) {
  721. if ($client_id == $l) {
  722. unset($kfList[$k][$key]['user_info'][$m]);
  723. break;
  724. }
  725. }
  726. // 刷新内存中客服的服务列表
  727. while (!self::$global->cas('kfList', $old, $kfList)) {
  728. };
  729. unset($old, $kfList);
  730. break;
  731. }
  732. }
  733. if ($isServiceUserOut) break;
  734. }
  735. // 尝试从排队的用户中删除退出的客户端
  736. if (false == $isServiceUserOut) {
  737. $old = $userList = self::$global->userList;
  738. foreach (self::$global->userList as $key => $vo) {
  739. if ($client_id == $vo['client_id']) {
  740. $isServiceUserOut = true;
  741. unset($userList[$key]);
  742. break;
  743. }
  744. }
  745. while (!self::$global->cas('userList', $old, $userList)) {
  746. };
  747. // 从会员的内存表中检索出该会员的信息,并更新内存
  748. $oldSimple = $simpleList = self::$global->uidSimpleList;
  749. foreach ($simpleList as $u => $c) {
  750. if ($c['0'] == $client_id) {
  751. unset($simpleList[$u]);
  752. break;
  753. }
  754. }
  755. while (!self::$global->cas('uidSimpleList', $oldSimple, $simpleList)) {
  756. };
  757. unset($oldSimple, $simpleList);
  758. }
  759. // 尝试是否是客服退出
  760. if (false == $isServiceUserOut) {
  761. $old = $kfList = self::$global->kfList;
  762. foreach (self::$global->kfList as $k => $v) {
  763. foreach ($v as $key => $vo) {
  764. // 客服服务列表中无数据,才去删除客服内存信息
  765. if ($client_id == $vo['client_id'] && (0 == count($vo['user_info']))) {
  766. unset($kfList[$k][$key]);
  767. break;
  768. }
  769. }
  770. }
  771. while (!self::$global->cas('kfList', $old, $kfList)) {
  772. };
  773. }
  774. }
  775. /**
  776. * 有人退出
  777. * @param $group
  778. */
  779. private static function userOfflineTask($group)
  780. {
  781. // TODO 此处查询最大的可服务人数,后面可以用其他的方式,存储这个数值,让其更高效的访问
  782. $maxNumber = self::getMaxServiceNum();
  783. $res = self::assignmentTask(self::$global->kfList, self::$global->userList, $group, $maxNumber);
  784. unset($maxNumber);
  785. if (1 == $res['code']) {
  786. while (!self::$global->cas('kfList', self::$global->kfList, $res['data']['4'])) {
  787. }; // 更新客服数据
  788. while (!self::$global->cas('userList', self::$global->userList, $res['data']['5'])) {
  789. }; // 更新会员数据
  790. // 通知会员发送信息绑定客服的id
  791. $noticeUser = [
  792. 'message_type' => 'connect',
  793. 'data' => [
  794. 'kf_id' => $res['data']['0'],
  795. 'kf_name' => $res['data']['1']
  796. ]
  797. ];
  798. Gateway::sendToClient($res['data']['3']['client_id'], json_encode($noticeUser, 256));
  799. unset($noticeUser);
  800. // 通知客服端绑定会员的信息
  801. $noticeKf = [
  802. 'message_type' => 'connect',
  803. 'data' => [
  804. 'user_info' => $res['data']['3']
  805. ]
  806. ];
  807. Gateway::sendToClient($res['data']['2'], json_encode($noticeKf, 256));
  808. unset($noticeKf);
  809. // 逐一通知
  810. $number = 1;
  811. foreach (self::$global->userList as $vo) {
  812. $waitMsg = '您前面还有 ' . $number . ' 位会员在等待。';
  813. $waitMessage = [
  814. 'message_type' => 'wait',
  815. 'data' => [
  816. 'content' => $waitMsg,
  817. ]
  818. ];
  819. Gateway::sendToClient($vo['client_id'], json_encode($waitMessage, 256));
  820. $number++;
  821. }
  822. unset($waitMessage, $number);
  823. // 写入接入值
  824. $key = date('Ymd') . 'success_in';
  825. self::$global->$key = 0;
  826. do {
  827. $oldKey = date('Ymd', strtotime('-1 day')); // 删除前一天的统计值
  828. unset(self::$global->$oldKey);
  829. } while (!self::$global->increment($key));
  830. unset($key);
  831. } else {
  832. switch ($res['code']) {
  833. case -1:
  834. $waitMsg = '暂时没有客服上班,请稍后再咨询。';
  835. // 逐一通知
  836. foreach (self::$global->userList as $vo) {
  837. $waitMessage = [
  838. 'message_type' => 'wait',
  839. 'data' => [
  840. 'content' => $waitMsg,
  841. ]
  842. ];
  843. Gateway::sendToClient($vo['client_id'], json_encode($waitMessage, 256));
  844. }
  845. break;
  846. case -2:
  847. break;
  848. case -3:
  849. break;
  850. case -4:
  851. // 逐一通知
  852. $number = 1;
  853. foreach (self::$global->userList as $vo) {
  854. $waitMsg = '您前面还有 ' . $number . ' 位会员在等待。';
  855. $waitMessage = [
  856. 'message_type' => 'wait',
  857. 'data' => [
  858. 'content' => $waitMsg,
  859. ]
  860. ];
  861. Gateway::sendToClient($vo['client_id'], json_encode($waitMessage, 256));
  862. $number++;
  863. }
  864. break;
  865. }
  866. unset($waitMessage, $number);
  867. }
  868. }
  869. /**
  870. * 有人进入执行分配
  871. * @param $client_id
  872. * @param $group
  873. * @param $uid
  874. */
  875. private static function userOnlineTask($client_id, $group, $uid = 0)
  876. {
  877. // TODO 此处查询最大的可服务人数,后面可以用其他的方式,存储这个数值,让其更高效的访问
  878. $maxNumber = self::getMaxServiceNum();
  879. $res = self::assignmentTask(self::$global->kfList, self::$global->userList, $group, $maxNumber, $uid);
  880. unset($maxNumber);
  881. if (1 == $res['code']) {
  882. while (!self::$global->cas('kfList', self::$global->kfList, $res['data']['4'])) {
  883. }; // 更新客服数据
  884. while (!self::$global->cas('userList', self::$global->userList, $res['data']['5'])) {
  885. }; // 更新会员数据
  886. $userToKf = self::$global->userToKf;
  887. $userToKf[$res['data']['3']['id']] = [
  888. $res['data']['3']['id'],
  889. $res['data']['0']
  890. ];
  891. self::$global->userToKf = $userToKf;
  892. // 服务信息入库
  893. $serviceLog = [
  894. 'user_id' => $res['data']['3']['id'],
  895. 'client_id' => $res['data']['3']['client_id'],
  896. 'user_name' => $res['data']['3']['name'],
  897. 'user_ip' => $res['data']['3']['ip'],
  898. 'user_avatar' => $res['data']['3']['avatar'],
  899. 'kf_id' => intval(ltrim($res['data']['0'], 'KF')),
  900. 'start_time' => time(),
  901. 'group_id' => $group,
  902. 'website' => $res['data']['3']['website'],
  903. 'system' => $res['data']['3']['system'],
  904. 'browse' => $res['data']['3']['browse'],
  905. 'status' => 1,
  906. 'end_time' => 0
  907. ];
  908. $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();
  909. if (!$hisSession) {
  910. $conversationId = self::$db->insert('ws_service_log')->cols($serviceLog)->query();
  911. } else {
  912. self::$db->update('ws_service_log')->cols(['status' => 1])->where('servicelog_id=' . $hisSession['servicelog_id'])->query();
  913. $conversationId = $hisSession['servicelog_id'];
  914. }
  915. unset($serviceLog);
  916. // 通知会员发送信息绑定客服的id
  917. $noticeUser = [
  918. 'message_type' => 'connect',
  919. 'data' => [
  920. 'kf_id' => $res['data']['0'],
  921. 'conversationId' => $conversationId,
  922. 'kf_name' => $res['data']['1']
  923. ]
  924. ];
  925. Gateway::sendToClient($client_id, json_encode($noticeUser, 256));
  926. unset($noticeUser);
  927. // 通知客服端绑定会员的信息
  928. $noticeKf = [
  929. 'message_type' => 'connect',
  930. 'data' => [
  931. 'user_info' => $res['data']['3'],
  932. 'conversationId' => $conversationId,
  933. ]
  934. ];
  935. Gateway::sendToClient($res['data']['2'], json_encode($noticeKf, 256));
  936. unset($noticeKf);
  937. // 写入接入值
  938. $key = date('Ymd') . 'success_in';
  939. self::$global->$key = 0;
  940. do {
  941. $oldKey = date('Ymd', strtotime('-1 day')); // 删除前一天的统计值
  942. unset(self::$global->$oldKey);
  943. } while (!self::$global->increment($key));
  944. unset($key);
  945. } else {
  946. $waitMsg = '';
  947. switch ($res['code']) {
  948. case -1:
  949. $waitMsg = '暂时没有客服上班,请稍后再咨询。';
  950. break;
  951. case -2:
  952. break;
  953. case -3:
  954. break;
  955. case -4:
  956. $number = count(self::$global->userList);
  957. $waitMsg = '您前面还有 ' . $number . ' 位会员在等待。';
  958. break;
  959. }
  960. $waitMessage = [
  961. 'message_type' => 'wait',
  962. 'data' => [
  963. 'content' => $waitMsg,
  964. ]
  965. ];
  966. Gateway::sendToClient($client_id, json_encode($waitMessage, 256));
  967. unset($waitMessage);
  968. }
  969. }
  970. /**
  971. * 给客服分配会员【均分策略】
  972. * @param $kfList
  973. * @param $userList
  974. * @param $group
  975. * @param $total
  976. */
  977. private static function assignmentTask($kfList, $userList, $group, $total, $uid = 0)
  978. {
  979. // 没有客服上线
  980. if (empty($kfList) || empty($kfList[$group])) {
  981. return ['code' => -1];
  982. }
  983. // 没有待分配的会员
  984. if (empty($userList)) {
  985. return ['code' => -2];
  986. }
  987. // 未设置每个客服可以服务多少人
  988. if (0 == $total) {
  989. return ['code' => -3];
  990. }
  991. // 查看该组的客服是否在线
  992. if (!isset($kfList[$group])) {
  993. return ['code' => -1];
  994. }
  995. //上次用户掉线后,还可以继续上一次 (如果没有关闭) 的会话 --1
  996. $odltalksession = false;
  997. $user = $user_first = array_shift($userList);
  998. if ($uid > 0 && $user['id'] != $uid && count($userList) > 1) {
  999. $timevalielimit = time() - 60 * 5;
  1000. $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();
  1001. if ($odltalksession) {
  1002. foreach ($userList as $ttkey => $ttval) {
  1003. if ($ttval['id'] == $uid) {
  1004. array_unshift($userList, $user);
  1005. $user = $userList[$ttkey];
  1006. unset($userList[$ttkey]);
  1007. break;
  1008. }
  1009. }
  1010. }
  1011. }
  1012. //上次用户掉线后,还可以继续上一次 (如果没有关闭) 的会话 --2
  1013. if ($odltalksession) {
  1014. $oldkrid = 'KF' . $odltalksession['kf_id'];
  1015. if (isset($kfList[$group][$oldkrid])) {
  1016. $kf = $kfList[$group][$oldkrid];
  1017. $min = $kf['task'];
  1018. $flag = $kf['id'];
  1019. unset($kfList[$group][$oldkrid]);
  1020. } else {
  1021. goto NOSIGNKF;
  1022. }
  1023. } else {
  1024. NOSIGNKF:
  1025. $kf = $kfList[$group];
  1026. $kf = array_shift($kf);
  1027. $min = $kf['task'];
  1028. $flag = $kf['id'];
  1029. foreach ($kfList[$group] as $key => $vo) {
  1030. if ($vo['task'] < $min) {
  1031. $min = $vo['task'];
  1032. $flag = $key;
  1033. }
  1034. }
  1035. unset($kf);
  1036. }
  1037. // 需要排队了
  1038. if ($kfList[$group][$flag]['task'] == $total) {
  1039. return ['code' => -4];
  1040. }
  1041. $kfList[$group][$flag]['task'] += 1;
  1042. array_push($kfList[$group][$flag]['user_info'], $user['client_id']); // 被分配的用户信息
  1043. return [
  1044. 'code' => 1,
  1045. 'data' => [
  1046. $kfList[$group][$flag]['id'],
  1047. $kfList[$group][$flag]['name'],
  1048. $kfList[$group][$flag]['client_id'],
  1049. $user,
  1050. $kfList,
  1051. $userList
  1052. ]
  1053. ];
  1054. }
  1055. /**
  1056. * 获取最大的服务人数
  1057. * @return int
  1058. */
  1059. private static function getMaxServiceNum()
  1060. {
  1061. $maxNumber = self::$db->query('select `max_service` from `ws_kf_config` where `id` = 1');
  1062. if (!empty($maxNumber)) {
  1063. $maxNumber = 5;
  1064. } else {
  1065. $maxNumber = $maxNumber['0']['max_service'];
  1066. }
  1067. return $maxNumber;
  1068. }
  1069. /**
  1070. * 将内存中的数据写入统计表
  1071. * @param int $flag
  1072. */
  1073. private static function writeLog($flag = 1)
  1074. {
  1075. // 上午 8点 到 22 点开始统计
  1076. if (date('H') < 8 || date('H') > 22) {
  1077. return;
  1078. }
  1079. // 当前正在接入的人 和 在线客服数
  1080. $kfList = self::$global->kfList;
  1081. $nowTalking = 0;
  1082. $onlineKf = 0;
  1083. if (!empty($kfList)) {
  1084. foreach ($kfList as $key => $vo) {
  1085. $onlineKf += count($vo);
  1086. foreach ($vo as $k => $v) {
  1087. $nowTalking += count($v['user_info']);
  1088. }
  1089. }
  1090. }
  1091. // 在队列中的用户
  1092. $inQueue = count(self::$global->userList);
  1093. $key = date('Ymd') . 'total_in';
  1094. $key2 = date('Ymd') . 'success_in';
  1095. $param = [
  1096. 'is_talking' => $nowTalking,
  1097. 'in_queue' => $inQueue,
  1098. 'online_kf' => $onlineKf,
  1099. 'success_in' => self::$global->$key2,
  1100. 'total_in' => self::$global->$key,
  1101. 'now_date' => date('Y-m-d')
  1102. ];
  1103. self::$db->update('ws_now_data')->cols($param)->where('id=1')->query();
  1104. if (2 == $flag) {
  1105. $param = [
  1106. 'is_talking' => $nowTalking,
  1107. 'in_queue' => $inQueue,
  1108. 'online_kf' => $onlineKf,
  1109. 'success_in' => self::$global->$key2,
  1110. 'total_in' => self::$global->$key,
  1111. 'add_date' => date('Y-m-d'),
  1112. 'add_hour' => date('H'),
  1113. 'add_minute' => date('i'),
  1114. ];
  1115. self::$db->insert('ws_service_data')->cols($param)->query();
  1116. }
  1117. unset($kfList, $nowTalking, $inQueue, $onlineKf, $key, $key2, $param);
  1118. }
  1119. /**
  1120. * 机器人问答
  1121. * @param $client_id 服务ID
  1122. * @param $message 数据
  1123. */
  1124. private static function toRobot($client_id, $message)
  1125. {
  1126. $groups_id = $message['data']['groups_id'];
  1127. $robot_name = $message['data']['robot_name'];
  1128. $robotgroups_id = $message['data']['robotgroups_id'];
  1129. // 查询问题.
  1130. $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 . "'");
  1131. $chat_message = [
  1132. 'message_type' => 'chatMessage',
  1133. 'data' => [
  1134. 'name' => '智能助手',
  1135. 'time' => date('H:i'),
  1136. 'content' => $getRobot ? htmlspecialchars($getRobot[0]['robot_content']) : 'error',
  1137. ]
  1138. ];
  1139. Gateway::sendToClient($client_id, json_encode($chat_message, 256));
  1140. }
  1141. /**
  1142. * 评价
  1143. * @param $client_id 服务ID
  1144. * @param $message 数据
  1145. */
  1146. private static function evaluate($client_id, $message)
  1147. {
  1148. // 修改数据库.
  1149. $evaluate_id = $message['data']['evaluate_id'];
  1150. $result = self::$db->query("UPDATE `ws_service_log` SET `evaluate_id` = '" . $evaluate_id . "' WHERE `client_id`='" . $client_id . "'");
  1151. if ($result) {
  1152. $chat_message = [
  1153. 'message_type' => 'evaluate',
  1154. 'data' => [
  1155. 'status' => 1,
  1156. 'time' => date('H:i'),
  1157. ]
  1158. ];
  1159. } else {
  1160. $chat_message = [
  1161. 'message_type' => 'evaluate',
  1162. 'data' => [
  1163. 'status' => 2,
  1164. 'time' => date('H:i'),
  1165. ]
  1166. ];
  1167. }
  1168. Gateway::sendToClient($client_id, json_encode($chat_message));
  1169. }
  1170. //踢掉同一用户的旧用户
  1171. private static function tickOlduser($uid)
  1172. {
  1173. }
  1174. }