Events.php 56 KB

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