Events.php 54 KB

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