Events.php 55 KB

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