Events.php 60 KB

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