Events.php 63 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752
  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. use Workerman\Worker;
  23. /**
  24. * 主逻辑
  25. * 主要是处理 onConnect onMessage onClose 三个方法
  26. * onConnect 和 onClose 如果不需要可以不用实现并删除
  27. */
  28. class Events
  29. {
  30. /**
  31. * 新建一个类的静态成员,用来保存数据库实例
  32. */
  33. public static $db = null;
  34. public static $global = null;
  35. public static $redis = null;
  36. public static $logic = null;
  37. const KFINFOKEY = 'KFINFO'; //客服信息hash表
  38. const USERINFOKEY = 'USERINFO'; //用户信息hash表
  39. const USERLIST = 'USERLIST'; //用户排队表
  40. const SERVICELOG = 'SERVICELOG'; //工单信息
  41. const WEBSOCKALLUSER = 'WEBSOCKALLUSER'; //所有连接
  42. /**
  43. * 进程启动后初始化数据库连接
  44. */
  45. public static function onWorkerStart($worker)
  46. {
  47. include_once(__DIR__ . DIRECTORY_SEPARATOR . "Mlogic.php");
  48. self::$logic = Mlogic::GetInstance();
  49. self::$db = self::$logic->getDb();
  50. self::$redis = self::$logic->getRedis();
  51. self::$global = self::$logic->getGlbData();
  52. self::TimerThing($worker);
  53. }
  54. /**
  55. * 每分钟定时向客服发送一次排队情况
  56. */
  57. public static function lineup()
  58. {
  59. $group = self::$global->groupmap;
  60. foreach ($group as $groupid => $gname) {
  61. $users = self::getUselistData($groupid);
  62. if (!empty($users)) {
  63. Gateway::sendToGroup('group_' . $groupid, json_encode(['type' => 'lineupCount', count($users)], 256));
  64. }
  65. }
  66. }
  67. /**
  68. * 当客户端连接时触发
  69. * 如果业务不需此回调可以删除onConnect
  70. *
  71. * @param int $client_id 连接id
  72. */
  73. public static function onConnect($client_id)
  74. {
  75. // 检测是否开启自动应答
  76. $sayHello = self::$global->replay['1'];
  77. if (!empty($sayHello) && 1 == $sayHello['status']) {
  78. $hello = [
  79. 'message_type' => 'helloMessage',
  80. 'data' => [
  81. 'name' => '智能助手',
  82. 'time' => date('H:i'),
  83. 'content' => $sayHello['word']
  84. ]
  85. ];
  86. Gateway::sendToClient($client_id, json_encode($hello, 256));
  87. unset($hello);
  88. }
  89. unset($sayHello);
  90. // 检测是否开启广告
  91. $advertisement = self::$db->query('select * from `ws_advertisement` where `advertisement_status` = 1');
  92. if (!empty($advertisement)) {
  93. $chat_message = [
  94. 'message_type' => 'advertisement',
  95. 'data' => $advertisement
  96. ];
  97. Gateway::sendToClient($client_id, json_encode($chat_message, 256));
  98. unset($chat_message);
  99. }
  100. unset($advertisement);
  101. self::$redis->hset(self::WEBSOCKALLUSER, $client_id, json_encode(array_merge($_SERVER, ['time' => date('H:i:s')])));
  102. }
  103. /**
  104. * 当客户端发来消息时触发
  105. * @param int $client_id 连接id
  106. * @param mixed $message 具体消息
  107. */
  108. public static function onMessage($client_id, $message)
  109. {
  110. if ($message == '{"type":"ping"}') {
  111. Gateway::sendToCurrentClient('{"type":"pong"}');
  112. return;
  113. } else {
  114. self::DebugOut($message, "OnMessage");
  115. }
  116. //echo(Gateway::getAllClientCount());
  117. $message = json_decode($message, true);
  118. if (isset($message['type'])) {
  119. switch ($message['type']) {
  120. case 'mydebug':
  121. self::mydebug($client_id, $message['data']);
  122. break;
  123. // 管理员初始化
  124. case 'adminInit':
  125. $token = $message['token'];
  126. self::adminInit($client_id, $token);
  127. break;
  128. // 客服初始化
  129. case 'init':
  130. $data = $message['data'];
  131. self::Kfinit($client_id, $data);
  132. break;
  133. // 顾客初始化
  134. case 'userInit';
  135. $data = $message['data'];
  136. self::userInitEnt($client_id, $data);
  137. break;
  138. //在线客服信息
  139. case 'getkfonlines':
  140. Gateway::sendToCurrentClient(json_encode(self::getkfonlines(), 256));
  141. break;
  142. //客服获取用户详细信息
  143. case 'kfgetuserinfo':
  144. $tmp_id = isset($message['data']['id']) ? $message['data']['id'] : 0;
  145. self::kfgetuserinfo($client_id, intval($tmp_id));
  146. break;
  147. // 客服聊天
  148. case 'chatMessage':
  149. self::chatMessage($message['data']);
  150. break;
  151. // 机器人问答.
  152. case 'toRobot':
  153. self::toRobot($client_id, $message);
  154. break;
  155. // 评价.
  156. case 'evaluate':
  157. self::evaluate($message['data']);
  158. break;
  159. // 客服关闭会话.
  160. case 'kfCloseUser':
  161. self::serverClose($message['data']['conversationId'], 3);
  162. break;
  163. // 客服更改状态.
  164. case 'kfOnline':
  165. self::KFStatusCg($client_id, $message);
  166. break;
  167. case 'changeOtherhKeFu';
  168. self::changeOtherhKeFu($client_id, $message);
  169. break;
  170. // 弹出评价.
  171. case 'getEvaluate';
  172. self::getEvaluate($message['data']);
  173. break;
  174. }
  175. }
  176. return true;
  177. }
  178. // 弹出评价.
  179. public static function getEvaluate($message)
  180. {
  181. // 获取当前会话工单.
  182. $data = json_decode(self::$redis->HGET('SERVICELOG', $message['conversationId']), true);
  183. if (empty($data)) {
  184. return;
  185. }
  186. $chat_message = [
  187. 'message_type' => 'getEvaluate',
  188. 'data' => [
  189. 'content' => '欢迎你的咨询,请对我们的服务做出评价',
  190. ]
  191. ];
  192. Gateway::sendToClient($data['client_id'], json_encode($chat_message, 256));
  193. }
  194. //客服聊天
  195. public static function chatMessage($message)
  196. {
  197. // 获取当前会话工单.
  198. $data = json_decode(self::$redis->HGET('SERVICELOG', $message['conversationId']), true);
  199. if (empty($data)) {
  200. return;
  201. }
  202. $chat_message = [
  203. 'message_type' => 'chatMessage',
  204. 'data' => [
  205. 'name' => $message['from_name'],
  206. 'id' => $message['from_id'],
  207. 'time' => date('H:i'),
  208. 'content' => $message['content'],
  209. ]
  210. ];
  211. // 是否为第一次回复.
  212. if (isset($message['isFirst']) && $message['isFirst']) {
  213. $data['alarm_corresponding'] = time() - $data['start_time'];
  214. $data['alarm_respond'] = 2;
  215. }
  216. // 发送消息.
  217. if (substr($message['from_id'], 0, 2) === 'KF') {
  218. // 统计敏感词.
  219. $data['alarm_serverSensitive'] += $message['sensitiveNumber'];
  220. $data['serverLastTime'] = time();
  221. Gateway::sendToClient($data['client_id'], json_encode($chat_message, 256));
  222. } else {
  223. // 统计敏感词.
  224. $data['alarm_userSensitive'] += $message['sensitiveNumber'];
  225. $data['userLastTime'] = time();
  226. Gateway::sendToClient($data['kf_client_id'], json_encode($chat_message, 256));
  227. }
  228. // 返回当前时间
  229. $chat_message = [
  230. 'message_type' => 'webTime',
  231. 'data' => [
  232. 'webTime' => date('H:i'),
  233. ]
  234. ];
  235. Gateway::sendToCurrentClient(json_encode($chat_message, 256));
  236. // 保存修改后的工单信息.
  237. self::$redis->HSET('SERVICELOG', $message['conversationId'], json_encode($data, 256));
  238. // 聊天信息入库
  239. $insertChatData = [
  240. 'from_id' => $message['from_id'],
  241. 'from_name' => $message['from_name'],
  242. 'to_id' => $message['to_id'],
  243. 'to_name' => $message['to_name'],
  244. 'content' => $message['content'],
  245. 'servicelog_id' => $message['conversationId'],
  246. 'time_line' => time()
  247. ];
  248. self::$db->insert('ws_chat_log')->cols($insertChatData)->query();
  249. }
  250. //得到一个用户详细信息
  251. public static function kfgetuserinfo($clientid, $id)
  252. {
  253. $ret = self::$db->select('*')->from('ws_account')->where('id=:id')->bindValues(['id' => $id])->row();
  254. Gateway::sendToClient($clientid, json_encode(['message_type' => 'userdetailinfo', 'data' => $ret]));
  255. return;
  256. }
  257. //获取在线客服列表
  258. public static function getkfonlines()
  259. {
  260. $return = [
  261. 'message_type' => 'onlinekfs',
  262. 'data' => [],
  263. ];
  264. $nowkfid = isset($_SESSION['uid']) ? $_SESSION['uid'] : 0;
  265. $fromgrouupid = isset($_SESSION['group']) ? $_SESSION['group'] : 0;
  266. if (empty($fromgrouupid) || empty($nowkfid)) {
  267. return $return;
  268. }
  269. $online = self::getOnlineKfData(0, 1);
  270. if (empty($online)) {
  271. return $return;
  272. }
  273. $groupnamemap = self::$global->groupmap;
  274. $ret = [];
  275. foreach ($online as $uinfo) {
  276. if ($nowkfid == $uinfo['id']) {
  277. continue;
  278. }
  279. $ret[] = ['groupid' => $uinfo['group'], 'groupname' => $groupnamemap[$uinfo['group']], 'kfuid' => $uinfo['id'], 'kfname' => $uinfo['name'], 'kfjobname' => $uinfo['job_name']];
  280. }
  281. $return['data'] = $ret;
  282. return $return;
  283. }
  284. public static function KFStatusCg($client_id, $message)
  285. {
  286. if (!isset($_SESSION['iskefu']) || $_SESSION['iskefu'] != 1) {
  287. return;
  288. }
  289. $userId = $message['data']['uid'];
  290. $status = intval($message['data']['status']);
  291. if (!in_array($status, [1, 2, 3])) {
  292. return false;
  293. }
  294. $oldstatus = '';
  295. $kfinfo = self::$redis->hget(self::KFINFOKEY, $userId);
  296. if (empty($kfinfo)) {
  297. return false;
  298. }
  299. $kfinfo = json_decode($kfinfo, true);
  300. if (!$kfinfo) {
  301. return false;
  302. }
  303. if ($kfinfo['status'] != $status) {
  304. $oldstatus = $kfinfo['status'];
  305. $kfinfo['status'] = $status;
  306. self::$redis->hset(self::KFINFOKEY, $userId, json_encode($kfinfo, 256));
  307. }
  308. self::writeLogKfStatus($userId, $status);
  309. Gateway::sendToCurrentClient(json_encode(['message_type' => 'cgstatus', 'data' => ['new_status' => $status, 'old_status' => $oldstatus]]));
  310. return;
  311. }
  312. //获取某个用户全部信息
  313. public static function getClientIndo($id)
  314. {
  315. $ret = self::$db->from('ws_accounts')->select("*")->where(['id' => $id])->row();
  316. return $ret;
  317. }
  318. //客服接入sock,及初始化
  319. public static function Kfinit($client_id, $message)
  320. {
  321. $uid = self::getPars($message, 'uid');
  322. $group = intval(self::getPars($message, 'group', 0));
  323. if (empty($uid) || empty($group) || !isset(self::$global->groupmap[$group])) {
  324. self::MySendMsg($client_id, json_encode(["message_type" => 'checkfalse', 'data' => "客服登陆参数错误"], 256));
  325. Gateway::closeCurrentClient();
  326. return;
  327. }
  328. $loginstate = self::$logic->userIsLogin($client_id, $uid, $group);
  329. if ($loginstate == 1) {
  330. self::MySendMsg($client_id, (json_encode(['message_type' => 'reLoginErr', 'msg' => '正在登陆中,请稍后...'], 256)));
  331. Gateway::closeClient($client_id);
  332. return;
  333. }
  334. //客服登陆验证 不符合的直接断掉
  335. $kfinfo = self::KfloginCheck($client_id, $message);
  336. if (empty($kfinfo)) {
  337. self::MySendMsg($client_id, json_encode(["message_type" => 'checkfalse', 'data' => "验证失败"], 256));
  338. Gateway::closeCurrentClient();
  339. return true;
  340. } elseif ($kfinfo['status'] != 1) {
  341. self::MySendMsg($client_id, json_encode(["message_type" => 'checkfalse', 'data' => "禁用中..."], 256));
  342. Gateway::closeCurrentClient();
  343. return true;
  344. }
  345. if ($loginstate == 2) {
  346. $oldcontids = Gateway::getClientIdByUid($uid);
  347. Gateway::sendToClient($oldcontids['0'], (json_encode(['message_type' => 'reLoginErr', 'msg' => '你的账号在其它登陆,本次下线'], 256)));
  348. Gateway::closeClient($oldcontids['0']);
  349. sleep(2);
  350. }
  351. self::$redis->hset('loginTmp:' . $uid, 'uid', time());
  352. self::$redis->expire('loginTmp:' . $uid, 5);
  353. $newinfo =
  354. [
  355. 'id' => 'KF' . $kfinfo['id'],
  356. 'name' => $kfinfo['user_name'],
  357. 'job_name' => $kfinfo['user_job_number'],
  358. 'avatar' => $kfinfo['user_avatar'],
  359. 'group' => $group,
  360. 'client_id' => $client_id,
  361. 'task' => 0,
  362. 'intime' => time(),
  363. 'signature' => $kfinfo['signature'],
  364. 'status' => 2, // 1为在线(接收分配、接收消息)2为隐身(不接收分配、只接收消息)3、休息
  365. 'user_info' => [], //在会话的用户cid key为clientid ,值为工单号
  366. ];
  367. self::$redis->hset(self::KFINFOKEY, $uid, json_encode($newinfo, 256));
  368. $_SESSION['info'] = $newinfo;
  369. // 绑定 client_id 和 uid
  370. Gateway::bindUid($client_id, $message['uid']);
  371. $_SESSION['group'] = $message['group'];
  372. $_SESSION['iskefu'] = 1;
  373. $_SESSION['uid'] = $message['uid'];
  374. $_SESSION['name'] = $message['name'];
  375. Gateway::joinGroup($client_id, 'group_' . $message['group']);
  376. $chat_message = [
  377. 'message_type' => 'loginSuccess',
  378. ];
  379. self::MySendMsg($client_id, json_encode($chat_message, 256));
  380. unset($chat_message);
  381. self::writeLogKfStatus($message['uid'], 2);
  382. return;
  383. }
  384. /**
  385. * 管理员登陆验证
  386. * @param $client_id 服务ID
  387. * @param $message 数据
  388. */
  389. public static function adminInit($client_id, $token)
  390. {
  391. // 查询token是否存在.
  392. $systemConfigData = self::$db->query("SELECT `id` FROM `ws_admins` where `token`= '$token'");
  393. if ($systemConfigData) {
  394. self::$redis->sadd('adminList', $client_id);
  395. self::systemMonitoring([$client_id]);
  396. } else {
  397. $chat_message = [
  398. 'message_type' => 'tips',
  399. 'data' => '管理员不存在'
  400. ];
  401. Gateway::sendToClient($client_id, json_encode($chat_message, 256));
  402. Gateway::closeClient($client_id);
  403. }
  404. }
  405. //客服登陆验证
  406. public static function KfloginCheck($client, $messageArray)
  407. {
  408. $uid = isset($messageArray['uid']) ? $messageArray['uid'] : '';
  409. $token = isset($messageArray['token']) ? $messageArray['token'] : '';
  410. if (empty($uid) || empty($token)) {
  411. return false;
  412. }
  413. $expire_time_vali = time() - 60 * 60 * 24;
  414. $kfid = intval(substr($uid, 2));
  415. $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();
  416. if ($ret) {
  417. self::$db->update('ws_users')->cols(array('online_status' => 1, 'online_connectid' => $client))->where('id=' . $kfid)->query();
  418. return $ret;
  419. }
  420. return false;
  421. }
  422. //用户发送邦定用户事件
  423. public static function userInitEnt($client_id, $message)
  424. {
  425. $uid = intval($message['uid']);
  426. $group = intval($message['group']);
  427. if (!isset(self::$global->groupmap[$group])) {
  428. self::MySendMsg($client_id, (json_encode(['message_type' => 'reLoginErr', 'msg' => '不存在客服组....'], 256)));
  429. return true;
  430. //Gateway::closeCurrentClient();
  431. }
  432. $loginstate = self::$logic->userIsLogin($client_id, $uid, $group);
  433. if ($loginstate == 1) {
  434. self::MySendMsg($client_id, (json_encode(['message_type' => 'reLoginErr', 'msg' => '正在登陆中,请稍后...'], 256)));
  435. Gateway::closeCurrentClient();
  436. return;
  437. }
  438. $hisdata = self::$redis->hget(self::USERINFOKEY, $uid);
  439. if ($hisdata) {
  440. $hisdata = json_decode($hisdata, true);
  441. $oldclientid = $hisdata['client_id'];
  442. self::MySendMsg($oldclientid, json_encode(['type' => 'reLoginErr', 'msg' => '相同账号登陆,本次退出'], 256));
  443. self::MySendMsg($client_id, json_encode(['type' => 'reLoginErr', 'msg' => '相同账号登陆,本次退出'], 256));
  444. Gateway::closeClient($oldclientid);
  445. Gateway::closeCurrentClient();
  446. return;
  447. }
  448. $last = self::UserHasOldTalk($uid);
  449. $onlinekf = self::getOnlineKfData($group, 1);
  450. if (empty($onlinekf)&&empty($last)) {
  451. Gateway::sendToClient($client_id, json_encode(['message_type' => 'notice', 'content' => '暂时没有客服上班,请稍后再咨询。'], 256));
  452. //Gateway::closeClient($client_id);
  453. return;
  454. }
  455. self::$redis->hset('loginTmp:' . $uid, 'uid', time());
  456. self::$redis->expire('loginTmp:' . $uid, 5);
  457. $data = [
  458. 'id' => $uid,
  459. 'name' => $message['name'],
  460. 'avatar' => $message['avatar'],
  461. 'website' => $_SESSION['origin'],//$message['website'],
  462. 'browse' => Gateway::browse_info(),
  463. 'system' => Gateway::get_os(),//$message['system'],
  464. 'ip' => isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '',//message['ip'],
  465. 'group' => $message['group'],
  466. 'intime' => time(),
  467. 'kfuid' => '',
  468. 'ip' => $_SESSION['remotip'],
  469. 'serverid' => 0,
  470. 'client_id' => $client_id
  471. ];
  472. self::$redis->hset(self::USERLIST, $uid, json_encode($data, 256));
  473. self::$redis->hset(self::USERINFOKEY, $uid, json_encode($data, 256));
  474. // 写入接入值
  475. $key = date('Ymd') . 'total_in';
  476. self::$global->increment($key);
  477. // 绑定 client_id 和 uid
  478. Gateway::bindUid($client_id, $uid);
  479. $_SESSION['iskefu'] = 0;
  480. $_SESSION['uid'] = $message['uid'];
  481. // 尝试分配新会员进入服务
  482. self::userOnlineTask($group, $uid, $last, $client_id);
  483. }
  484. /**
  485. * 当用户断开连接时触发
  486. * @param int $client_id 连接id
  487. *
  488. * tips: 当服务端主动退出的时候,会出现 exit status 9.原因是:服务端主动断开之后,连接的客户端会走这个方法,而短时间内进程
  489. * 需要处理这多的逻辑,又有cas操作,导致进程退出会超时,然后会被内核杀死,从而报出错误 9.实际对真正的业务没有任何的影响。
  490. */
  491. public static function onClose($client_id)
  492. {
  493. self::$redis->hdel(self::WEBSOCKALLUSER, $client_id);
  494. $isKefuoff = isset($_SESSION['iskefu']) ? $_SESSION['iskefu'] : 0;
  495. $uid = isset($_SESSION['uid']) ? $_SESSION['uid'] : false;
  496. echo "下线:uid: $uid - cid: $client_id - iskf: $isKefuoff \n";
  497. $isAdmin = self::$redis->sismember('adminList', $client_id);
  498. if ($isAdmin) {
  499. self::$redis->srem('adminList', $client_id);
  500. }
  501. if (empty($uid)) {
  502. return true;
  503. }
  504. if ($isKefuoff) {
  505. self::serviceOffline($client_id, $uid);
  506. } else {
  507. self::guestOffline($client_id, $uid);
  508. }
  509. return true;
  510. }
  511. //客服下线了 系统调用,不能手动调用
  512. public static function serviceOffline($client_id, $uid)
  513. {
  514. $group = $_SESSION['group'];
  515. $uinfo = self::$redis->hget(self::KFINFOKEY, $uid);
  516. self::$redis->hdel(self::KFINFOKEY, $uid);
  517. $uinfo = json_decode($uinfo, true);
  518. if (empty($uinfo)) {
  519. echo "客服发生异常退出\n";
  520. return;
  521. }
  522. $user_info = $uinfo['user_info'];
  523. $kfid = self::getkfid($uid);
  524. $now = time();
  525. $starttime = $now - 86400 * 7;
  526. self::$redis->hset('loginTmp:' . $uid, 'uid', time());
  527. self::$redis->expire('loginTmp:' . $uid, 5);
  528. if (!empty($user_info)) {
  529. foreach ($user_info as $val => $serverid) {
  530. self::insertServerLog($serverid, 4);
  531. self::$redis->hdel(self::SERVICELOG, intval($serverid));
  532. self::MySendMsg($val, json_encode(['message_type' => 'serviceoffline', 'msg' => '客户人员下线!'], 256));
  533. Gateway::closeClient($val);
  534. }
  535. }
  536. $sql = "update `ws_service_log` set `status` = '2',end_time=$now,`servicelog_close_type` = 4 where start_time>=$starttime and kf_id=$kfid and group_id=$group and `status`!=2 ";
  537. echo "客服退出: " . $uid . "\n";
  538. self::$db->query($sql);
  539. self::$db->update('ws_users')->cols(array('online_status' => 0, 'online_connectid' => ''))->where('id=' . $kfid)->query();
  540. self::writeLogKfStatus($uid, 0);
  541. return;
  542. }
  543. //用户下线了 系统调用,不能手动调用
  544. public static function guestOffline($client_id, $uid)
  545. {
  546. self::$redis->hset('loginTmp:' . $uid, 'uid', time());
  547. self::$redis->expire('loginTmp:' . $uid, 3);
  548. $uid = intval($uid);
  549. $krclient_id = 0;
  550. $data = self::$redis->hget(self::USERINFOKEY, $uid);
  551. if (empty($data)) {
  552. return;
  553. }
  554. $info = json_decode($data, true);
  555. self::$redis->hdel(self::USERLIST, $uid);
  556. self::$redis->hdel(self::USERINFOKEY, $uid);
  557. if (!empty($info['kfuid'])) {
  558. $kfinfo = self::$redis->hget(self::KFINFOKEY, $info['kfuid']);
  559. if (!empty($kfinfo)) {
  560. $kfinfoArr = json_decode($kfinfo, true);
  561. $krclient_id = $kfinfoArr['client_id'];
  562. /*$kfinfoArr['user_info'] = self::ArrayDataopt($kfinfoArr['user_info'], $client_id, 0);
  563. $kfinfoArr['task'] = count($kfinfoArr['user_info']);
  564. self::$redis->hset(self::KFINFOKEY, $info['kfuid'], json_encode($kfinfoArr, 256));*/
  565. }
  566. }
  567. $chat_message = [
  568. 'message_type' => 'userClose',
  569. 'data' => [
  570. 'content' => '用户连接已断开',
  571. 'id' => $uid,
  572. 'time' => date('H:i'),
  573. ]
  574. ];
  575. $now = time();
  576. $serverid = intval($info['serverid']);
  577. if ($serverid) {
  578. $sql = "update `ws_service_log` set `status` = '3' where servicelog_id=$serverid and `status` !=2 ";
  579. self::$db->query($sql);
  580. }
  581. if ($krclient_id) {
  582. Gateway::sendToClient($krclient_id, json_encode($chat_message, 256));
  583. }
  584. return;
  585. }
  586. /**
  587. * 客服结束会话
  588. *
  589. * tips: 未有$client_id的关闭
  590. */
  591. public static function closeUser($servicelog_id, $userId, $kf_id, $groupId)
  592. {
  593. }
  594. /**
  595. * 工单结束
  596. * @param int $client_id 连接id
  597. *
  598. * tips: 当服务端主动退出的时候,会出现 exit status 9.原因是:服务端主动断开之后,连接的客户端会走这个方法,而短时间内进程
  599. * 需要处理这多的逻辑,又有cas操作,导致进程退出会超时,然后会被内核杀死,从而报出错误 9.实际对真正的业务没有任何的影响。
  600. */
  601. public static function serverClose($servicelogId, $closeBy = 0)
  602. {
  603. // 获取当前工单数据.
  604. $data = json_decode(self::$redis->HGET('SERVICELOG', $servicelogId), true);
  605. if (empty($data)) {
  606. return;
  607. }
  608. // 获取当前客服.
  609. $kfInfo = json_decode(self::$redis->HGET('KFINFO', 'KF' . $data['kf_id']), true);
  610. if (empty($kfInfo)) {
  611. return;
  612. }
  613. // 删除当前工单.
  614. self::$redis->hdel('SERVICELOG', $servicelogId);
  615. // 当前服务客服删除当前人员.
  616. $kfUserList = self::ArrayDataopt($kfInfo['user_info'], $data['client_id'], 0);
  617. // 删除当前人员信息.
  618. self::$redis->hdel('USERINFO', $data['user_id']);
  619. // 当前客服所接待人员.
  620. $kfInfo['user_info'] = $kfUserList;
  621. $kfInfo['task'] = count($kfUserList);
  622. // 存入客服信息.
  623. self::$redis->HSET('KFINFO', 'KF' . $data['kf_id'], json_encode($kfInfo, 256));
  624. // 发送消息给用户.
  625. $chat_message = [
  626. 'message_type' => 'closeBysever',
  627. 'data' => [
  628. 'content' => '客服停止了该会话',
  629. 'time' => date('H:i'),
  630. ]
  631. ];
  632. Gateway::sendToClient($data['client_id'], json_encode($chat_message, 256));
  633. // 关闭用户连接.
  634. Gateway::closeClient($data['client_id']);
  635. // 发送消息给客服.
  636. $del_message = [
  637. 'message_type' => 'delUser',
  638. 'data' => [
  639. 'id' => $data['user_id']
  640. ]
  641. ];
  642. Gateway::sendToClient($data['kf_client_id'], json_encode($del_message, 256));
  643. // 查询工单会话总数.
  644. $chatCount = self::$db->select('count(*) as count')->from('ws_chat_log')->where("servicelog_id=$servicelogId")->row();
  645. // 将数据存入数据库.
  646. $updateServiceLogData = [
  647. 'status' => 2,
  648. 'evaluate_id' => isset($data['evaluate_id']) ? $data['evaluate_id'] : 0,
  649. 'evaluate_content' => isset($data['evaluate_content']) ? $data['evaluate_content'] : '',
  650. 'servicelog_close_type' => $closeBy,
  651. 'end_time' => time(),
  652. ];
  653. $updataAlarmData = [
  654. 'alarm_userSensitive' => $data['alarm_userSensitive'],
  655. 'alarm_serverSensitive' => $data['alarm_serverSensitive'],
  656. 'alarm_corresponding' => $data['alarm_corresponding'],
  657. 'alarm_cvtOvertime' => time() - $data['start_time'],
  658. 'alarm_respond' => $data['alarm_respond'],
  659. 'alarm_lineTime' => $data['start_time'] - $data['intime'],
  660. 'alarm_count' => $chatCount['count'],
  661. ];
  662. self::$db->update('ws_service_log')->cols($updateServiceLogData)->where("servicelog_id=$servicelogId")->query();
  663. self::$db->update('ws_alarm')->cols($updataAlarmData)->where("servicelog_id=$servicelogId")->query();
  664. }
  665. /**
  666. * 修改工单数据库数据
  667. * @param int $client_id 连接id
  668. *
  669. * tips: 当服务端主动退出的时候,会出现 exit status 9.原因是:服务端主动断开之后,连接的客户端会走这个方法,而短时间内进程
  670. * 需要处理这多的逻辑,又有cas操作,导致进程退出会超时,然后会被内核杀死,从而报出错误 9.实际对真正的业务没有任何的影响。
  671. */
  672. public static function insertServerLog($servicelogId, $closeBy = 0)
  673. {
  674. // 获取当前工单数据.
  675. $data = json_decode(self::$redis->HGET('SERVICELOG', $servicelogId), true);
  676. if (empty($data)) {
  677. return;
  678. }
  679. // 查询工单会话总数.
  680. $chatCount = self::$db->select('count(*) as count')->from('ws_chat_log')->where("servicelog_id=$servicelogId")->row();
  681. // 将数据存入数据库.
  682. $updateServiceLogData = [
  683. 'status' => 2,
  684. 'evaluate_id' => isset($data['evaluate_id']) ? $data['evaluate_id'] : 0,
  685. 'evaluate_content' => isset($data['evaluate_content']) ? $data['evaluate_content'] : '',
  686. 'servicelog_close_type' => $closeBy,
  687. 'end_time' => time(),
  688. ];
  689. $updataAlarmData = [
  690. 'alarm_userSensitive' => $data['alarm_userSensitive'],
  691. 'alarm_serverSensitive' => $data['alarm_serverSensitive'],
  692. 'alarm_corresponding' => $data['alarm_corresponding'],
  693. 'alarm_cvtOvertime' => time() - $data['start_time'],
  694. 'alarm_respond' => $data['alarm_respond'],
  695. 'alarm_lineTime' => $data['start_time'] - $data['intime'],
  696. 'alarm_count' => $chatCount['count'],
  697. ];
  698. self::$db->update('ws_service_log')->cols($updateServiceLogData)->where("servicelog_id=$servicelogId")->query();
  699. self::$db->update('ws_alarm')->cols($updataAlarmData)->where("servicelog_id=$servicelogId")->query();
  700. }
  701. /**
  702. * 有人退出
  703. * @param $group
  704. */
  705. private static function userOfflineTask($group)
  706. {
  707. }
  708. /**
  709. * 有人进入执行分配
  710. * @param $client_id
  711. * @param $group
  712. * @param $uid
  713. */
  714. private static function userOnlineTask($group = 0, $uid = 0, $last=[], $client_id='')
  715. {
  716. $allusergkarr = self::getUserListData();
  717. if (empty($allusergkarr)) {
  718. return;
  719. }
  720. $allkfgkarr = self::getWorkKfData();
  721. if (empty($allkfgkarr)) {
  722. return;
  723. }
  724. $maxset = (self::$global->systemconfig)['KFMaxServices'] ?? 5;
  725. $maxset = intval($maxset);
  726. if ($group && $uid) {
  727. // 指定用指定组 [可能存在断线重连的情况] 如果存在旧的会话,直接连线客服和用户
  728. //否则按先到后到以及客服最大服务数限制
  729. if ($last) {
  730. self::BeginTalk(self::getkfuid($last['kf_id']), $uid, $last['group_id'], $last['servicelog_id']);
  731. $toOld_message = [
  732. 'message_type' => 'toOld',
  733. 'data' => [
  734. 'content' => '接入至未结束的会话'
  735. ]
  736. ];
  737. Gateway::sendToCurrentClient(json_encode($toOld_message, 256));
  738. return;
  739. } else {
  740. //系统定时调用时,无组,无用户
  741. foreach ($allusergkarr as $group => $gusersArr) {
  742. if (!isset($allkfgkarr[$group]) || count($allkfgkarr[$group]) <= 0) {
  743. //所属客服组无人在线
  744. continue;
  745. }
  746. $nowkfs = $allkfgkarr[$group];
  747. $count = count($nowkfs);
  748. $i = 0;
  749. foreach ($gusersArr as $user) {
  750. if ($nowkfs[$i]['task'] > $maxset) {
  751. break;
  752. }
  753. $nowkfs[$i]['task']++;
  754. self::BeginTalk($nowkfs[$i]['id'], $user['id'], $group, 0, $user);
  755. self::$redis->hdel(self::USERLIST, $user['id']);
  756. $i++;
  757. if ($i >= $count) {
  758. $i = 0;
  759. }
  760. }
  761. }
  762. return;
  763. }
  764. }
  765. }
  766. //开启一个会话
  767. private static function BeginTalk($kfuid, $uid, $group, $serviceid = 0, $userInfo = false)
  768. {
  769. $serviceid = intval($serviceid);
  770. if (!$userInfo) {
  771. $userInfo = json_decode(self::$redis->hget(self::USERINFOKEY, $uid), true);
  772. }
  773. $kfinfo = json_decode(self::$redis->hget(self::KFINFOKEY, $kfuid), true);
  774. if (empty($userInfo) || empty($kfinfo)) {
  775. return false;
  776. }
  777. $server = [];
  778. $armarr = [];
  779. if ($serviceid) {
  780. $server = self::$db->select('*')->from('ws_service_log')->where("servicelog_id=$serviceid ")->row();
  781. if ($server) {
  782. $armarr = self::$db->select('*')->from('ws_alarm')->where("servicelog_id=$serviceid ")->row();
  783. }
  784. }
  785. if (empty($server)) {
  786. $array = [
  787. 'user_id' => intval($uid),
  788. 'client_id' => $userInfo['client_id'],
  789. 'user_name' => $userInfo['name'],
  790. 'user_avatar' => $userInfo['avatar'],
  791. 'user_ip' => $userInfo['ip'],
  792. 'kf_id' => self::getkfid($kfuid),
  793. 'start_time' => time(),
  794. 'group_id' => $group ? $group : $userInfo['group'],
  795. 'website' => $userInfo['website'],
  796. 'system' => $userInfo['system'],
  797. 'browse' => $userInfo['browse'],
  798. 'intime' => $userInfo['intime'],
  799. 'status' => 1,
  800. 'evaluate_id' => 0,
  801. 'servicelog_close_type' => 0
  802. ];
  803. $serviceid = self::$db->insert('ws_service_log')->cols($array)->query();
  804. $server = array_merge(['servicelog_id' => $serviceid], $array);
  805. $armid = self::$db->insert('ws_alarm')->cols(['servicelog_id' => $serviceid])->query();
  806. $armarr = self::$db->select('*')->from('ws_alarm')->where("alarm_id=$armid")->row();
  807. }
  808. $redisData = array_merge($server, $armarr, ['kf_client_id' => $kfinfo['client_id'], 'server_name' => $kfinfo['name']]);
  809. self::$redis->hset(self::SERVICELOG, $serviceid, json_encode($redisData, 256));
  810. $kfinfo['user_info'] = array_merge($kfinfo['user_info'], [$userInfo['client_id'] => $serviceid]);
  811. $kfinfo['task'] = count($kfinfo['user_info']);
  812. self::$redis->hset(self::KFINFOKEY, $kfuid, json_encode($kfinfo, 256));
  813. $userInfo['serverid'] = $serviceid;
  814. $userInfo['kfuid'] = $kfuid;
  815. self::$redis->hset(self::USERINFOKEY, $uid, json_encode($userInfo, 256));
  816. // 通知会员发送信息绑定客服的id
  817. $noticeUser = [
  818. 'message_type' => 'connect',
  819. 'data' => [
  820. 'kf_id' => $kfuid,
  821. 'conversationId' => $serviceid,
  822. 'serverInfo' => $kfinfo,
  823. 'kf_name' => $kfinfo['job_name']
  824. ]
  825. ];
  826. self::MySendMsg($userInfo['client_id'], json_encode($noticeUser, 256));
  827. $sayHello = (self::$global->replay)['2'];
  828. if (!empty($sayHello) && 1 == $sayHello['status']) {
  829. $chat_message = [
  830. 'message_type' => 'chatMessage',
  831. 'data' => [
  832. 'id' => self::getkfuid($kfinfo['id']),
  833. 'name' => $kfinfo['name'],
  834. 'time' => date('H:i'),
  835. 'content' => $sayHello['word']
  836. ]
  837. ];
  838. self::MySendMsg($userInfo['client_id'], json_encode($chat_message, 256));
  839. unset($chat_message);
  840. }
  841. $noticeKf = [
  842. 'message_type' => 'connect',
  843. 'data' => [
  844. 'user_info' => $userInfo,
  845. 'conversationId' => $serviceid,
  846. ]
  847. ];
  848. self::MySendMsg($kfinfo['client_id'], json_encode($noticeKf, 256));
  849. unset($noticeKf);
  850. $key = date('Ymd') . 'success_in';
  851. self::$global->increment($key);
  852. return;
  853. }
  854. //连接至上一个会话
  855. private static function BeginOldTalk($kfuid, $uid, $group, $serviceid = 0, $userInfo = false)
  856. {
  857. $serviceid = intval($serviceid);
  858. $userInfo = json_decode(self::$redis->hget(self::USERINFOKEY, $uid), true);
  859. $kfinfo = json_decode(self::$redis->hget(self::KFINFOKEY, $kfuid), true);
  860. if (empty($userInfo) || empty($kfinfo)) {
  861. return false;
  862. }
  863. // 获取旧工单信息.
  864. $data = json_decode(self::$redis->HGET('SERVICELOG', $last['servicelog_id']), true);
  865. // 修改工单数据.
  866. $data['user_avatar'] = $userInfo['avatar'];
  867. $data['client_id'] = $userInfo['client_id'];
  868. $data['user_ip'] = $userInfo['ip'];
  869. $data['website'] = $userInfo['website'];
  870. $data['system'] = $userInfo['system'];
  871. $data['browse'] = $userInfo['browse'];
  872. $data['status'] = $userInfo['status'];
  873. self::$redis->hset(self::SERVICELOG, $serviceid, json_encode($data, 256));
  874. // 更改用户连接客服信息
  875. $userInfo['serverid'] = $serviceid;
  876. $userInfo['kfuid'] = $kfuid;
  877. self::$redis->hset(self::USERINFOKEY, $uid, json_encode($userInfo, 256));
  878. // 通知会员发送信息绑定客服的id
  879. $noticeUser = [
  880. 'message_type' => 'connect',
  881. 'data' => [
  882. 'kf_id' => $kfuid,
  883. 'conversationId' => $serviceid,
  884. 'serverInfo' => $kfinfo,
  885. 'kf_name' => $kfinfo['job_name']
  886. ]
  887. ];
  888. self::MySendMsg($userInfo['client_id'], json_encode($noticeUser, 256));
  889. // 发送给客服用户信息.
  890. $noticeKf = [
  891. 'message_type' => 'connect',
  892. 'data' => [
  893. 'user_info' => $userInfo,
  894. 'conversationId' => $serviceid,
  895. ]
  896. ];
  897. self::MySendMsg($kfinfo['client_id'], json_encode($noticeKf, 256));
  898. unset($noticeKf);
  899. $key = date('Ymd') . 'success_in';
  900. self::$global->increment($key);
  901. return;
  902. }
  903. //用户排队数据 按组
  904. private static function getUserListData()
  905. {
  906. $alluser = self::$redis->hgetall(self::USERLIST);
  907. if (empty($alluser)) {
  908. return false;
  909. }
  910. $allusergkarr = [];
  911. foreach ($alluser as $val) {
  912. $now = json_decode($val, true);
  913. if ($now) {
  914. //用户分组后的数组
  915. $allusergkarr[$now['group']][] = $now;
  916. }
  917. }
  918. foreach ($allusergkarr as $group => $nowgroups) {
  919. usort($allusergkarr[$group], function ($a, $b) {
  920. if ($a['intime'] == $b['intime']) {
  921. return 0;
  922. }
  923. return ($a['intime'] > $b['intime']) ? 1 : -1;
  924. });
  925. }
  926. if (!$allusergkarr) {
  927. return false;
  928. }
  929. unset($alluser);
  930. return $allusergkarr;
  931. }
  932. //找到可以接工单的客服 按组
  933. private static function getWorkKfData()
  934. {
  935. $allkfs = self::$redis->hgetall(self::KFINFOKEY);
  936. if (empty($allkfs)) {
  937. return false;
  938. }
  939. $allkfgkarr = [];
  940. foreach ($allkfs as $val) {
  941. $now = json_decode($val, true);
  942. if ($now && $now['status'] == 1) {
  943. //客分组后的数组
  944. $allkfgkarr[$now['group']][] = $now;
  945. }
  946. }
  947. if (!$allkfgkarr) {
  948. return false;
  949. }
  950. //客服每组按任务数由小到大排序 任务相同时按时间先后顺序
  951. foreach ($allkfgkarr as $group => $nowgroups) {
  952. usort($allkfgkarr[$group], function ($a, $b) {
  953. if ($a['task'] == $b['task']) {
  954. if ($a['intime'] == $b['intime']) {
  955. return 0;
  956. }
  957. return ($a['intime'] > $b['intime']) ? 1 : -1;
  958. }
  959. return ($a['task'] > $b['task']) ? 1 : -1;
  960. });
  961. }
  962. unset($allkfs);
  963. return $allkfgkarr;
  964. }
  965. //找到用户是否有一条未关闭的会话
  966. private static function UserHasOldTalk($uid)
  967. {
  968. $uid = intval($uid);
  969. $start_time = time() - 86400;
  970. $ret = self::$db->select('*')->from('ws_service_log')->where("start_time>=$start_time and user_id=$uid and status!=2 ")->orderByDESC(['servicelog_id'])->row();
  971. return $ret;
  972. }
  973. //今天排序累加
  974. private static function todayqueuelength()
  975. {
  976. $dtype = 'user.queue.day.length';
  977. $today = date("Y-m-d");
  978. $sret = self::$db->select('*')->from('ws_countmidtable')->where('dtype=:dtype and mdate=:mdate')->bindValues(array('dtype' => $dtype, 'mdate' => $today))->row();
  979. if ($sret) {
  980. self::$db->update('ws_countmidtable')->cols(array('dcontent' => intval($sret['dcontent']) + 1))->where('id=' . $sret['id'])->query();
  981. } else {
  982. self::$db->insert('ws_countmidtable')->cols(array(
  983. 'dtype' => $dtype,
  984. 'mdate' => $today,
  985. 'datatype' => 1,
  986. 'dcontent' => 1))->query();
  987. }
  988. }
  989. //客服工单转单
  990. private static function servicetrutoother($type, $owen, $otherkfid, $serverid, $clientuid)
  991. {
  992. $owen = intval(substr($owen, 2));
  993. $otherkfid = intval(substr($otherkfid, 2));
  994. self::$db->insert('ws_serviceturn_log')->cols(array(
  995. 'stype' => $type,
  996. 'uid' => $owen,
  997. 'tuid' => $otherkfid,
  998. 'serverid' => $serverid,
  999. 'guestuid' => $clientuid
  1000. ))->query();
  1001. }
  1002. /**
  1003. * 给客服分配会员【均分策略】
  1004. * @param $kfList
  1005. * @param $userList
  1006. * @param $group
  1007. * @param $total
  1008. */
  1009. private static function assignmentTask($kfList, $userList, $group, $total, $uid = 0)
  1010. {
  1011. }
  1012. /**
  1013. * 获取最大的服务人数
  1014. * @return int
  1015. */
  1016. private static function getMaxServiceNum()
  1017. {
  1018. $maxNumber = self::$db->query('select `max_service` from `ws_kf_config` where `id` = 1');
  1019. if (!empty($maxNumber)) {
  1020. $maxNumber = 5;
  1021. } else {
  1022. $maxNumber = $maxNumber['0']['max_service'];
  1023. }
  1024. return $maxNumber;
  1025. }
  1026. /**
  1027. * 将内存中的数据写入统计表
  1028. * @param int $flag
  1029. */
  1030. private static function writeLog($flag = 1)
  1031. {
  1032. // 上午 8点 到 22 点开始统计
  1033. if (date('H') < 8 || date('H') > 22) {
  1034. return;
  1035. }
  1036. $inQueue_1 = self::$redis->hgetall(self::USERLIST);
  1037. $inQueue = empty($inQueue_1) ? 0 : count($inQueue_1);
  1038. $allkf = self::$redis->hgetall(self::KFINFOKEY);
  1039. $nowTalking = $onlineKf = 0;
  1040. if (!empty($allkf)) {
  1041. foreach ($allkf as $kfuid => $val) {
  1042. $tmp = json_decode($val, true);
  1043. $onlineKf++;
  1044. $nowTalking += count($tmp['user_info']);
  1045. }
  1046. }
  1047. $key = date('Ymd') . 'total_in';
  1048. $key2 = date('Ymd') . 'success_in';
  1049. $param = [
  1050. 'is_talking' => $nowTalking,
  1051. 'in_queue' => $inQueue,
  1052. 'online_kf' => $onlineKf,
  1053. 'success_in' => self::$global->$key2,
  1054. 'total_in' => self::$global->$key,
  1055. 'now_date' => date('Y-m-d')
  1056. ];
  1057. self::$db->update('ws_now_data')->cols($param)->where('id=1')->query();
  1058. if (2 == $flag) {
  1059. $param = [
  1060. 'is_talking' => $nowTalking,
  1061. 'in_queue' => $inQueue,
  1062. 'online_kf' => $onlineKf,
  1063. 'success_in' => self::$global->$key2,
  1064. 'total_in' => self::$global->$key,
  1065. 'add_date' => date('Y-m-d'),
  1066. 'add_hour' => date('H'),
  1067. 'add_minute' => date('i'),
  1068. ];
  1069. self::$db->insert('ws_service_data')->cols($param)->query();
  1070. }
  1071. unset($allkf, $nowTalking, $inQueue, $onlineKf, $key, $key2, $param);
  1072. }
  1073. /**
  1074. * 机器人问答
  1075. * @param $client_id 服务ID
  1076. * @param $message 数据
  1077. */
  1078. private static function toRobot($client_id, $message)
  1079. {
  1080. $groups_id = $message['data']['groups_id'];
  1081. $robot_name = $message['data']['robot_name'];
  1082. $robotgroups_id = $message['data']['robotgroups_id'];
  1083. // 查询问题.
  1084. $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 . "'");
  1085. $chat_message = [
  1086. 'message_type' => 'robotMessage',
  1087. //'message_type' => 'chatMessage',
  1088. 'data' => [
  1089. 'name' => '智能助手',
  1090. 'time' => date('H:i'),
  1091. 'content' => $getRobot ? $getRobot[0]['robot_content'] : 'error',
  1092. ]
  1093. ];
  1094. Gateway::sendToClient($client_id, json_encode($chat_message, 256));
  1095. }
  1096. /**
  1097. * 评价
  1098. * @param $client_id 服务ID
  1099. * @param $message 数据
  1100. */
  1101. private static function evaluate($message)
  1102. {
  1103. // 获取当前会话工单.
  1104. $data = json_decode(self::$redis->HGET('SERVICELOG', $message['conversationId']), true);
  1105. if (empty($data)) {
  1106. return;
  1107. }
  1108. $data['evaluate_id'] = $message['evaluate_id'];
  1109. $data['evaluate_content'] = $message['evaluate_content'];
  1110. self::$redis->HSET('SERVICELOG', $data['client_id'], json_encode($data, 256));
  1111. $chat_message = [
  1112. 'message_type' => 'evaluate',
  1113. 'data' => [
  1114. 'status' => 1,
  1115. 'time' => date('H:i'),
  1116. ]
  1117. ];
  1118. Gateway::sendToClient($message['client_id'], json_encode($chat_message, 256));
  1119. }
  1120. //获取系统配置
  1121. private static function upsystemconfig()
  1122. {
  1123. $systemConfigData = self::$db->query("SELECT * FROM `ws_systemconfig`");
  1124. $arr = [];
  1125. if ($systemConfigData) {
  1126. foreach ($systemConfigData as $item) {
  1127. $arr[$item['systemconfig_enName']] = $item;
  1128. }
  1129. self::$global->systemconfig = $arr;
  1130. }
  1131. $group = self::$db->query("SELECT * FROM `ws_groups`");
  1132. $arr = [];
  1133. if ($group) {
  1134. foreach ($group as $val) {
  1135. $arr[$val['id']] = $val['name'];
  1136. }
  1137. self::$global->groupmap = $arr;
  1138. }
  1139. $arr = [];
  1140. $replay = self::$db->query('select * from `ws_reply`');
  1141. if ($replay) {
  1142. foreach ($replay as $val) {
  1143. $arr[$val['id']] = $val;
  1144. }
  1145. self::$global->replay = $arr;
  1146. }
  1147. }
  1148. /**
  1149. * 超时
  1150. * @param $client_id 服务ID
  1151. * @param $message 数据
  1152. */
  1153. private static function overTime()
  1154. {
  1155. // 查询对话时效设置.
  1156. $systemConfigData = self::$db->query("SELECT `systemconfig_data`,`systemconfig_enName`,`systemconfig_content` FROM `ws_systemconfig`");
  1157. foreach ($systemConfigData as $k => $v) {
  1158. if ($v['systemconfig_enName'] == 'overtime') {
  1159. $configOvertime = $v;
  1160. } elseif ($v['systemconfig_enName'] == 'unoperated') {
  1161. $configUnoperated = $v;
  1162. }
  1163. }
  1164. // 查询未断开的工单.
  1165. $serviceLog = self::$redis->hGetall('SERVICELOG');
  1166. $setOvertime = strtotime('-' . ($configOvertime['systemconfig_data'] - 60) . ' second');
  1167. $overtime = strtotime('-' . ($configOvertime['systemconfig_data']) . ' second');
  1168. $setUnoperated = strtotime('-' . ($configUnoperated['systemconfig_data'] - 60) . ' second');
  1169. $unoperated = strtotime('-' . ($configUnoperated['systemconfig_data']) . ' second');
  1170. foreach ($serviceLog as $k => $v) {
  1171. // 无效会话关闭.如果没有说一句话.
  1172. $data = json_decode($v, true);
  1173. if (!isset($data['userLastTime'])) {
  1174. if ($data['start_time'] <= $unoperated) {
  1175. self::serverClose($k, 1);
  1176. // 如果小于设定时间前一分钟则给出提示.
  1177. } elseif ($data['start_time'] <= $setUnoperated) {
  1178. $chat_message = [
  1179. 'message_type' => 'overtime',
  1180. 'data' => [
  1181. 'content' => $configUnoperated['systemconfig_content'],
  1182. ]
  1183. ];
  1184. Gateway::sendToClient($data['client_id'], json_encode($chat_message, 256));
  1185. }
  1186. // 双方静默超时.
  1187. } elseif ($data['userLastTime'] <= $overtime && $data['serverLastTime'] <= $overtime) {
  1188. self::serverClose($k, 2);
  1189. // 如果小于设定时间前一分钟则给出提示.
  1190. } elseif ($data['userLastTime'] <= $setOvertime && $data['serverLastTime'] <= $setOvertime) {
  1191. $chat_message = [
  1192. 'message_type' => 'overtime',
  1193. 'data' => [
  1194. 'content' => $configOvertime['systemconfig_content'],
  1195. ]
  1196. ];
  1197. Gateway::sendToClient($data['client_id'], json_encode($chat_message, 256));
  1198. }
  1199. }
  1200. }
  1201. /**
  1202. * 系统监控
  1203. * @param $message 数据
  1204. */
  1205. private static function systemMonitoring($adminList)
  1206. {
  1207. // 查询正进行的工单.
  1208. $serviceLog = self::$redis->hGetall('SERVICELOG');
  1209. // 查询系统设置表.
  1210. $systemconfig = self::$db->query("SELECT `systemconfig_data`,`systemconfig_enName` FROM `ws_systemconfig` WHERE `systemconfig_enName`='verifyReturnTime' or `systemconfig_enName`='verifyAllTime'");
  1211. // 质检会话响应时长.
  1212. $returnTimeKey = array_search('verifyReturnTime', array_column($systemconfig, 'systemconfig_enName'));
  1213. $verifyReturnTime = $systemconfig[$returnTimeKey]['systemconfig_data'];
  1214. // 质检会话时长.
  1215. $allTimeKey = array_search('verifyAllTime', array_column($systemconfig, 'systemconfig_enName'));
  1216. $verifyAllTime = $systemconfig[$allTimeKey]['systemconfig_data'];
  1217. $evaluateCount = 0; // 差评总次数.
  1218. $overtimeNumber = 0; // 会话超时总次数.
  1219. $overtimeTime = []; // 每次会话超时时间.
  1220. $userSensitive = 0; // 用户敏感词报警总次数.
  1221. $serverSensitive = 0; // 客服敏感词报警总次数.
  1222. $csdNumber = 0; // 响应超时总次数.
  1223. $csdTime = []; // 每次响应超时时间.
  1224. foreach ($serviceLog as $k => $v) {
  1225. $data = json_decode($v, true);
  1226. // 工单报警次数.
  1227. $allCount = 0;
  1228. if ($data['evaluate_id'] == 3) {
  1229. $evaluateCount++; // 差评次数.
  1230. $allCount++; // 工单报警次数.
  1231. }
  1232. // 会话超时.
  1233. $duration = time() - $data['start_time'];
  1234. if ($duration > $verifyAllTime) {
  1235. $overtimeNumber++; // 会话超时总次数.
  1236. $allCount++; // 工单报警次数.
  1237. $overtimeTime[] = $duration; // 响应超时时间.
  1238. }
  1239. // 敏感词报警.
  1240. $userSensitive += $data['alarm_userSensitive'];
  1241. $allCount += $data['alarm_userSensitive'];
  1242. $serverSensitive += $data['alarm_serverSensitive'];
  1243. $allCount += $data['alarm_serverSensitive'];
  1244. // 响应超时.
  1245. if ($data['alarm_corresponding'] > $verifyReturnTime) {
  1246. $csdTime[] = $data['alarm_corresponding']; // 响应超时时间.
  1247. $csdNumber++; // 响应超时总次数.
  1248. $allCount++; // 工单报警次数.
  1249. }
  1250. $serviceLog[$k] = $data;
  1251. $serviceLog[$k]['allCount'] = $allCount; // 工单报警次数.
  1252. }
  1253. self::DebugOut([$serviceLog, $csdTime, $verifyReturnTime], 'systemMonitoring');
  1254. $chat_message = [
  1255. 'message_type' => 'monitor',
  1256. 'data' => [
  1257. 'cvtList' => $serviceLog,
  1258. 'userSensitive' => $userSensitive,
  1259. 'serverSensitive' => $serverSensitive,
  1260. 'csdNumber' => $csdNumber,
  1261. 'csdTime' => $csdTime,
  1262. 'overtimeNumber' => $overtimeNumber,
  1263. 'overtimeTime' => $overtimeTime,
  1264. 'evaluateCount' => $evaluateCount,
  1265. ]
  1266. ];
  1267. // 查询对话时效设置.
  1268. foreach ($adminList as $v) {
  1269. Gateway::sendToClient($v, json_encode($chat_message, 256));
  1270. }
  1271. }
  1272. //客户工单内部组转接
  1273. public static function changeOtherhKeFu($client_id, $smessage)
  1274. {
  1275. $message = $smessage['data'];
  1276. $groupid = isset($message['fromgroup']) ? intval($message['fromgroup']) : 0;
  1277. $groupidto = isset($message['togroup']) ? intval($message['togroup']) : 0;
  1278. $toukfid = isset($message['toukfuid']) ? $message['toukfuid'] : 0;
  1279. $fromkfuid = isset($message['fromkfuid']) ? $message['fromkfuid'] : 0;
  1280. $uid = isset($message['uid']) ? intval($message['uid']) : 0;
  1281. $word = isset($message['word']) ? $message['word'] : '';
  1282. if (empty($groupid) || empty($groupidto) || empty($toukfid) || empty($fromkfuid) || empty($uid) || ($toukfid == $fromkfuid)) {
  1283. self::DebugOut('changeOtherhKeFu exit1...');
  1284. return false;
  1285. }
  1286. if (!Gateway::isUidOnline($toukfid) || !Gateway::isUidOnline($uid)) {
  1287. self::DebugOut('changeOtherhKeFu exit2...');
  1288. return false;
  1289. }
  1290. $kf_info_from = json_decode(self::$redis->hget(self::KFINFOKEY, $fromkfuid), true);
  1291. $kf_info_to = json_decode(self::$redis->hget(self::KFINFOKEY, $toukfid), true);
  1292. $user_info = json_decode(self::$redis->hget(self::USERINFOKEY, $uid), true);
  1293. $serviceid = intval($user_info['serverid']);
  1294. if (empty($kf_info_from) || empty($kf_info_to) || empty($user_info) || empty($serviceid)) {
  1295. self::DebugOut('changeOtherhKeFu exit23...');
  1296. return false;
  1297. }
  1298. if ($kf_info_to['status'] != 1) {
  1299. self::DebugOut('changeOtherhKeFu exit4...');
  1300. return false;
  1301. }
  1302. /////////取消原有会话,开启新会话
  1303. $oldlog = self::$db->select('*')->from('ws_service_log')->where('servicelog_id=:servicelog_id ')->bindValues(['servicelog_id' => $serviceid])->orderByDESC(['servicelog_id'])->row();
  1304. if (!$oldlog) {
  1305. self::DebugOut('changeOtherhKeFu exit5...');
  1306. return false;
  1307. }
  1308. self::insertServerLog($serviceid, 5);
  1309. self::$redis->hdel(self::SERVICELOG, $serviceid);
  1310. unset($oldlog['servicelog_id']);
  1311. ///更新redis数据
  1312. $kf_info_from['user_info'] = self::ArrayDataopt($kf_info_from['user_info'], $user_info['client_id'], 0);
  1313. $kf_info_from['task'] = count($kf_info_from['user_info']);
  1314. self::$redis->hset(self::KFINFOKEY, $fromkfuid, json_encode($kf_info_from, 256));
  1315. ///////旧工单部分数据更新回库
  1316. /// 查询工单会话总数.
  1317. self:: BeginTalk($toukfid, $uid, $groupidto, 0, $user_info);
  1318. self::servicetrutoother('OUT', $fromkfuid, $toukfid, $serviceid, $uid);
  1319. $newUserInfo = json_decode(self::$redis->hget(self::USERINFOKEY, $uid), true);
  1320. self::servicetrutoother('IN', $toukfid, $fromkfuid, $newUserInfo['serverid'], $uid);
  1321. //回转接人,转接成功
  1322. Gateway::sendToCurrentClient(json_encode(['message_type' => 'trunconnect', 'data' => ['status' => 1]], 256));
  1323. // 发送给用户转接消息
  1324. Gateway::sendToClient($user_info['client_id'], json_encode(['message_type' => 'changeKeFuSuccess', 'data' => ['content' => "会话转接成功"]], 256));
  1325. self::DebugOut('changekf 转换成功!');
  1326. return;
  1327. }
  1328. //客服在线状态写组
  1329. private static function writeLogKfStatus($kf, $status, $flag = 1)
  1330. {
  1331. if ($flag == 1) {
  1332. $status = intval($status);
  1333. if ($status == 0) {
  1334. self::$db->delete('ws_kfonline')->where("uid='$kf'")->query();
  1335. } else {
  1336. $now = date('Y-m-d H:i;s');
  1337. $ip = isset($_SESSION['remotip']) ? $_SESSION['remotip'] : '';
  1338. $sql = "insert into ws_kfonline(uid,status,uptime,ip) values('$kf',$status,'$now','$ip') ON DUPLICATE KEY UPDATE status=$status,uptime='$now' ";
  1339. self::$db->query($sql);
  1340. }
  1341. } else {
  1342. self::$db->query("delete from ws_kfonline ");
  1343. }
  1344. }
  1345. public static function resetServiceLog($kfid = 0)
  1346. {
  1347. $t = time() - 24 * 3600 * 7;
  1348. $now = time();
  1349. if ($kfid) {
  1350. if ((substr($kfid, 0, 2) == 'KF')) {
  1351. $kfid = intval(substr($kfid, 2));
  1352. }
  1353. $kfid = intval($kfid);
  1354. self::$db->query("update ws_service_log set status=2,end_time=$now where start_time>=$t and kf_id=$kfid and status!=2");
  1355. self::$redis->hdel(self::KFINFOKEY, 'KF' . $kfid);
  1356. } else {
  1357. self::$redis->del(self::KFINFOKEY);
  1358. self::$redis->del(self::USERLIST);
  1359. self::$redis->del(self::USERINFOKEY);
  1360. self::$redis->del('adminList');
  1361. self::$redis->del(self::WEBSOCKALLUSER);
  1362. self::$redis->del('SERVICELOG');
  1363. self::$db->query("update ws_service_log set status=2,end_time=$now where start_time>=$t and status!=2");
  1364. }
  1365. }
  1366. public static function onWorkerStop($businessWorker)
  1367. {
  1368. if ($businessWorker->id == 1) {
  1369. self::resetServiceLog();
  1370. }
  1371. }
  1372. //用户下线通知
  1373. private static function userCloseNotice($client_id, $cuid, $group)
  1374. {
  1375. }
  1376. //踢掉同一用户的旧用户
  1377. private static function tickOlduser($uid)
  1378. {
  1379. }
  1380. private static function DebugOut($msg, $title = '', $type = 'info')
  1381. {
  1382. $config = self::$global->systemconfig;
  1383. if (!isset($config['isdebug']) || empty($config['isdebug']['systemconfig_data'])) {
  1384. return;
  1385. }
  1386. if (!is_string($msg)) {
  1387. $msg = json_encode([$msg], 256);
  1388. }
  1389. $msg = date("Y-m-d H:i:s") . ' - ' . $type . ' - ' . $title . ' - ' . $msg . "\n";
  1390. echo $msg;
  1391. }
  1392. //定时器相关
  1393. private static function TimerThing($worker)
  1394. {
  1395. // 当天的累积接入值
  1396. $key = date('Ymd') . 'total_in';
  1397. if (is_null(self::$global->$key)) {
  1398. self::$global->$key = 0;
  1399. $oldKey = date('Ymd', strtotime('-1 day')); // 删除前一天的统计值
  1400. unset(self::$global->$oldKey);
  1401. unset($oldKey, $key);
  1402. }
  1403. // 成功接入值
  1404. $key = date('Ymd') . 'success_in';
  1405. if (is_null(self::$global->$key)) {
  1406. self::$global->$key = 0;
  1407. $oldKey = date('Ymd', strtotime('-1 day')); // 删除前一天的统计值
  1408. unset(self::$global->$oldKey);
  1409. unset($oldKey, $key);
  1410. }
  1411. // 定时统计数据
  1412. if (0 == $worker->id) {
  1413. self::writeLogKfStatus(0, 0, 0);
  1414. //每5秒更新进行一次人员分配
  1415. Timer::add(5, function () {
  1416. self::userOnlineTask();
  1417. });
  1418. //每1分钟报告一次本组排列人员(如果有人排队)
  1419. Timer::add(60, function () {
  1420. self::lineup();
  1421. });
  1422. // 1分钟统计一次实时数据
  1423. Timer::add(60 * 1, function () {
  1424. self::writeLog(1);
  1425. });
  1426. // 40分钟写一次当前日期点数的log数据
  1427. Timer::add(60 * 40, function () {
  1428. self::writeLog(2);
  1429. });
  1430. //初始化.....
  1431. self::upsystemconfig();
  1432. //每3分钟更新一次系统配置文件
  1433. Timer::add(60 * 3, function () {
  1434. self::upsystemconfig();
  1435. });
  1436. // 删除前一天的统计值
  1437. Timer::add(60 * 60 * 12, function () {
  1438. $oldKey = date('Ymd', strtotime('-1 day'));
  1439. unset(self::$global->$oldKey);
  1440. });
  1441. // 管理员实时监控.
  1442. Timer::add(20, function () {
  1443. // 获取在线管理员
  1444. $adminList = self::$redis->smembers('adminList');
  1445. if ($adminList) {
  1446. self::systemMonitoring($adminList);
  1447. }
  1448. });
  1449. // 检查对话时效给出.
  1450. Timer::add(40, function () {
  1451. self::overTime();
  1452. });
  1453. self::resetServiceLog();
  1454. }
  1455. }
  1456. //调试使用
  1457. public static function mydebug($client_id, $message)
  1458. {
  1459. }
  1460. public static function MySendMsg($clientId, $msg)
  1461. {
  1462. Gateway::sendToClient($clientId, $msg);
  1463. }
  1464. //得到客服的UID字符值
  1465. public static function getkfuid($uid)
  1466. {
  1467. if (substr($uid, 0, 2) == 'KF') {
  1468. return $uid;
  1469. } else {
  1470. return 'KF' . intval($uid);
  1471. }
  1472. }
  1473. //得到客服的ID整数值
  1474. public static function getkfid($id)
  1475. {
  1476. if (strtolower(substr($id, 0, 2)) == 'kf') {
  1477. return intval(substr($id, 2));
  1478. }
  1479. return intval($id);
  1480. }
  1481. //从数组中获取参数
  1482. public static function getPars($array, $key, $default = '')
  1483. {
  1484. if (isset($array[$key])) {
  1485. return $array[$key];
  1486. }
  1487. return $default;
  1488. }
  1489. //获取在线客服信息
  1490. public static function getOnlineKfData($group = 0, $status = 0)
  1491. {
  1492. $all = self::$redis->hgetall(self::KFINFOKEY);
  1493. if (!$all) {
  1494. return false;
  1495. }
  1496. $return = [];
  1497. foreach ($all as $val) {
  1498. $now = json_decode($val, true);
  1499. if ($group) {
  1500. if ($now['group'] != $group) {
  1501. continue;
  1502. }
  1503. }
  1504. if ($status) {
  1505. if ($now['status'] != $status) {
  1506. continue;
  1507. }
  1508. }
  1509. $return[$now['id']] = $now;
  1510. }
  1511. return $return;
  1512. }
  1513. //找到在排队的用户按时间先后顺序
  1514. public static function getUselistData($group)
  1515. {
  1516. $all = self::$redis->hgetall(self::USERLIST);
  1517. if (!$all) {
  1518. return false;
  1519. }
  1520. $return = [];
  1521. foreach ($all as $val) {
  1522. $now = json_decode($val, true);
  1523. if ($group == $now['group']) {
  1524. $return[] = $now;
  1525. }
  1526. }
  1527. usort($return, function ($a, $b) {
  1528. if ($a['intime'] == $b['intime']) {
  1529. return 0;
  1530. }
  1531. return $a['intime'] > $b['intime'] ? 1 : -1;
  1532. });
  1533. return $return;
  1534. }
  1535. //对客服的用户user_info数组进行加减操作 $clientid用户连接号 opt=1添加 0删除 $serverid服务工单号
  1536. public static function ArrayDataopt($array, $clientid, $opt, $serverid = 0)
  1537. {
  1538. if (!is_array($array)) {
  1539. return [];
  1540. }
  1541. if ($opt == 0) {
  1542. if (isset($array[$clientid])) {
  1543. unset($array[$clientid]);
  1544. }
  1545. return $array;
  1546. } else {
  1547. $array[$clientid] = $serverid;
  1548. return $array;
  1549. }
  1550. }
  1551. }