Events.php 58 KB

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