Events.php 66 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841
  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::writeLogKfStatus($uid, 0);
  551. return;
  552. }
  553. //用户下线了 系统调用,不能手动调用
  554. public static function guestOffline($client_id, $uid)
  555. {
  556. self::$redis->hset('loginTmp:' . $uid, 'uid', time());
  557. self::$redis->expire('loginTmp:' . $uid, 3);
  558. $uid = intval($uid);
  559. $krclient_id = 0;
  560. $data = self::$redis->hget(self::USERINFOKEY, $uid);
  561. if (empty($data)) {
  562. return;
  563. }
  564. $info = json_decode($data, true);
  565. self::$redis->hdel(self::USERLIST, $uid);
  566. self::$redis->hdel(self::USERINFOKEY, $uid);
  567. if (!empty($info['kfuid'])) {
  568. $kfinfo = self::$redis->hget(self::KFINFOKEY, $info['kfuid']);
  569. if (!empty($kfinfo)) {
  570. $kfinfoArr = json_decode($kfinfo, true);
  571. $krclient_id = $kfinfoArr['client_id'];
  572. /*$kfinfoArr['user_info'] = self::ArrayDataopt($kfinfoArr['user_info'], $client_id, 0);
  573. $kfinfoArr['task'] = count($kfinfoArr['user_info']);
  574. self::$redis->hset(self::KFINFOKEY, $info['kfuid'], json_encode($kfinfoArr, 256));*/
  575. }
  576. }
  577. $chat_message = [
  578. 'message_type' => 'userClose',
  579. 'data' => [
  580. 'content' => '用户连接已断开',
  581. 'id' => $uid,
  582. 'time' => date('H:i'),
  583. ]
  584. ];
  585. $now = time();
  586. $serverid = intval($info['serverid']);
  587. if ($serverid) {
  588. $sql = "update `ws_service_log` set `status` = '3' where servicelog_id=$serverid and `status` !=2 ";
  589. self::$db->query($sql);
  590. }
  591. if ($krclient_id) {
  592. Gateway::sendToClient($krclient_id, json_encode($chat_message, 256));
  593. }
  594. return;
  595. }
  596. /**
  597. * 客服结束会话
  598. *
  599. * tips: 未有$client_id的关闭
  600. */
  601. public static function closeUser($servicelog_id, $userId, $kf_id, $groupId)
  602. {
  603. }
  604. /**
  605. * 工单结束
  606. * @param int $client_id 连接id
  607. *
  608. * tips: 当服务端主动退出的时候,会出现 exit status 9.原因是:服务端主动断开之后,连接的客户端会走这个方法,而短时间内进程
  609. * 需要处理这多的逻辑,又有cas操作,导致进程退出会超时,然后会被内核杀死,从而报出错误 9.实际对真正的业务没有任何的影响。
  610. */
  611. public static function serverClose($servicelogId, $closeBy = 0)
  612. {
  613. // 获取当前工单数据.
  614. $data = json_decode(self::$redis->HGET('SERVICELOG', $servicelogId), true);
  615. if (empty($data)) {
  616. return;
  617. }
  618. // 获取当前客服.
  619. $kfInfo = json_decode(self::$redis->HGET('KFINFO', 'KF' . $data['kf_id']), true);
  620. if (empty($kfInfo)) {
  621. return;
  622. }
  623. // 删除当前工单.
  624. self::$redis->hdel('SERVICELOG', $servicelogId);
  625. // 当前服务客服删除当前人员.
  626. //$kfUserList = self::ArrayDataopt($kfInfo['user_info'], $data['client_id'], 0);
  627. self::$redis->hdel(self::getKfServiceKey($kfInfo['id']), $data['client_id']);
  628. // 删除当前人员信息.
  629. self::$redis->hdel('USERINFO', $data['user_id']);
  630. // 当前客服所接待人员.
  631. //$kfInfo['user_info'] = $kfUserList;
  632. //$kfInfo['task'] = count($kfUserList);
  633. // 存入客服信息.
  634. self::$redis->HSET('KFINFO', 'KF' . $data['kf_id'], json_encode($kfInfo, 256));
  635. // 发送消息给用户.
  636. $chat_message = [
  637. 'message_type' => 'closeBysever',
  638. 'data' => [
  639. 'content' => '客服停止了该会话',
  640. 'time' => date('H:i'),
  641. ]
  642. ];
  643. Gateway::sendToClient($data['client_id'], json_encode($chat_message, 256));
  644. // 关闭用户连接.
  645. Gateway::closeClient($data['client_id']);
  646. // 发送消息给客服.
  647. $del_message = [
  648. 'message_type' => 'delUser',
  649. 'data' => [
  650. 'id' => $data['user_id']
  651. ]
  652. ];
  653. Gateway::sendToClient($data['kf_client_id'], json_encode($del_message, 256));
  654. // 查询工单会话总数.
  655. $chatCount = self::$db->select('count(*) as count')->from('ws_chat_log')->where("servicelog_id=$servicelogId")->row();
  656. // 将数据存入数据库.
  657. $updateServiceLogData = [
  658. 'status' => 2,
  659. 'evaluate_id' => isset($data['evaluate_id']) ? $data['evaluate_id'] : 0,
  660. 'evaluate_content' => isset($data['evaluate_content']) ? $data['evaluate_content'] : '',
  661. 'servicelog_close_type' => $closeBy,
  662. 'end_time' => time(),
  663. ];
  664. $updataAlarmData = [
  665. 'alarm_userSensitive' => $data['alarm_userSensitive'],
  666. 'alarm_serverSensitive' => $data['alarm_serverSensitive'],
  667. 'alarm_corresponding' => $data['alarm_corresponding'],
  668. 'alarm_cvtOvertime' => time() - $data['start_time'],
  669. 'alarm_respond' => $data['alarm_respond'],
  670. 'alarm_lineTime' => $data['start_time'] - $data['intime'],
  671. 'alarm_count' => $chatCount['count'],
  672. ];
  673. self::$db->update('ws_service_log')->cols($updateServiceLogData)->where("servicelog_id=$servicelogId")->query();
  674. self::$db->update('ws_alarm')->cols($updataAlarmData)->where("servicelog_id=$servicelogId")->query();
  675. }
  676. /**
  677. * 修改工单数据库数据
  678. * @param int $client_id 连接id
  679. *
  680. * tips: 当服务端主动退出的时候,会出现 exit status 9.原因是:服务端主动断开之后,连接的客户端会走这个方法,而短时间内进程
  681. * 需要处理这多的逻辑,又有cas操作,导致进程退出会超时,然后会被内核杀死,从而报出错误 9.实际对真正的业务没有任何的影响。
  682. */
  683. public static function insertServerLog($servicelogId, $closeBy = 0)
  684. {
  685. // 获取当前工单数据.
  686. $data = json_decode(self::$redis->HGET('SERVICELOG', $servicelogId), true);
  687. if (empty($data)) {
  688. return;
  689. }
  690. // 查询工单会话总数.
  691. $chatCount = self::$db->select('count(*) as count')->from('ws_chat_log')->where("servicelog_id=$servicelogId")->row();
  692. // 将数据存入数据库.
  693. $updateServiceLogData = [
  694. 'status' => 2,
  695. 'evaluate_id' => isset($data['evaluate_id']) ? $data['evaluate_id'] : 0,
  696. 'evaluate_content' => isset($data['evaluate_content']) ? $data['evaluate_content'] : '',
  697. 'servicelog_close_type' => $closeBy,
  698. 'end_time' => time(),
  699. ];
  700. $updataAlarmData = [
  701. 'alarm_userSensitive' => $data['alarm_userSensitive'],
  702. 'alarm_serverSensitive' => $data['alarm_serverSensitive'],
  703. 'alarm_corresponding' => $data['alarm_corresponding'],
  704. 'alarm_cvtOvertime' => time() - $data['start_time'],
  705. 'alarm_respond' => $data['alarm_respond'],
  706. 'alarm_lineTime' => $data['start_time'] - $data['intime'],
  707. 'alarm_count' => $chatCount['count'],
  708. ];
  709. self::$db->update('ws_service_log')->cols($updateServiceLogData)->where("servicelog_id=$servicelogId")->query();
  710. self::$db->update('ws_alarm')->cols($updataAlarmData)->where("servicelog_id=$servicelogId")->query();
  711. }
  712. /**
  713. * 有人退出
  714. * @param $group
  715. */
  716. private static function userOfflineTask($group)
  717. {
  718. }
  719. /**
  720. * 有人进入执行分配
  721. * @param $client_id
  722. * @param $group
  723. * @param $uid
  724. */
  725. private static function userOnlineTask($group = 0, $uid = 0, $last = [], $client_id = '')
  726. {
  727. $allusergkarr = self::getUserListData();
  728. if (empty($allusergkarr)) {
  729. return;
  730. }
  731. $allkfgkarr = self::getWorkKfData();
  732. if (empty($allkfgkarr) && !$last) {
  733. return;
  734. }
  735. $maxset = intval((self::$global->systemconfig)['KFMaxServices']);
  736. if ($group && $uid) {
  737. // 指定用指定组 [可能存在断线重连的情况] 如果存在旧的会话,直接连线客服和用户
  738. //否则按先到后到以及客服最大服务数限制
  739. if ($last) {
  740. self::BeginOldTalk(self::getkfuid($last['kf_id']), $uid, $last['group_id'], $last['servicelog_id']);
  741. // 查询工单历史会话.
  742. $serviceid = $last['servicelog_id'];
  743. $chatLog = self::$db->select('*')->from('ws_chat_log')->where("servicelog_id=$serviceid")->orderByDESC(['time_line'])->row();
  744. $toOld_message = [
  745. 'message_type' => 'toOld',
  746. 'data' => [
  747. 'chatLog' => $chatLog ?? [],
  748. 'content' => '接入至未结束的会话'
  749. ]
  750. ];
  751. Gateway::sendToCurrentClient(json_encode($toOld_message, 256));
  752. return;
  753. }
  754. }
  755. //系统定时调用时,无组,无用户
  756. foreach ($allusergkarr as $group => $gusersArr) {
  757. if (!isset($allkfgkarr[$group]) || count($allkfgkarr[$group]) <= 0) {
  758. //所属客服组无人在线
  759. continue;
  760. }
  761. $nowkfs = $allkfgkarr[$group];
  762. $count = count($nowkfs);
  763. $i = 0;
  764. foreach ($gusersArr as $user) {
  765. if ($nowkfs[$i]['task'] > $maxset) {
  766. break;
  767. }
  768. $nowkfs[$i]['task']++;
  769. self::BeginTalk($nowkfs[$i]['id'], $user['id'], $group, 0, $user);
  770. self::$redis->hdel(self::USERLIST, $user['id']);
  771. $i++;
  772. if ($i >= $count) {
  773. $i = 0;
  774. }
  775. }
  776. }
  777. return;
  778. }
  779. //开启一个会话
  780. private static function BeginTalk($kfuid, $uid, $group, $serviceid = 0, $userInfo = false)
  781. {
  782. $serviceid = intval($serviceid);
  783. if (!$userInfo) {
  784. $userInfo = json_decode(self::$redis->hget(self::USERINFOKEY, $uid), true);
  785. }
  786. $kfinfo = json_decode(self::$redis->hget(self::KFINFOKEY, $kfuid), true);
  787. if (empty($userInfo) || empty($kfinfo)) {
  788. return false;
  789. }
  790. $server = [];
  791. $armarr = [];
  792. if ($serviceid) {
  793. $server = self::$db->select('*')->from('ws_service_log')->where("servicelog_id=$serviceid ")->row();
  794. if ($server) {
  795. $armarr = self::$db->select('*')->from('ws_alarm')->where("servicelog_id=$serviceid ")->row();
  796. }
  797. }
  798. if (empty($server)) {
  799. $array = [
  800. 'user_id' => intval($uid),
  801. 'client_id' => $userInfo['client_id'],
  802. 'user_name' => $userInfo['name'],
  803. 'user_avatar' => $userInfo['avatar'],
  804. 'user_ip' => $userInfo['ip'],
  805. 'kf_id' => self::getkfid($kfuid),
  806. 'start_time' => time(),
  807. 'group_id' => $group ? $group : $userInfo['group'],
  808. 'website' => $userInfo['website'],
  809. 'system' => $userInfo['system'],
  810. 'browse' => $userInfo['browse'],
  811. 'intime' => $userInfo['intime'],
  812. 'status' => 1,
  813. 'evaluate_id' => 0,
  814. 'servicelog_close_type' => 0
  815. ];
  816. $serviceid = self::$db->insert('ws_service_log')->cols($array)->query();
  817. $server = array_merge(['servicelog_id' => $serviceid], $array);
  818. $armid = self::$db->insert('ws_alarm')->cols(['servicelog_id' => $serviceid])->query();
  819. $armarr = self::$db->select('*')->from('ws_alarm')->where("alarm_id=$armid")->row();
  820. }
  821. $redisData = array_merge($server, $armarr, ['kf_client_id' => $kfinfo['client_id'], 'server_name' => $kfinfo['name']]);
  822. self::$redis->hset(self::SERVICELOG, $serviceid, json_encode($redisData, 256));
  823. self::setKfTasks($kfuid, $userInfo['client_id'], 1, $serviceid);
  824. $userInfo['serverid'] = $serviceid;
  825. $userInfo['kfuid'] = $kfuid;
  826. self::$redis->hset(self::USERINFOKEY, $uid, json_encode($userInfo, 256));
  827. // 通知会员发送信息绑定客服的id
  828. $noticeUser = [
  829. 'message_type' => 'connect',
  830. 'data' => [
  831. 'kf_id' => $kfuid,
  832. 'conversationId' => $serviceid,
  833. 'serverInfo' => $kfinfo,
  834. 'kf_name' => $kfinfo['job_name']
  835. ]
  836. ];
  837. self::MySendMsg($userInfo['client_id'], json_encode($noticeUser, 256));
  838. $sayHello = (self::$global->replay)['2'];
  839. if (!empty($sayHello) && 1 == $sayHello['status']) {
  840. $chat_message = [
  841. 'message_type' => 'chatMessage',
  842. 'data' => [
  843. 'id' => self::getkfuid($kfinfo['id']),
  844. 'name' => $kfinfo['name'],
  845. 'time' => date('H:i'),
  846. 'content' => $sayHello['word']
  847. ]
  848. ];
  849. self::MySendMsg($userInfo['client_id'], json_encode($chat_message, 256));
  850. unset($chat_message);
  851. }
  852. $userInfo['intime'] = date("H:i", $userInfo['intime']); ///后改为只显示小时分
  853. $noticeKf = [
  854. 'message_type' => 'connect',
  855. 'data' => [
  856. 'user_info' => $userInfo,
  857. 'conversationId' => $serviceid,
  858. ]
  859. ];
  860. self::MySendMsg($kfinfo['client_id'], json_encode($noticeKf, 256));
  861. unset($noticeKf);
  862. $key = date('Ymd') . 'success_in';
  863. self::$global->increment($key);
  864. return;
  865. }
  866. //连接至上一个会话
  867. private static function BeginOldTalk($kfuid, $uid, $group, $serviceid = 0, $userInfo = false)
  868. {
  869. $serviceid = intval($serviceid);
  870. $userInfo = json_decode(self::$redis->hget(self::USERINFOKEY, $uid), true);
  871. $kfinfo = json_decode(self::$redis->hget(self::KFINFOKEY, $kfuid), true);
  872. if (empty($userInfo) || empty($kfinfo)) {
  873. return false;
  874. }
  875. // 获取旧工单信息.
  876. $data = json_decode(self::$redis->HGET('SERVICELOG', $serviceid), true);
  877. if (empty($data)) {
  878. return;
  879. }
  880. // 修改工单数据.
  881. $data['user_avatar'] = $userInfo['avatar'];
  882. $data['client_id'] = $userInfo['client_id'];
  883. $data['user_ip'] = $userInfo['ip'];
  884. $data['website'] = $userInfo['website'];
  885. $data['system'] = $userInfo['system'];
  886. $data['browse'] = $userInfo['browse'];
  887. $data['status'] = 1;
  888. self::$redis->hset(self::SERVICELOG, $serviceid, json_encode($data, 256));
  889. // 更改用户连接客服信息
  890. $userInfo['serverid'] = $serviceid;
  891. $userInfo['kfuid'] = $kfuid;
  892. self::$redis->hset(self::USERINFOKEY, $uid, json_encode($userInfo, 256));
  893. // 更改客服连接信息.
  894. $kfinfo = json_decode(self::$redis->hget(self::KFINFOKEY, $kfuid), true);
  895. $kfUsers = self::$redis->hgetall(self::getKfServiceKey($kfuid));
  896. foreach ($kfUsers as $key => $value) {
  897. if ($value == $serviceid) {
  898. // 删除之前的当前用户连接
  899. self::$redis->hdel(self::getKfServiceKey($kfuid), $key);
  900. }
  901. }
  902. self::$redis->hset(self::getKfServiceKey($kfuid), $userInfo['client_id'], $serviceid);
  903. // 通知会员发送信息绑定客服的id
  904. $noticeUser = [
  905. 'message_type' => 'connect',
  906. 'data' => [
  907. 'kf_id' => $kfuid,
  908. 'conversationId' => $serviceid,
  909. 'serverInfo' => $kfinfo,
  910. 'kf_name' => $kfinfo['job_name']
  911. ]
  912. ];
  913. self::MySendMsg($userInfo['client_id'], json_encode($noticeUser, 256));
  914. // 发送给客服用户信息.
  915. $noticeKf = [
  916. 'message_type' => 'connect',
  917. 'data' => [
  918. 'user_info' => $userInfo,
  919. 'conversationId' => $serviceid,
  920. ]
  921. ];
  922. self::MySendMsg($kfinfo['client_id'], json_encode($noticeKf, 256));
  923. unset($noticeKf);
  924. $key = date('Ymd') . 'success_in';
  925. self::$global->increment($key);
  926. return;
  927. }
  928. //用户排队数据 按组
  929. private static function getUserListData()
  930. {
  931. $alluser = self::$redis->hgetall(self::USERLIST);
  932. if (empty($alluser)) {
  933. return false;
  934. }
  935. $allusergkarr = [];
  936. foreach ($alluser as $val) {
  937. $now = json_decode($val, true);
  938. if ($now) {
  939. //用户分组后的数组
  940. $allusergkarr[$now['group']][] = $now;
  941. }
  942. }
  943. foreach ($allusergkarr as $group => $nowgroups) {
  944. usort($allusergkarr[$group], function ($a, $b) {
  945. if ($a['intime'] == $b['intime']) {
  946. return 0;
  947. }
  948. return ($a['intime'] > $b['intime']) ? 1 : -1;
  949. });
  950. }
  951. if (!$allusergkarr) {
  952. return false;
  953. }
  954. unset($alluser);
  955. return $allusergkarr;
  956. }
  957. //找到可以接工单的客服 按组
  958. private static function getWorkKfData()
  959. {
  960. $allkfs = self::$redis->hgetall(self::KFINFOKEY);
  961. if (empty($allkfs)) {
  962. return false;
  963. }
  964. $allkfgkarr = [];
  965. foreach ($allkfs as $val) {
  966. $now = json_decode($val, true);
  967. if ($now && $now['status'] == 1) {
  968. //客分组后的数组
  969. $tmp = self::getKfTasks($now['id']);
  970. $now['task'] = $tmp ? count($tmp) : 0;
  971. $allkfgkarr[$now['group']][] = $now;
  972. }
  973. }
  974. if (!$allkfgkarr) {
  975. return false;
  976. }
  977. //客服每组按任务数由小到大排序 任务相同时按时间先后顺序
  978. foreach ($allkfgkarr as $group => $nowgroups) {
  979. usort($allkfgkarr[$group], function ($a, $b) {
  980. if ($a['task'] == $b['task']) {
  981. if ($a['intime'] == $b['intime']) {
  982. return 0;
  983. }
  984. return ($a['intime'] > $b['intime']) ? 1 : -1;
  985. }
  986. return ($a['task'] > $b['task']) ? 1 : -1;
  987. });
  988. }
  989. unset($allkfs);
  990. return $allkfgkarr;
  991. }
  992. //找到用户是否有一条未关闭的会话
  993. private static function UserHasOldTalk($uid)
  994. {
  995. $uid = intval($uid);
  996. $start_time = time() - 86400;
  997. $ret = self::$db->select('*')->from('ws_service_log')->where("start_time>=$start_time and user_id=$uid and status!=2 ")->orderByDESC(['servicelog_id'])->row();
  998. return $ret;
  999. }
  1000. //今天排序累加
  1001. private static function todayqueuelength()
  1002. {
  1003. $dtype = 'user.queue.day.length';
  1004. $today = date("Y-m-d");
  1005. $sret = self::$db->select('*')->from('ws_countmidtable')->where('dtype=:dtype and mdate=:mdate')->bindValues(array('dtype' => $dtype, 'mdate' => $today))->row();
  1006. if ($sret) {
  1007. self::$db->update('ws_countmidtable')->cols(array('dcontent' => intval($sret['dcontent']) + 1))->where('id=' . $sret['id'])->query();
  1008. } else {
  1009. self::$db->insert('ws_countmidtable')->cols(array(
  1010. 'dtype' => $dtype,
  1011. 'mdate' => $today,
  1012. 'datatype' => 1,
  1013. 'dcontent' => 1))->query();
  1014. }
  1015. }
  1016. //客服工单转单
  1017. private static function servicetrutoother($type, $owen, $otherkfid, $serverid, $clientuid)
  1018. {
  1019. $owen = intval(substr($owen, 2));
  1020. $otherkfid = intval(substr($otherkfid, 2));
  1021. self::$db->insert('ws_serviceturn_log')->cols(array(
  1022. 'stype' => $type,
  1023. 'uid' => $owen,
  1024. 'tuid' => $otherkfid,
  1025. 'serverid' => $serverid,
  1026. 'guestuid' => $clientuid
  1027. ))->query();
  1028. }
  1029. /**
  1030. * 给客服分配会员【均分策略】
  1031. * @param $kfList
  1032. * @param $userList
  1033. * @param $group
  1034. * @param $total
  1035. */
  1036. private static function assignmentTask($kfList, $userList, $group, $total, $uid = 0)
  1037. {
  1038. }
  1039. /**
  1040. * 获取最大的服务人数
  1041. * @return int
  1042. */
  1043. private static function getMaxServiceNum()
  1044. {
  1045. $maxNumber = self::$db->query('select `max_service` from `ws_kf_config` where `id` = 1');
  1046. if (!empty($maxNumber)) {
  1047. $maxNumber = 5;
  1048. } else {
  1049. $maxNumber = $maxNumber['0']['max_service'];
  1050. }
  1051. return $maxNumber;
  1052. }
  1053. /**
  1054. * 将内存中的数据写入统计表
  1055. * @param int $flag
  1056. */
  1057. private static function writeLog($flag = 1)
  1058. {
  1059. // 上午 8点 到 22 点开始统计
  1060. if (date('H') < 8 || date('H') > 22) {
  1061. return;
  1062. }
  1063. $inQueue_1 = self::$redis->hgetall(self::USERLIST);
  1064. $inQueue = empty($inQueue_1) ? 0 : count($inQueue_1);
  1065. $allkf = self::$redis->hgetall(self::KFINFOKEY);
  1066. $nowTalking = $onlineKf = 0;
  1067. if (!empty($allkf)) {
  1068. foreach ($allkf as $kfuid => $val) {
  1069. $onlineKf++;
  1070. $nowTalking = 0;
  1071. }
  1072. }
  1073. $key = date('Ymd') . 'total_in';
  1074. $key2 = date('Ymd') . 'success_in';
  1075. $param = [
  1076. 'is_talking' => $nowTalking,
  1077. 'in_queue' => $inQueue,
  1078. 'online_kf' => $onlineKf,
  1079. 'success_in' => self::$global->$key2,
  1080. 'total_in' => self::$global->$key,
  1081. 'now_date' => date('Y-m-d')
  1082. ];
  1083. self::$db->update('ws_now_data')->cols($param)->where('id=1')->query();
  1084. if (2 == $flag) {
  1085. $param = [
  1086. 'is_talking' => $nowTalking,
  1087. 'in_queue' => $inQueue,
  1088. 'online_kf' => $onlineKf,
  1089. 'success_in' => self::$global->$key2,
  1090. 'total_in' => self::$global->$key,
  1091. 'add_date' => date('Y-m-d'),
  1092. 'add_hour' => date('H'),
  1093. 'add_minute' => date('i'),
  1094. ];
  1095. self::$db->insert('ws_service_data')->cols($param)->query();
  1096. }
  1097. unset($allkf, $nowTalking, $inQueue, $onlineKf, $key, $key2, $param);
  1098. }
  1099. /**
  1100. * 机器人问答
  1101. * @param $client_id 服务ID
  1102. * @param $message 数据
  1103. */
  1104. private static function toRobot($client_id, $message)
  1105. {
  1106. $groups_id = $message['data']['groups_id'];
  1107. $robot_name = $message['data']['robot_name'];
  1108. $robotgroups_id = $message['data']['robotgroups_id'];
  1109. // 查询问题.
  1110. $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 . "'");
  1111. $chat_message = [
  1112. 'message_type' => 'robotMessage',
  1113. //'message_type' => 'chatMessage',
  1114. 'data' => [
  1115. 'name' => '智能助手',
  1116. 'time' => date('H:i'),
  1117. 'content' => $getRobot ? $getRobot[0]['robot_content'] : 'error',
  1118. ]
  1119. ];
  1120. Gateway::sendToClient($client_id, json_encode($chat_message, 256));
  1121. }
  1122. /**
  1123. * 评价
  1124. * @param $client_id 服务ID
  1125. * @param $message 数据
  1126. */
  1127. private static function evaluate($message)
  1128. {
  1129. // 获取当前会话工单.
  1130. $data = json_decode(self::$redis->HGET('SERVICELOG', $message['conversationId']), true);
  1131. if (empty($data)) {
  1132. return;
  1133. }
  1134. $data['evaluate_id'] = $message['evaluate_id'];
  1135. $data['evaluate_content'] = $message['evaluate_content'];
  1136. self::$redis->HSET('SERVICELOG', $data['client_id'], json_encode($data, 256));
  1137. $chat_message = [
  1138. 'message_type' => 'evaluate',
  1139. 'data' => [
  1140. 'status' => 1,
  1141. 'time' => date('H:i'),
  1142. ]
  1143. ];
  1144. Gateway::sendToClient($message['client_id'], json_encode($chat_message, 256));
  1145. }
  1146. //获取系统配置
  1147. private static function upsystemconfig()
  1148. {
  1149. $systemConfigData = self::$db->query("SELECT * FROM `ws_systemconfig`");
  1150. $arr = [];
  1151. if ($systemConfigData) {
  1152. foreach ($systemConfigData as $item) {
  1153. $arr[$item['systemconfig_enName']] = $item;
  1154. }
  1155. self::$global->systemconfig = $arr;
  1156. }
  1157. $group = self::$db->query("SELECT * FROM `ws_groups`");
  1158. $arr = [];
  1159. if ($group) {
  1160. foreach ($group as $val) {
  1161. $arr[$val['id']] = $val['name'];
  1162. }
  1163. self::$global->groupmap = $arr;
  1164. }
  1165. $arr = [];
  1166. $replay = self::$db->query('select * from `ws_reply`');
  1167. if ($replay) {
  1168. foreach ($replay as $val) {
  1169. $arr[$val['id']] = $val;
  1170. }
  1171. self::$global->replay = $arr;
  1172. }
  1173. }
  1174. /**
  1175. * 超时
  1176. * @param $client_id 服务ID
  1177. * @param $message 数据
  1178. */
  1179. private static function overTime()
  1180. {
  1181. // 查询对话时效设置.
  1182. $systemConfigData = self::$db->query("SELECT `systemconfig_data`,`systemconfig_enName`,`systemconfig_content` FROM `ws_systemconfig`");
  1183. foreach ($systemConfigData as $k => $v) {
  1184. if ($v['systemconfig_enName'] == 'overtime') {
  1185. $configOvertime = $v;
  1186. } elseif ($v['systemconfig_enName'] == 'unoperated') {
  1187. $configUnoperated = $v;
  1188. }
  1189. }
  1190. // 查询未断开的工单.
  1191. $serviceLog = self::$redis->hGetall('SERVICELOG');
  1192. $setOvertime = strtotime('-' . ($configOvertime['systemconfig_data'] - 60) . ' second');
  1193. $overtime = strtotime('-' . ($configOvertime['systemconfig_data']) . ' second');
  1194. $setUnoperated = strtotime('-' . ($configUnoperated['systemconfig_data'] - 60) . ' second');
  1195. $unoperated = strtotime('-' . ($configUnoperated['systemconfig_data']) . ' second');
  1196. foreach ($serviceLog as $k => $v) {
  1197. // 无效会话关闭.如果没有说一句话.
  1198. $data = json_decode($v, true);
  1199. if (!isset($data['userLastTime'])) {
  1200. if ($data['start_time'] <= $unoperated) {
  1201. self::serverClose($k, 1);
  1202. // 如果小于设定时间前一分钟则给出提示.
  1203. } elseif ($data['start_time'] <= $setUnoperated) {
  1204. $chat_message = [
  1205. 'message_type' => 'overtime',
  1206. 'data' => [
  1207. 'content' => $configUnoperated['systemconfig_content'],
  1208. ]
  1209. ];
  1210. Gateway::sendToClient($data['client_id'], json_encode($chat_message, 256));
  1211. }
  1212. // 双方静默超时.
  1213. } elseif ($data['userLastTime'] <= $overtime && $data['serverLastTime'] <= $overtime) {
  1214. self::serverClose($k, 2);
  1215. // 如果小于设定时间前一分钟则给出提示.
  1216. } elseif ($data['userLastTime'] <= $setOvertime && $data['serverLastTime'] <= $setOvertime) {
  1217. $chat_message = [
  1218. 'message_type' => 'overtime',
  1219. 'data' => [
  1220. 'content' => $configOvertime['systemconfig_content'],
  1221. ]
  1222. ];
  1223. Gateway::sendToClient($data['client_id'], json_encode($chat_message, 256));
  1224. }
  1225. }
  1226. }
  1227. /**
  1228. * 系统监控
  1229. * @param $message 数据
  1230. */
  1231. private static function systemMonitoring($adminList)
  1232. {
  1233. // 查询正进行的工单.
  1234. $serviceLog = self::$redis->hGetall('SERVICELOG');
  1235. // 查询系统设置表.
  1236. $systemconfig = self::$db->query("SELECT `systemconfig_data`,`systemconfig_enName` FROM `ws_systemconfig` WHERE `systemconfig_enName`='verifyReturnTime' or `systemconfig_enName`='verifyAllTime'");
  1237. // 质检会话响应时长.
  1238. $returnTimeKey = array_search('verifyReturnTime', array_column($systemconfig, 'systemconfig_enName'));
  1239. $verifyReturnTime = $systemconfig[$returnTimeKey]['systemconfig_data'];
  1240. // 质检会话时长.
  1241. $allTimeKey = array_search('verifyAllTime', array_column($systemconfig, 'systemconfig_enName'));
  1242. $verifyAllTime = $systemconfig[$allTimeKey]['systemconfig_data'];
  1243. $evaluateCount = 0; // 差评总次数.
  1244. $overtimeNumber = 0; // 会话超时总次数.
  1245. $overtimeTime = []; // 每次会话超时时间.
  1246. $userSensitive = 0; // 用户敏感词报警总次数.
  1247. $serverSensitive = 0; // 客服敏感词报警总次数.
  1248. $csdNumber = 0; // 响应超时总次数.
  1249. $csdTime = []; // 每次响应超时时间.
  1250. foreach ($serviceLog as $k => $v) {
  1251. $data = json_decode($v, true);
  1252. // 工单报警次数.
  1253. $allCount = 0;
  1254. if ($data['evaluate_id'] == 3) {
  1255. $evaluateCount++; // 差评次数.
  1256. $allCount++; // 工单报警次数.
  1257. }
  1258. // 会话超时.
  1259. $duration = time() - $data['start_time'];
  1260. if ($duration > $verifyAllTime) {
  1261. $overtimeNumber++; // 会话超时总次数.
  1262. $allCount++; // 工单报警次数.
  1263. $overtimeTime[] = $duration; // 响应超时时间.
  1264. }
  1265. // 敏感词报警.
  1266. $userSensitive += $data['alarm_userSensitive'];
  1267. $allCount += $data['alarm_userSensitive'];
  1268. $serverSensitive += $data['alarm_serverSensitive'];
  1269. $allCount += $data['alarm_serverSensitive'];
  1270. // 响应超时.
  1271. if ($data['alarm_corresponding'] > $verifyReturnTime) {
  1272. $csdTime[] = $data['alarm_corresponding']; // 响应超时时间.
  1273. $csdNumber++; // 响应超时总次数.
  1274. $allCount++; // 工单报警次数.
  1275. }
  1276. $serviceLog[$k] = $data;
  1277. $serviceLog[$k]['allCount'] = $allCount; // 工单报警次数.
  1278. }
  1279. self::DebugOut([$serviceLog, $csdTime, $verifyReturnTime], 'systemMonitoring');
  1280. $chat_message = [
  1281. 'message_type' => 'monitor',
  1282. 'data' => [
  1283. 'cvtList' => $serviceLog,
  1284. 'userSensitive' => $userSensitive,
  1285. 'serverSensitive' => $serverSensitive,
  1286. 'csdNumber' => $csdNumber,
  1287. 'csdTime' => $csdTime,
  1288. 'overtimeNumber' => $overtimeNumber,
  1289. 'overtimeTime' => $overtimeTime,
  1290. 'evaluateCount' => $evaluateCount,
  1291. ]
  1292. ];
  1293. // 查询对话时效设置.
  1294. foreach ($adminList as $v) {
  1295. Gateway::sendToClient($v, json_encode($chat_message, 256));
  1296. }
  1297. }
  1298. //客户工单内部组转接
  1299. public static function changeOtherhKeFu($client_id, $smessage)
  1300. {
  1301. $message = $smessage['data'];
  1302. $groupid = isset($message['fromgroup']) ? intval($message['fromgroup']) : 0;
  1303. $groupidto = isset($message['togroup']) ? intval($message['togroup']) : 0;
  1304. $toukfid = isset($message['toukfuid']) ? $message['toukfuid'] : 0;
  1305. $fromkfuid = isset($message['fromkfuid']) ? $message['fromkfuid'] : 0;
  1306. $uid = isset($message['uid']) ? intval($message['uid']) : 0;
  1307. $word = isset($message['word']) ? $message['word'] : '';
  1308. if (empty($groupid) || empty($groupidto) || empty($toukfid) || empty($fromkfuid) || empty($uid) || ($toukfid == $fromkfuid)) {
  1309. self::DebugOut('changeOtherhKeFu exit1...');
  1310. return false;
  1311. }
  1312. if (!Gateway::isUidOnline($toukfid) || !Gateway::isUidOnline($uid)) {
  1313. self::DebugOut('changeOtherhKeFu exit2...');
  1314. return false;
  1315. }
  1316. $kf_info_from = json_decode(self::$redis->hget(self::KFINFOKEY, $fromkfuid), true);
  1317. $kf_info_to = json_decode(self::$redis->hget(self::KFINFOKEY, $toukfid), true);
  1318. $user_info = json_decode(self::$redis->hget(self::USERINFOKEY, $uid), true);
  1319. $serviceid = intval($user_info['serverid']);
  1320. if (empty($kf_info_from) || empty($kf_info_to) || empty($user_info) || empty($serviceid)) {
  1321. self::DebugOut('changeOtherhKeFu exit23...');
  1322. return false;
  1323. }
  1324. if ($kf_info_to['status'] != 1) {
  1325. self::DebugOut('changeOtherhKeFu exit4...');
  1326. return false;
  1327. }
  1328. /////////取消原有会话,开启新会话
  1329. $oldlog = self::$db->select('*')->from('ws_service_log')->where('servicelog_id=:servicelog_id ')->bindValues(['servicelog_id' => $serviceid])->orderByDESC(['servicelog_id'])->row();
  1330. if (!$oldlog) {
  1331. self::DebugOut('changeOtherhKeFu exit5...');
  1332. return false;
  1333. }
  1334. self::insertServerLog($serviceid, 5);
  1335. self::$redis->hdel(self::SERVICELOG, $serviceid);
  1336. unset($oldlog['servicelog_id']);
  1337. ///更新redis数据
  1338. self::updteKfTasksByservicd($fromkfuid, $serviceid, $user_info['client_id']);
  1339. self:: BeginTalk($toukfid, $uid, $groupidto, 0, $user_info);
  1340. self::servicetrutoother('OUT', $fromkfuid, $toukfid, $serviceid, $uid);
  1341. $newUserInfo = json_decode(self::$redis->hget(self::USERINFOKEY, $uid), true);
  1342. self::servicetrutoother('IN', $toukfid, $fromkfuid, $newUserInfo['serverid'], $uid);
  1343. //回转接人,转接成功
  1344. Gateway::sendToCurrentClient(json_encode(['message_type' => 'trunconnect', 'data' => ['status' => 1]], 256));
  1345. // 发送给用户转接消息
  1346. Gateway::sendToClient($user_info['client_id'], json_encode(['message_type' => 'changeKeFuSuccess', 'data' => ['content' => "会话转接成功"]], 256));
  1347. self::DebugOut('changekf 转换成功!');
  1348. return;
  1349. }
  1350. //客服在线状态写组
  1351. private static function writeLogKfStatus($kf, $status, $flag = 1)
  1352. {
  1353. if ($flag == 1) {
  1354. $status = intval($status);
  1355. if ($status == 0) {
  1356. self::$db->delete('ws_kfonline')->where("uid='$kf'")->query();
  1357. } else {
  1358. $now = date('Y-m-d H:i;s');
  1359. $ip = isset($_SESSION['remotip']) ? $_SESSION['remotip'] : '';
  1360. $sql = "insert into ws_kfonline(uid,status,uptime,ip) values('$kf',$status,'$now','$ip') ON DUPLICATE KEY UPDATE status=$status,uptime='$now' ";
  1361. self::$db->query($sql);
  1362. }
  1363. } else {
  1364. self::$db->query("delete from ws_kfonline ");
  1365. }
  1366. }
  1367. public static function resetServiceLog($kfid = 0)
  1368. {
  1369. $t = time() - 24 * 3600 * 7;
  1370. $now = time();
  1371. if ($kfid) {
  1372. if ((substr($kfid, 0, 2) == 'KF')) {
  1373. $kfid = intval(substr($kfid, 2));
  1374. }
  1375. $kfid = intval($kfid);
  1376. self::$db->query("update ws_service_log set status=2,end_time=$now where start_time>=$t and kf_id=$kfid and status!=2");
  1377. self::$redis->hdel(self::KFINFOKEY, 'KF' . $kfid);
  1378. } else {
  1379. self::$redis->del(self::KFINFOKEY);
  1380. self::$redis->del(self::USERLIST);
  1381. self::$redis->del(self::USERINFOKEY);
  1382. self::$redis->del('adminList');
  1383. self::$redis->del(self::WEBSOCKALLUSER);
  1384. self::$redis->del('SERVICELOG');
  1385. self::$db->query("update ws_service_log set status=2,end_time=$now where start_time>=$t and status!=2");
  1386. }
  1387. }
  1388. public static function onWorkerStop($businessWorker)
  1389. {
  1390. if ($businessWorker->id == 1) {
  1391. self::resetServiceLog();
  1392. }
  1393. }
  1394. //用户下线通知
  1395. private static function userCloseNotice($client_id, $cuid, $group)
  1396. {
  1397. }
  1398. //踢掉同一用户的旧用户
  1399. private static function tickOlduser($uid)
  1400. {
  1401. }
  1402. private static function DebugOut($msg, $title = '', $type = 'info')
  1403. {
  1404. $config = self::$global->systemconfig;
  1405. if (!isset($config['isdebug']) || empty($config['isdebug']['systemconfig_data'])) {
  1406. return;
  1407. }
  1408. if (!is_string($msg)) {
  1409. $msg = json_encode([$msg], 256);
  1410. }
  1411. $msg = date("Y-m-d H:i:s") . ' - ' . $type . ' - ' . $title . ' - ' . $msg . "\n";
  1412. echo $msg;
  1413. }
  1414. //定时器相关
  1415. private static function TimerThing($worker)
  1416. {
  1417. // 当天的累积接入值
  1418. $key = date('Ymd') . 'total_in';
  1419. if (is_null(self::$global->$key)) {
  1420. self::$global->$key = 0;
  1421. $oldKey = date('Ymd', strtotime('-1 day')); // 删除前一天的统计值
  1422. unset(self::$global->$oldKey);
  1423. unset($oldKey, $key);
  1424. }
  1425. // 成功接入值
  1426. $key = date('Ymd') . 'success_in';
  1427. if (is_null(self::$global->$key)) {
  1428. self::$global->$key = 0;
  1429. $oldKey = date('Ymd', strtotime('-1 day')); // 删除前一天的统计值
  1430. unset(self::$global->$oldKey);
  1431. unset($oldKey, $key);
  1432. }
  1433. // 定时统计数据
  1434. if (0 == $worker->id) {
  1435. self::writeLogKfStatus(0, 0, 0);
  1436. //每5秒更新进行一次人员分配
  1437. Timer::add(5, function () {
  1438. self::userOnlineTask();
  1439. });
  1440. //每1分钟报告一次本组排列人员(如果有人排队)
  1441. Timer::add(60, function () {
  1442. self::lineup();
  1443. });
  1444. // 1分钟统计一次实时数据
  1445. Timer::add(60 * 1, function () {
  1446. self::writeLog(1);
  1447. });
  1448. // 40分钟写一次当前日期点数的log数据
  1449. Timer::add(60 * 40, function () {
  1450. self::writeLog(2);
  1451. });
  1452. //初始化.....
  1453. self::upsystemconfig();
  1454. //每3分钟更新一次系统配置文件
  1455. Timer::add(60 * 3, function () {
  1456. self::upsystemconfig();
  1457. });
  1458. // 删除前一天的统计值
  1459. Timer::add(60 * 60 * 12, function () {
  1460. $oldKey = date('Ymd', strtotime('-1 day'));
  1461. unset(self::$global->$oldKey);
  1462. });
  1463. // 管理员实时监控.
  1464. Timer::add(20, function () {
  1465. // 获取在线管理员
  1466. $adminList = self::$redis->smembers('adminList');
  1467. if ($adminList) {
  1468. self::systemMonitoring($adminList);
  1469. }
  1470. });
  1471. // 检查对话时效给出.
  1472. Timer::add(40, function () {
  1473. self::overTime();
  1474. });
  1475. self::resetServiceLog();
  1476. }
  1477. }
  1478. //调试使用
  1479. public static function mydebug($client_id, $message)
  1480. {
  1481. }
  1482. public static function MySendMsg($clientId, $msg)
  1483. {
  1484. Gateway::sendToClient($clientId, $msg);
  1485. }
  1486. //得到客服的UID字符值
  1487. public static function getkfuid($uid)
  1488. {
  1489. if (substr($uid, 0, 2) == 'KF') {
  1490. return $uid;
  1491. } else {
  1492. return 'KF' . intval($uid);
  1493. }
  1494. }
  1495. //得到客服的ID整数值
  1496. public static function getkfid($id)
  1497. {
  1498. if (strtolower(substr($id, 0, 2)) == 'kf') {
  1499. return intval(substr($id, 2));
  1500. }
  1501. return intval($id);
  1502. }
  1503. //从数组中获取参数
  1504. public static function getPars($array, $key, $default = '')
  1505. {
  1506. if (isset($array[$key])) {
  1507. return $array[$key];
  1508. }
  1509. return $default;
  1510. }
  1511. //获取在线客服信息
  1512. public static function getOnlineKfData($group = 0, $status = 0)
  1513. {
  1514. $all = self::$redis->hgetall(self::KFINFOKEY);
  1515. if (!$all) {
  1516. return false;
  1517. }
  1518. $return = [];
  1519. foreach ($all as $val) {
  1520. $now = json_decode($val, true);
  1521. if ($group) {
  1522. if ($now['group'] != $group) {
  1523. continue;
  1524. }
  1525. }
  1526. if ($status) {
  1527. if ($now['status'] != $status) {
  1528. continue;
  1529. }
  1530. }
  1531. $return[$now['id']] = $now;
  1532. }
  1533. return $return;
  1534. }
  1535. //找到在排队的用户按时间先后顺序
  1536. public static function getUselistData($group)
  1537. {
  1538. $all = self::$redis->hgetall(self::USERLIST);
  1539. if (!$all) {
  1540. return false;
  1541. }
  1542. $return = [];
  1543. foreach ($all as $val) {
  1544. $now = json_decode($val, true);
  1545. if ($group == $now['group']) {
  1546. $return[] = $now;
  1547. }
  1548. }
  1549. usort($return, function ($a, $b) {
  1550. if ($a['intime'] == $b['intime']) {
  1551. return 0;
  1552. }
  1553. return $a['intime'] > $b['intime'] ? 1 : -1;
  1554. });
  1555. return $return;
  1556. }
  1557. //对客服的用户user_info数组进行加减操作 $clientid用户连接号 opt=1添加 0删除 $serverid服务工单号
  1558. public static function ArrayDataopt($array, $clientid, $opt, $serverid = 0)
  1559. {
  1560. if (!is_array($array)) {
  1561. return [];
  1562. }
  1563. if ($opt == 0) {
  1564. if (isset($array[$clientid])) {
  1565. unset($array[$clientid]);
  1566. }
  1567. return $array;
  1568. } else {
  1569. $array[$clientid] = $serverid;
  1570. return $array;
  1571. }
  1572. }
  1573. //调试使用
  1574. public static function debug($dataArray)
  1575. {
  1576. }
  1577. //客服的工单hash健名
  1578. public static function getKfServiceKey($kfuid)
  1579. {
  1580. return self::KFSERVICES . ':' . $kfuid;
  1581. }
  1582. //获取客服所有连接信息及工单信息
  1583. public static function getKfTasks($kfuid)
  1584. {
  1585. $all = self::$redis->hgetall(self::getKfServiceKey($kfuid));
  1586. if (empty($r)) {
  1587. return false;
  1588. }
  1589. return $all;
  1590. }
  1591. //设置或删除客服的连接 opt==0删除 1添加
  1592. public static function setKfTasks($kfuid, $clientid, $opt = 0, $serviceid = 0)
  1593. {
  1594. $k = self::getKfServiceKey($kfuid);
  1595. if ($opt == 0) {
  1596. self::$redis->hdel($k, $clientid);
  1597. return;
  1598. }
  1599. self::$redis->hset($k, $clientid, $serviceid);
  1600. }
  1601. //有旧单时,更新连接ID
  1602. public static function updteKfTasksByservicd($kfuid, $serciceid, $newclientid, $opt = 1)
  1603. {
  1604. $tkey = self::getKfServiceKey($kfuid);
  1605. $all = self::getKfTasks($kfuid);
  1606. if ($opt == 1) {
  1607. if (empty($all)) {
  1608. self::$redis->hset($tkey, $newclientid, $serciceid);
  1609. return;
  1610. }
  1611. foreach ($all as $cid => $nowserverid) {
  1612. if ($nowserverid == $serciceid) {
  1613. self::$redis->hdel(self::getKfServiceKey($kfuid), $cid);
  1614. }
  1615. }
  1616. self::$redis->hset($tkey, $newclientid, $serciceid);
  1617. return true;
  1618. } else {
  1619. if (empty($all)) {
  1620. return;
  1621. }
  1622. foreach ($all as $cid => $nowserverid) {
  1623. if ($nowserverid == $serciceid) {
  1624. self::$redis->hdel(self::getKfServiceKey($kfuid), $cid);
  1625. }
  1626. }
  1627. return true;
  1628. }
  1629. }
  1630. }