Events.php 59 KB

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