Events.php 80 KB

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