Events.php 55 KB

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