Events.php 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155
  1. <?php
  2. /**
  3. * This file is part of workerman.
  4. *
  5. * Licensed under The MIT License
  6. * For full copyright and license information, please see the MIT-LICENSE.txt
  7. * Redistributions of files must retain the above copyright notice.
  8. *
  9. * @author walkor<walkor@workerman.net>
  10. * @copyright walkor<walkor@workerman.net>
  11. * @link http://www.workerman.net/
  12. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  13. */
  14. /**
  15. * 用于检测业务代码死循环或者长时间阻塞等问题
  16. * 如果发现业务卡死,可以将下面declare打开(去掉//注释),并执行php start.php reload
  17. * 然后观察一段时间workerman.log看是否有process_timeout异常
  18. */
  19. //declare(ticks=1);
  20. use \GatewayWorker\Lib\Gateway;
  21. use Workerman\Lib\Timer;
  22. /**
  23. * 主逻辑
  24. * 主要是处理 onConnect onMessage onClose 三个方法
  25. * onConnect 和 onClose 如果不需要可以不用实现并删除
  26. */
  27. class Events
  28. {
  29. /**
  30. * 新建一个类的静态成员,用来保存数据库实例
  31. */
  32. public static $db = null;
  33. public static $global = null;
  34. /**
  35. * 进程启动后初始化数据库连接
  36. */
  37. public static function onWorkerStart($worker)
  38. {
  39. if (empty(self::$db)) {
  40. self::$db = new \Workerman\MySQL\Connection('192.168.2.186', '3306', 'root', '', 'customer_service');
  41. }
  42. if (empty(self::$global)) {
  43. self::$global = new \GlobalData\Client('127.0.0.1:2207');
  44. // 客服列表
  45. if (is_null(self::$global->kfList)) {
  46. self::$global->kfList = [];
  47. }
  48. // 会员列表[动态的,这里面只是目前未被分配的会员信息]
  49. if (is_null(self::$global->userList)) {
  50. self::$global->userList = [];
  51. }
  52. // 会员以 uid 为key的信息简表,只有在用户退出的时候,才去执行修改
  53. if (is_null(self::$global->uidSimpleList)) {
  54. self::$global->uidSimpleList = [];
  55. }
  56. // 当天的累积接入值
  57. $key = date('Ymd') . 'total_in';
  58. if (is_null(self::$global->$key)) {
  59. self::$global->$key = 0;
  60. $oldKey = date('Ymd', strtotime('-1 day')); // 删除前一天的统计值
  61. unset(self::$global->$oldKey);
  62. unset($oldKey, $key);
  63. }
  64. // 成功接入值
  65. $key = date('Ymd') . 'success_in';
  66. if (is_null(self::$global->$key)) {
  67. self::$global->$key = 0;
  68. $oldKey = date('Ymd', strtotime('-1 day')); // 删除前一天的统计值
  69. unset(self::$global->$oldKey);
  70. unset($oldKey, $key);
  71. }
  72. }
  73. // 定时统计数据
  74. if (0 === $worker->id) {
  75. // 1分钟统计一次实时数据
  76. Timer::add(60 * 1, function () {
  77. self::writeLog(1);
  78. });
  79. // 40分钟写一次当前日期点数的log数据
  80. Timer::add(60 * 40, function () {
  81. self::writeLog(2);
  82. });
  83. }
  84. }
  85. /**
  86. * 当客户端连接时触发
  87. * 如果业务不需此回调可以删除onConnect
  88. *
  89. * @param int $client_id 连接id
  90. */
  91. public static function onConnect($client_id)
  92. {
  93. // 检测是否开启自动应答
  94. $sayHello = self::$db->query('select `word`,`status` from `ws_reply` where `id` = 1');
  95. if (!empty($sayHello) && 1 == $sayHello['0']['status']) {
  96. $hello = [
  97. 'message_type' => 'helloMessage',
  98. 'data' => [
  99. 'name' => '智能助手',
  100. 'time' => date('H:i'),
  101. 'content' => htmlspecialchars($sayHello['0']['word'])
  102. ]
  103. ];
  104. Gateway::sendToClient($client_id, json_encode($hello, 256));
  105. unset($hello);
  106. }
  107. unset($sayHello);
  108. }
  109. /**
  110. * 当客户端发来消息时触发
  111. * @param int $client_id 连接id
  112. * @param mixed $message 具体消息
  113. */
  114. public static function onMessage($client_id, $message)
  115. {
  116. if ($message == '{"type":"ping"}') {
  117. Gateway::sendToCurrentClient('{"type":"pong"}');
  118. return;
  119. } else {
  120. echo "onMessage: " . $message . "\r\n";
  121. print_r([self::$global->kfList, self::$global->userList, self::$global->uidSimpleList, self::$global->userToKf]);
  122. }
  123. $message = json_decode($message, true);
  124. switch ($message['type']) {
  125. // 客服初始化
  126. case 'init':
  127. self::Kfinit($client_id, $message);
  128. break;
  129. // 顾客初始化
  130. case 'userInit';
  131. self::userInitEnt($client_id, $message);
  132. break;
  133. // 聊天
  134. case 'chatMessage':
  135. $client = Gateway::getClientIdByUid($message['data']['to_id']);
  136. if (!empty($client)) {
  137. $chat_message = [
  138. 'message_type' => 'chatMessage',
  139. 'data' => [
  140. 'name' => $message['data']['from_name'],
  141. 'avatar' => $message['data']['from_avatar'],
  142. 'id' => $message['data']['from_id'],
  143. 'time' => date('H:i'),
  144. 'content' => htmlspecialchars($message['data']['content']),
  145. ]
  146. ];
  147. Gateway::sendToClient($client['0'], json_encode($chat_message));
  148. unset($chat_message);
  149. // 聊天信息入库
  150. $serviceLog = [
  151. 'from_id' => $message['data']['from_id'],
  152. 'from_name' => $message['data']['from_name'],
  153. 'from_avatar' => $message['data']['from_avatar'],
  154. 'to_id' => $message['data']['to_id'],
  155. 'to_name' => $message['data']['to_name'],
  156. 'content' => $message['data']['content'],
  157. 'servicelog_id' => $message['data']['conversationId'],
  158. 'time_line' => time()
  159. ];
  160. self::$db->insert('ws_chat_log')->cols($serviceLog)->query();
  161. unset($serviceLog);
  162. }
  163. break;
  164. // 转接
  165. case 'changeGroup':
  166. // 通知客户端转接中
  167. $simpleList = self::$global->uidSimpleList;
  168. if (!isset($simpleList[$message['uid']])) { // 客户已经退出
  169. return;
  170. }
  171. $userClient = $simpleList[$message['uid']]['0'];
  172. $userGroup = $simpleList[$message['uid']]['1']; // 会员原来的分组也是客服的分组
  173. $reLink = [
  174. 'message_type' => 'relinkMessage'
  175. ];
  176. Gateway::sendToClient($userClient, json_encode($reLink));
  177. unset($reLink);
  178. // 记录该客服与该会员的服务结束
  179. self::$db->query("update `ws_service_log` set `end_time` = " . time() . " , `status` = '2' where `client_id`= '" . $userClient . "'");
  180. // 从当前客服的服务表中删除这个会员
  181. $old = $kfList = self::$global->kfList;
  182. if (!isset($kfList[$userGroup])) {
  183. $waitMsg = '暂时没有相关客服上班,请稍后再咨询。';
  184. // 逐一通知
  185. foreach (self::$global->userList as $vo) {
  186. $waitMessage = [
  187. 'message_type' => 'wait',
  188. 'data' => [
  189. 'content' => $waitMsg,
  190. ]
  191. ];
  192. Gateway::sendToClient($userClient, json_encode($waitMessage, 256));
  193. unset($waitMessage);
  194. }
  195. return;
  196. }
  197. $myList = $kfList[$userGroup]; // 该客服分组数组
  198. foreach ($myList as $key => $vo) {
  199. if (in_array($userClient, $vo['user_info'])) {
  200. // 维护现在的该客服的服务信息
  201. $kfList[$userGroup][$key]['task'] -= 1; // 当前服务的人数 -1
  202. foreach ($vo['user_info'] as $k => $v) {
  203. if ($userClient == $v) {
  204. unset($kfList[$userGroup][$key]['user_info'][$k]);
  205. break;
  206. }
  207. }
  208. break;
  209. }
  210. }
  211. while (!self::$global->cas('kfList', $old, $kfList)) {
  212. }; // 刷新内存中客服的服务列表
  213. unset($old, $kfList, $myList);
  214. // 将会员加入队列中
  215. $userList = self::$global->userList;
  216. do {
  217. $NewUserList = $userList;
  218. $NewUserList[$message['uid']] = [
  219. 'id' => $message['uid'],
  220. 'name' => $message['name'],
  221. 'avatar' => $message['avatar'],
  222. 'ip' => $message['ip'],
  223. 'group' => $message['group'], // 指定要链接的分组
  224. 'client_id' => $userClient
  225. ];
  226. } while (!self::$global->cas('userList', $userList, $NewUserList));
  227. unset($NewUserList, $userList);
  228. // 执行会员分配通知双方
  229. self::userOnlineTask($userClient, $message['group']);
  230. unset($userClient, $userGroup);
  231. break;
  232. case 'closeUser':
  233. $userInfo = self::$global->uidSimpleList;
  234. if (isset($userInfo[$message['uid']])) {
  235. $waitMessage = [
  236. 'message_type' => 'wait',
  237. 'data' => [
  238. 'content' => '暂时没有客服上班,请稍后再咨询。',
  239. ]
  240. ];
  241. Gateway::sendToClient($userInfo[$message['uid']]['0'], json_encode($waitMessage, 256));
  242. unset($waitMessage);
  243. }
  244. unset($userInfo);
  245. break;
  246. // 机器人问答.
  247. case 'toRobot':
  248. self::toRobot($client_id, $message);
  249. break;
  250. // 评价.
  251. case 'evaluate':
  252. self::evaluate($client_id, $message);
  253. break;
  254. // 客服关闭会话.
  255. case 'kfCloseUser':
  256. $client = Gateway::getClientIdByUid($message['data']['to_id']);
  257. if (!empty($client)) {
  258. self::serverClose($client['0']);
  259. }
  260. break;
  261. // default:
  262. // Gateway::closeClient($client_id);
  263. }
  264. }
  265. //客服接入sock,及初始化
  266. public static function Kfinit($client_id, $message){
  267. $kfList = self::$global->kfList;
  268. //客服登陆验证 不符合的直接断掉
  269. $logcheck = true ; //开发时使用
  270. //$logcheck = self::KfloginChedk($client_id, $message);
  271. if (!$logcheck) {
  272. Gateway::closeCurrentClient();
  273. return true;
  274. }
  275. // 如果该客服未在内存中记录则记录
  276. if (!isset($kfList[$message['group']]) || !array_key_exists($message['uid'], $kfList[$message['group']])) {
  277. do {
  278. $newKfList = $kfList;
  279. $newKfList[$message['group']][$message['uid']] = [
  280. 'id' => $message['uid'],
  281. 'name' => $message['name'],
  282. 'avatar' => $message['avatar'],
  283. 'client_id' => $client_id,
  284. 'task' => 0,
  285. 'user_info' => []
  286. ];
  287. } while (!self::$global->cas('kfList', $kfList, $newKfList));
  288. unset($newKfList, $kfList);
  289. } else if (isset($kfList[$message['group']][$message['uid']])) {
  290. do {
  291. $newKfList = $kfList;
  292. $newKfList[$message['group']][$message['uid']]['client_id'] = $client_id;
  293. } while (!self::$global->cas('kfList', $kfList, $newKfList));
  294. unset($newKfList, $kfList);
  295. }
  296. // 绑定 client_id 和 uid
  297. Gateway::bindUid($client_id, $message['uid']);
  298. $_SESSION['group'] = $message['group'];
  299. $_SESSION['iskefu'] = 1;
  300. $_SESSION['uid'] = $message['uid'];
  301. // TODO 尝试拉取用户来服务 [二期规划]
  302. }
  303. //客服登陆验证
  304. public static function KfloginChedk($client, $messageArray)
  305. {
  306. $uid = isset($messageArray['uid']) ? ($messageArray['uid']) : '';
  307. $token = isset($messageArray['token']) ?   ($messageArray['token']) : '';
  308. if (empty($uid) || empty($token)) {
  309. return false;
  310. }
  311. $expire_time_vali = time() - 60 * 60 * 24 * 3;
  312. $kfid = intval(substr($uid, 2));
  313. $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();
  314. if ($ret) {
  315. self::$db->update('ws_users')->cols(array('online_status'=>1,'online_connectid'=>$client))->where('id='.$kfid)->query();
  316. return $ret;
  317. }
  318. return false;
  319. }
  320. //用户发送邦定用户事件
  321. public static function userInitEnt($client_id, $message)
  322. {
  323. $userList = self::$global->userList;
  324. // 如果该顾客未在内存中记录则记录
  325. $uidSimpleList = self::$global->uidSimpleList;
  326. if (isset($uidSimpleList[$message['uid']])) {
  327. $uidSimpleList = self::$global->uidSimpleList;
  328. $oldclientid = $uidSimpleList[$message['uid']]['0'];
  329. Gateway::sendToClient($oldclientid, json_encode(['type' => 'reLoginErr', 'msg' => '相同账号登陆,本次退出'], 256));
  330. Gateway::closeClient($oldclientid);
  331. sleep(2);
  332. }
  333. if (!array_key_exists($message['uid'], $userList)) {
  334. do {
  335. $NewUserList = $userList;
  336. $NewUserList[$message['uid']] = [
  337. 'id' => $message['uid'],
  338. 'name' => $message['name'],
  339. 'avatar' => $message['avatar'],
  340. 'website' => $_SESSION['origin'],//$_SERVER['HTTP_ORIGIN'],
  341. 'browse' => Gateway::browse_info(),
  342. 'system' => Gateway::get_os(),
  343. 'ip' => isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '',
  344. 'group' => $message['group'],
  345. 'client_id' => $client_id
  346. ];
  347. } while (!self::$global->cas('userList', $userList, $NewUserList));
  348. unset($NewUserList, $userList);
  349. // 维护 UID对应的client_id 数组
  350. do {
  351. $old = $newList = self::$global->uidSimpleList;
  352. $newList[$message['uid']] = [
  353. $client_id,
  354. $message['group']
  355. ];
  356. } while (!self::$global->cas('uidSimpleList', $old, $newList));
  357. unset($old, $newList);
  358. // 写入接入值
  359. $key = date('Ymd') . 'total_in';
  360. self::$global->$key = 0;
  361. do {
  362. $oldKey = date('Ymd', strtotime('-1 day')); // 删除前一天的统计值
  363. unset(self::$global->$oldKey);
  364. } while (!self::$global->increment($key));
  365. unset($key);
  366. }
  367. // 绑定 client_id 和 uid
  368. Gateway::bindUid($client_id, $message['uid']);
  369. $_SESSION['iskefu'] = 0;
  370. $_SESSION['uid'] = $message['uid'];
  371. // 尝试分配新会员进入服务
  372. self::userOnlineTask($client_id, $message['group'], $message['uid']);
  373. }
  374. /**
  375. * 当用户断开连接时触发
  376. * @param int $client_id 连接id
  377. *
  378. * tips: 当服务端主动退出的时候,会出现 exit status 9.原因是:服务端主动断开之后,连接的客户端会走这个方法,而短时间内进程
  379. * 需要处理这多的逻辑,又有cas操作,导致进程退出会超时,然后会被内核杀死,从而报出错误 9.实际对真正的业务没有任何的影响。
  380. */
  381. public static function onClose($client_id)
  382. {
  383. $isKefuoff = isset($_SESSION['iskefu']) ? $_SESSION['iskefu'] : 0;
  384. $uid = isset($_SESSION['uid']) ? $_SESSION['uid'] : false;
  385. if (empty($uid)) {
  386. return;
  387. }
  388. if ($isKefuoff) {
  389. self::serviceOffline($client_id, $uid);
  390. } else {
  391. self::guestOffline($client_id, $uid);
  392. }
  393. return;
  394. }
  395. //客服下线了
  396. public static function serviceOffline($client_id, $uid)
  397. {
  398. $group = $_SESSION['group'];
  399. $kefuinfo_old = $kefuinfo_old_new = self::$global->kfList;
  400. $user_info = $kefuinfo_old_new[$group][$uid]['user_info'];
  401. $simpliUsers = self::$global->uidSimpleList;
  402. $simpliUsersID_UID_Arr = [];
  403. if (!empty($simpliUsers)) {
  404. foreach ($simpliUsers as $key => $val) {
  405. $simpliUsersID_UID_Arr[$val['0']] = $key;
  406. }
  407. }
  408. $now = time();
  409. if (!empty($user_info)) {
  410. foreach ($user_info as $val) {
  411. Gateway::sendToClient($val, json_encode(['type' => 'serviceoffline', 'msg' => '客户人员下线!'], 256));
  412. if (isset($simpliUsersID_UID_Arr[$val])) {
  413. 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 ");
  414. }
  415. Gateway::closeClient($val);
  416. }
  417. }
  418. unset($kefuinfo_old_new[$group][$uid]);
  419. $kfid = intval(substr($uid,2));
  420. self::$db->update('ws_users')->cols(array('online_status'=>0,'online_connectid'=>''))->where('id='.$kfid)->query();
  421. do {
  422. } while (!self::$global->cas('kfList', $kefuinfo_old, $kefuinfo_old_new));
  423. return;
  424. }
  425. //用户下线了
  426. public static function guestOffline($client_id, $uid)
  427. {
  428. $kfuid = -1;
  429. $krclient_id = 0;
  430. $kfgroup = -1;
  431. $userToKf = $userToKfNew = self::$global->userToKf;
  432. if (isset($userToKfNew[$uid])) {
  433. $kfuid = isset($userToKfNew[$uid]['1']) ? $userToKfNew[$uid]['1'] : -1;
  434. $krclient_id = isset(Gateway::getClientIdByUid($kfuid)['0']) ? Gateway::getClientIdByUid($kfuid)['0'] : 0;
  435. unset($userToKfNew[$uid]);
  436. do {
  437. } while (!self::$global->cas('userToKf', $userToKf, $userToKfNew));
  438. }
  439. $uidSimpleList = $uidSimpleListNew = self::$global->uidSimpleList;
  440. if (isset($uidSimpleListNew[$uid])) {
  441. $kfgroup = $uidSimpleListNew[$uid]['1'];
  442. unset($uidSimpleListNew[$uid]);
  443. do {
  444. } while (!self::$global->cas('uidSimpleList', $uidSimpleList, $uidSimpleListNew));
  445. }
  446. $userList = $userListNew = self::$global->userList;
  447. if (!empty($userList)) {
  448. $ischange = 0;
  449. foreach ($userList as $key => $val) {
  450. if ($val['id'] == $uid) {
  451. unset($userListNew[$key]);
  452. $ischange = 1;
  453. break;
  454. }
  455. }
  456. if ($ischange) {
  457. do {
  458. } while (!self::$global->cas('userList', $userList, $userListNew));
  459. }
  460. }
  461. if ($kfuid != -1 && $kfgroup != -1) {
  462. $kefuinfo_old = $kefuinfo_old_new = self::$global->kfList;
  463. $ischange_kf_list = 0;
  464. if (isset($kefuinfo_old[$kfgroup][$kfuid])) {
  465. $infos = $kefuinfo_old[$kfgroup][$kfuid]['user_info'];
  466. if ($infos) {
  467. if (is_array($infos)) {
  468. foreach ($infos as $key => $val) {
  469. if ($val == $client_id) {
  470. $ischange_kf_list = 1;
  471. unset($kefuinfo_old_new[$kfgroup][$kfuid]['user_info'][$key]);
  472. $kefuinfo_old_new[$kfgroup][$kfuid]['task'] = $kefuinfo_old_new[$kfgroup][$kfuid]['task'] - 1;
  473. }
  474. }
  475. }
  476. if ($ischange_kf_list) {
  477. do {
  478. } while (!self::$global->cas('kfList', $kefuinfo_old, $kefuinfo_old_new));
  479. $chat_message = [
  480. 'message_type' => 'userClose',
  481. 'data' => [
  482. 'content' => '用户连接已断开',
  483. 'time' => date('H:i'),
  484. ]
  485. ];
  486. $now = time();
  487. $kf__uid = substr($kfuid, 2);
  488. $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 ";
  489. //echo "客户退出:". $sql ."\n";
  490. self::$db->query($sql);
  491. Gateway::sendToClient($krclient_id, json_encode($chat_message, 256));
  492. }
  493. }
  494. }
  495. }
  496. }
  497. /**
  498. * 客服结束会话
  499. * @param int $client_id 连接id
  500. *
  501. * tips: 当服务端主动退出的时候,会出现 exit status 9.原因是:服务端主动断开之后,连接的客户端会走这个方法,而短时间内进程
  502. * 需要处理这多的逻辑,又有cas操作,导致进程退出会超时,然后会被内核杀死,从而报出错误 9.实际对真正的业务没有任何的影响。
  503. */
  504. public static function serverClose($client_id)
  505. {
  506. // 返回.
  507. $chat_message = [
  508. 'message_type' => 'closeBysever',
  509. 'data' => [
  510. 'content' => '客服停止了该会话',
  511. 'time' => date('H:i'),
  512. ]
  513. ];
  514. Gateway::sendToClient($client_id, json_encode($chat_message, 256));
  515. $isServiceUserOut = false;
  516. // 将会员服务信息,从客服的服务列表中移除
  517. $old = $kfList = self::$global->kfList;
  518. foreach ($kfList as $k => $v) {
  519. foreach ($v as $key => $vo) {
  520. if (in_array($client_id, $vo['user_info'])) {
  521. $isServiceUserOut = true;
  522. // 根据client id 去更新会话工单一些信息
  523. self::$db->query("update `ws_service_log` set `end_time` = " . time() . " , `status` = '2' where `client_id`= '" . $client_id . "'");
  524. // 从会员的内存表中检索出该会员的信息,并更新内存
  525. $oldSimple = $simpleList = self::$global->uidSimpleList;
  526. $outUser = [];
  527. foreach ($simpleList as $u => $c) {
  528. if ($c['0'] == $client_id) {
  529. $outUser[] = [
  530. 'user_id' => $u,
  531. 'group_id' => $c['1']
  532. ];
  533. unset($simpleList[$u]);
  534. break;
  535. }
  536. }
  537. while (!self::$global->cas('uidSimpleList', $oldSimple, $simpleList)) {
  538. };
  539. unset($oldSimple, $simpleList);
  540. $outUser = self::$db->query("select `user_id`,`group_id` from `ws_service_log` where `client_id`= '" . $client_id . "'");
  541. // 通知 客服删除退出的用户
  542. if (!empty($outUser)) {
  543. $del_message = [
  544. 'message_type' => 'delUser',
  545. 'data' => [
  546. 'id' => $outUser['0']['user_id']
  547. ]
  548. ];
  549. Gateway::sendToClient($vo['client_id'], json_encode($del_message, 256));
  550. unset($del_message);
  551. // 尝试分配新会员进入服务
  552. self::userOfflineTask($outUser['0']['group_id']);
  553. }
  554. unset($outUser);
  555. // 维护现在的该客服的服务信息
  556. $kfList[$k][$key]['task'] -= 1; // 当前服务的人数 -1
  557. foreach ($vo['user_info'] as $m => $l) {
  558. if ($client_id == $l) {
  559. unset($kfList[$k][$key]['user_info'][$m]);
  560. break;
  561. }
  562. }
  563. // 刷新内存中客服的服务列表
  564. while (!self::$global->cas('kfList', $old, $kfList)) {
  565. };
  566. unset($old, $kfList);
  567. break;
  568. }
  569. }
  570. if ($isServiceUserOut) break;
  571. }
  572. // 尝试从排队的用户中删除退出的客户端
  573. if (false == $isServiceUserOut) {
  574. $old = $userList = self::$global->userList;
  575. foreach (self::$global->userList as $key => $vo) {
  576. if ($client_id == $vo['client_id']) {
  577. $isServiceUserOut = true;
  578. unset($userList[$key]);
  579. break;
  580. }
  581. }
  582. while (!self::$global->cas('userList', $old, $userList)) {
  583. };
  584. // 从会员的内存表中检索出该会员的信息,并更新内存
  585. $oldSimple = $simpleList = self::$global->uidSimpleList;
  586. foreach ($simpleList as $u => $c) {
  587. if ($c['0'] == $client_id) {
  588. unset($simpleList[$u]);
  589. break;
  590. }
  591. }
  592. while (!self::$global->cas('uidSimpleList', $oldSimple, $simpleList)) {
  593. };
  594. unset($oldSimple, $simpleList);
  595. }
  596. // 尝试是否是客服退出
  597. if (false == $isServiceUserOut) {
  598. $old = $kfList = self::$global->kfList;
  599. foreach (self::$global->kfList as $k => $v) {
  600. foreach ($v as $key => $vo) {
  601. // 客服服务列表中无数据,才去删除客服内存信息
  602. if ($client_id == $vo['client_id'] && (0 == count($vo['user_info']))) {
  603. unset($kfList[$k][$key]);
  604. break;
  605. }
  606. }
  607. }
  608. while (!self::$global->cas('kfList', $old, $kfList)) {
  609. };
  610. }
  611. }
  612. /**
  613. * 有人退出
  614. * @param $group
  615. */
  616. private static function userOfflineTask($group)
  617. {
  618. // TODO 此处查询最大的可服务人数,后面可以用其他的方式,存储这个数值,让其更高效的访问
  619. $maxNumber = self::getMaxServiceNum();
  620. $res = self::assignmentTask(self::$global->kfList, self::$global->userList, $group, $maxNumber);
  621. unset($maxNumber);
  622. if (1 == $res['code']) {
  623. while (!self::$global->cas('kfList', self::$global->kfList, $res['data']['4'])) {
  624. }; // 更新客服数据
  625. while (!self::$global->cas('userList', self::$global->userList, $res['data']['5'])) {
  626. }; // 更新会员数据
  627. // 通知会员发送信息绑定客服的id
  628. $noticeUser = [
  629. 'message_type' => 'connect',
  630. 'data' => [
  631. 'kf_id' => $res['data']['0'],
  632. 'kf_name' => $res['data']['1']
  633. ]
  634. ];
  635. Gateway::sendToClient($res['data']['3']['client_id'], json_encode($noticeUser, 256));
  636. unset($noticeUser);
  637. // 通知客服端绑定会员的信息
  638. $noticeKf = [
  639. 'message_type' => 'connect',
  640. 'data' => [
  641. 'user_info' => $res['data']['3']
  642. ]
  643. ];
  644. Gateway::sendToClient($res['data']['2'], json_encode($noticeKf, 256));
  645. unset($noticeKf);
  646. // 逐一通知
  647. $number = 1;
  648. foreach (self::$global->userList as $vo) {
  649. $waitMsg = '您前面还有 ' . $number . ' 位会员在等待。';
  650. $waitMessage = [
  651. 'message_type' => 'wait',
  652. 'data' => [
  653. 'content' => $waitMsg,
  654. ]
  655. ];
  656. Gateway::sendToClient($vo['client_id'], json_encode($waitMessage, 256));
  657. $number++;
  658. }
  659. unset($waitMessage, $number);
  660. // 写入接入值
  661. $key = date('Ymd') . 'success_in';
  662. self::$global->$key = 0;
  663. do {
  664. $oldKey = date('Ymd', strtotime('-1 day')); // 删除前一天的统计值
  665. unset(self::$global->$oldKey);
  666. } while (!self::$global->increment($key));
  667. unset($key);
  668. } else {
  669. switch ($res['code']) {
  670. case -1:
  671. $waitMsg = '暂时没有客服上班,请稍后再咨询。';
  672. // 逐一通知
  673. foreach (self::$global->userList as $vo) {
  674. $waitMessage = [
  675. 'message_type' => 'wait',
  676. 'data' => [
  677. 'content' => $waitMsg,
  678. ]
  679. ];
  680. Gateway::sendToClient($vo['client_id'], json_encode($waitMessage, 256));
  681. }
  682. break;
  683. case -2:
  684. break;
  685. case -3:
  686. break;
  687. case -4:
  688. // 逐一通知
  689. $number = 1;
  690. foreach (self::$global->userList as $vo) {
  691. $waitMsg = '您前面还有 ' . $number . ' 位会员在等待。';
  692. $waitMessage = [
  693. 'message_type' => 'wait',
  694. 'data' => [
  695. 'content' => $waitMsg,
  696. ]
  697. ];
  698. Gateway::sendToClient($vo['client_id'], json_encode($waitMessage, 256));
  699. $number++;
  700. }
  701. break;
  702. }
  703. unset($waitMessage, $number);
  704. }
  705. }
  706. /**
  707. * 有人进入执行分配
  708. * @param $client_id
  709. * @param $group
  710. * @param $uid
  711. */
  712. private static function userOnlineTask($client_id, $group, $uid = 0)
  713. {
  714. // TODO 此处查询最大的可服务人数,后面可以用其他的方式,存储这个数值,让其更高效的访问
  715. $maxNumber = self::getMaxServiceNum();
  716. $res = self::assignmentTask(self::$global->kfList, self::$global->userList, $group, $maxNumber, $uid);
  717. unset($maxNumber);
  718. if (1 == $res['code']) {
  719. while (!self::$global->cas('kfList', self::$global->kfList, $res['data']['4'])) {
  720. }; // 更新客服数据
  721. while (!self::$global->cas('userList', self::$global->userList, $res['data']['5'])) {
  722. }; // 更新会员数据
  723. $userToKf = self::$global->userToKf;
  724. $userToKf[$res['data']['3']['id']] = [
  725. $res['data']['3']['id'],
  726. $res['data']['0']
  727. ];
  728. self::$global->userToKf = $userToKf;
  729. // 服务信息入库
  730. $serviceLog = [
  731. 'user_id' => $res['data']['3']['id'],
  732. 'client_id' => $res['data']['3']['client_id'],
  733. 'user_name' => $res['data']['3']['name'],
  734. 'user_ip' => $res['data']['3']['ip'],
  735. 'user_avatar' => $res['data']['3']['avatar'],
  736. 'kf_id' => intval(ltrim($res['data']['0'], 'KF')),
  737. 'start_time' => time(),
  738. 'group_id' => $group,
  739. 'website' => $res['data']['3']['website'],
  740. 'system' => $res['data']['3']['system'],
  741. 'browse' => $res['data']['3']['browse'],
  742. 'status' => 1,
  743. 'end_time' => 0
  744. ];
  745. $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();
  746. if (!$hisSession) {
  747. $conversationId = self::$db->insert('ws_service_log')->cols($serviceLog)->query();
  748. } else {
  749. self::$db->update('ws_service_log')->cols(['status' => 1])->where('servicelog_id=' . $hisSession['servicelog_id'])->query();
  750. $conversationId = $hisSession['servicelog_id'];
  751. }
  752. unset($serviceLog);
  753. // 通知会员发送信息绑定客服的id
  754. $noticeUser = [
  755. 'message_type' => 'connect',
  756. 'data' => [
  757. 'kf_id' => $res['data']['0'],
  758. 'conversationId' => $conversationId,
  759. 'kf_name' => $res['data']['1']
  760. ]
  761. ];
  762. Gateway::sendToClient($client_id, json_encode($noticeUser, 256));
  763. unset($noticeUser);
  764. // 通知客服端绑定会员的信息
  765. $noticeKf = [
  766. 'message_type' => 'connect',
  767. 'data' => [
  768. 'user_info' => $res['data']['3'],
  769. 'conversationId' => $conversationId,
  770. ]
  771. ];
  772. Gateway::sendToClient($res['data']['2'], json_encode($noticeKf, 256));
  773. unset($noticeKf);
  774. // 写入接入值
  775. $key = date('Ymd') . 'success_in';
  776. self::$global->$key = 0;
  777. do {
  778. $oldKey = date('Ymd', strtotime('-1 day')); // 删除前一天的统计值
  779. unset(self::$global->$oldKey);
  780. } while (!self::$global->increment($key));
  781. unset($key);
  782. } else {
  783. $waitMsg = '';
  784. switch ($res['code']) {
  785. case -1:
  786. $waitMsg = '暂时没有客服上班,请稍后再咨询。';
  787. break;
  788. case -2:
  789. break;
  790. case -3:
  791. break;
  792. case -4:
  793. $number = count(self::$global->userList);
  794. $waitMsg = '您前面还有 ' . $number . ' 位会员在等待。';
  795. break;
  796. }
  797. $waitMessage = [
  798. 'message_type' => 'wait',
  799. 'data' => [
  800. 'content' => $waitMsg,
  801. ]
  802. ];
  803. Gateway::sendToClient($client_id, json_encode($waitMessage, 256));
  804. unset($waitMessage);
  805. }
  806. }
  807. /**
  808. * 给客服分配会员【均分策略】
  809. * @param $kfList
  810. * @param $userList
  811. * @param $group
  812. * @param $total
  813. */
  814. private static function assignmentTask($kfList, $userList, $group, $total, $uid = 0)
  815. {
  816. // 没有客服上线
  817. if (empty($kfList) || empty($kfList[$group])) {
  818. return ['code' => -1];
  819. }
  820. // 没有待分配的会员
  821. if (empty($userList)) {
  822. return ['code' => -2];
  823. }
  824. // 未设置每个客服可以服务多少人
  825. if (0 == $total) {
  826. return ['code' => -3];
  827. }
  828. // 查看该组的客服是否在线
  829. if (!isset($kfList[$group])) {
  830. return ['code' => -1];
  831. }
  832. //上次用户掉线后,还可以继续上一次 (如果没有关闭) 的会话 --1
  833. $odltalksession = false;
  834. $user = $user_first = array_shift($userList);
  835. if ($uid > 0 && $user['id'] != $uid && count($userList) > 1) {
  836. $timevalielimit = time() - 60 * 5;
  837. $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();
  838. if ($odltalksession) {
  839. foreach ($userList as $ttkey => $ttval) {
  840. if ($ttval['id'] == $uid) {
  841. array_unshift($userList, $user);
  842. $user = $userList[$ttkey];
  843. unset($userList[$ttkey]);
  844. break;
  845. }
  846. }
  847. }
  848. }
  849. //上次用户掉线后,还可以继续上一次 (如果没有关闭) 的会话 --2
  850. if ($odltalksession) {
  851. $oldkrid = 'KF' . $odltalksession['kf_id'];
  852. if (isset($kfList[$group][$oldkrid])) {
  853. $kf = $kfList[$group][$oldkrid];
  854. $min = $kf['task'];
  855. $flag = $kf['id'];
  856. unset($kfList[$group][$oldkrid]);
  857. } else {
  858. goto NOSIGNKF;
  859. }
  860. } else {
  861. NOSIGNKF:
  862. $kf = $kfList[$group];
  863. $kf = array_shift($kf);
  864. $min = $kf['task'];
  865. $flag = $kf['id'];
  866. foreach ($kfList[$group] as $key => $vo) {
  867. if ($vo['task'] < $min) {
  868. $min = $vo['task'];
  869. $flag = $key;
  870. }
  871. }
  872. unset($kf);
  873. }
  874. // 需要排队了
  875. if ($kfList[$group][$flag]['task'] == $total) {
  876. return ['code' => -4];
  877. }
  878. $kfList[$group][$flag]['task'] += 1;
  879. array_push($kfList[$group][$flag]['user_info'], $user['client_id']); // 被分配的用户信息
  880. return [
  881. 'code' => 1,
  882. 'data' => [
  883. $kfList[$group][$flag]['id'],
  884. $kfList[$group][$flag]['name'],
  885. $kfList[$group][$flag]['client_id'],
  886. $user,
  887. $kfList,
  888. $userList
  889. ]
  890. ];
  891. }
  892. /**
  893. * 获取最大的服务人数
  894. * @return int
  895. */
  896. private static function getMaxServiceNum()
  897. {
  898. $maxNumber = self::$db->query('select `max_service` from `ws_kf_config` where `id` = 1');
  899. if (!empty($maxNumber)) {
  900. $maxNumber = 5;
  901. } else {
  902. $maxNumber = $maxNumber['0']['max_service'];
  903. }
  904. return $maxNumber;
  905. }
  906. /**
  907. * 将内存中的数据写入统计表
  908. * @param int $flag
  909. */
  910. private static function writeLog($flag = 1)
  911. {
  912. // 上午 8点 到 22 点开始统计
  913. if (date('H') < 8 || date('H') > 22) {
  914. return;
  915. }
  916. // 当前正在接入的人 和 在线客服数
  917. $kfList = self::$global->kfList;
  918. $nowTalking = 0;
  919. $onlineKf = 0;
  920. if (!empty($kfList)) {
  921. foreach ($kfList as $key => $vo) {
  922. $onlineKf += count($vo);
  923. foreach ($vo as $k => $v) {
  924. $nowTalking += count($v['user_info']);
  925. }
  926. }
  927. }
  928. // 在队列中的用户
  929. $inQueue = count(self::$global->userList);
  930. $key = date('Ymd') . 'total_in';
  931. $key2 = date('Ymd') . 'success_in';
  932. $param = [
  933. 'is_talking' => $nowTalking,
  934. 'in_queue' => $inQueue,
  935. 'online_kf' => $onlineKf,
  936. 'success_in' => self::$global->$key2,
  937. 'total_in' => self::$global->$key,
  938. 'now_date' => date('Y-m-d')
  939. ];
  940. self::$db->update('ws_now_data')->cols($param)->where('id=1')->query();
  941. if (2 == $flag) {
  942. $param = [
  943. 'is_talking' => $nowTalking,
  944. 'in_queue' => $inQueue,
  945. 'online_kf' => $onlineKf,
  946. 'success_in' => self::$global->$key2,
  947. 'total_in' => self::$global->$key,
  948. 'add_date' => date('Y-m-d'),
  949. 'add_hour' => date('H'),
  950. 'add_minute' => date('i'),
  951. ];
  952. self::$db->insert('ws_service_data')->cols($param)->query();
  953. }
  954. unset($kfList, $nowTalking, $inQueue, $onlineKf, $key, $key2, $param);
  955. }
  956. /**
  957. * 机器人问答
  958. * @param $client_id 服务ID
  959. * @param $message 数据
  960. */
  961. private static function toRobot($client_id, $message)
  962. {
  963. $groups_id = $message['data']['groups_id'];
  964. $robot_name = $message['data']['robot_name'];
  965. $robotgroups_id = $message['data']['robotgroups_id'];
  966. // 查询问题.
  967. $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 . "'");
  968. $chat_message = [
  969. 'message_type' => 'chatMessage',
  970. 'data' => [
  971. 'name' => '智能助手',
  972. 'time' => date('H:i'),
  973. 'content' => $getRobot ? htmlspecialchars($getRobot[0]['robot_content']) : 'error',
  974. ]
  975. ];
  976. Gateway::sendToClient($client_id, json_encode($chat_message, 256));
  977. }
  978. /**
  979. * 评价
  980. * @param $client_id 服务ID
  981. * @param $message 数据
  982. */
  983. private static function evaluate($client_id, $message)
  984. {
  985. // 修改数据库.
  986. $evaluate_id = $message['data']['evaluate_id'];
  987. $result = self::$db->query("UPDATE `ws_service_log` SET `evaluate_id` = '" . $evaluate_id . "' WHERE `client_id`='" . $client_id . "'");
  988. if ($result) {
  989. $chat_message = [
  990. 'message_type' => 'evaluate',
  991. 'data' => [
  992. 'status' => 1,
  993. 'time' => date('H:i'),
  994. ]
  995. ];
  996. } else {
  997. $chat_message = [
  998. 'message_type' => 'evaluate',
  999. 'data' => [
  1000. 'status' => 2,
  1001. 'time' => date('H:i'),
  1002. ]
  1003. ];
  1004. }
  1005. Gateway::sendToClient($client_id, json_encode($chat_message));
  1006. }
  1007. //踢掉同一用户的旧用户
  1008. private static function tickOlduser($uid)
  1009. {
  1010. }
  1011. }