Events.php 66 KB

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