Events.php 64 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811
  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 ,值为工单号
  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. if (!isset(self::$global->groupmap[$group])) {
  432. self::MySendMsg($client_id, (json_encode(['message_type' => 'reLoginErr', 'msg' => '不存在客服组....'], 256)));
  433. return true;
  434. //Gateway::closeCurrentClient();
  435. }
  436. $loginstate = self::$logic->userIsLogin($client_id, $uid, $group);
  437. if ($loginstate == 1) {
  438. self::MySendMsg($client_id, (json_encode(['message_type' => 'reLoginErr', 'msg' => '正在登陆中,请稍后...'], 256)));
  439. Gateway::closeCurrentClient();
  440. return;
  441. }
  442. $hisdata = self::$redis->hget(self::USERINFOKEY, $uid);
  443. if ($hisdata) {
  444. $hisdata = json_decode($hisdata, true);
  445. $oldclientid = $hisdata['client_id'];
  446. self::MySendMsg($oldclientid, json_encode(['type' => 'reLoginErr', 'msg' => '相同账号登陆1,本次退出'], 256));
  447. self::MySendMsg($client_id, json_encode(['type' => 'reLoginErr', 'msg' => '相同账号登陆2,本次退出'], 256));
  448. Gateway::closeClient($oldclientid);
  449. Gateway::closeCurrentClient();
  450. return;
  451. }
  452. $last = self::UserHasOldTalk($uid);
  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. 'ip' => $_SESSION['remotip'],
  473. 'serverid' => 0,
  474. 'client_id' => $client_id
  475. ];
  476. self::$redis->hset(self::USERLIST, $uid, json_encode($data, 256));
  477. self::$redis->hset(self::USERINFOKEY, $uid, json_encode($data, 256));
  478. // 写入接入值
  479. $key = date('Ymd') . 'total_in';
  480. self::$global->increment($key);
  481. // 绑定 client_id 和 uid
  482. Gateway::bindUid($client_id, $uid);
  483. $_SESSION['iskefu'] = 0;
  484. $_SESSION['uid'] = $message['uid'];
  485. // 尝试分配新会员进入服务
  486. self::userOnlineTask($group, $uid, $last, $client_id);
  487. }
  488. /**
  489. * 当用户断开连接时触发
  490. * @param int $client_id 连接id
  491. *
  492. * tips: 当服务端主动退出的时候,会出现 exit status 9.原因是:服务端主动断开之后,连接的客户端会走这个方法,而短时间内进程
  493. * 需要处理这多的逻辑,又有cas操作,导致进程退出会超时,然后会被内核杀死,从而报出错误 9.实际对真正的业务没有任何的影响。
  494. */
  495. public static function onClose($client_id)
  496. {
  497. self::$redis->hdel(self::WEBSOCKALLUSER, $client_id);
  498. $isKefuoff = isset($_SESSION['iskefu']) ? $_SESSION['iskefu'] : 0;
  499. $uid = isset($_SESSION['uid']) ? $_SESSION['uid'] : false;
  500. echo "下线:uid: $uid - cid: $client_id - iskf: $isKefuoff \n";
  501. $isAdmin = self::$redis->sismember('adminList', $client_id);
  502. if ($isAdmin) {
  503. self::$redis->srem('adminList', $client_id);
  504. }
  505. if (empty($uid)) {
  506. return true;
  507. }
  508. if ($isKefuoff) {
  509. self::serviceOffline($client_id, $uid);
  510. } else {
  511. self::guestOffline($client_id, $uid);
  512. }
  513. return true;
  514. }
  515. //客服下线了 系统调用,不能手动调用
  516. public static function serviceOffline($client_id, $uid)
  517. {
  518. $group = $_SESSION['group'];
  519. $uinfo = self::$redis->hget(self::KFINFOKEY, $uid);
  520. self::$redis->hdel(self::KFINFOKEY, $uid);
  521. $uinfo = json_decode($uinfo, true);
  522. if (empty($uinfo)) {
  523. echo "客服发生异常退出\n";
  524. return;
  525. }
  526. //$user_info = $uinfo['user_info'];
  527. $user_info = self::$redis->hgetall(self::getKfServiceKey($uid));
  528. $kfid = self::getkfid($uid);
  529. $now = time();
  530. $starttime = $now - 86400 * 7;
  531. self::$redis->hset('loginTmp:' . $uid, 'uid', time());
  532. self::$redis->expire('loginTmp:' . $uid, 5);
  533. if (!empty($user_info)) {
  534. foreach ($user_info as $val => $serverid) {
  535. self::insertServerLog($serverid, 4);
  536. self::$redis->hdel(self::SERVICELOG, intval($serverid));
  537. self::MySendMsg($val, json_encode(['message_type' => 'serviceoffline', 'msg' => '客户人员下线!'], 256));
  538. Gateway::closeClient($val);
  539. }
  540. }
  541. $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 ";
  542. echo "客服退出: " . $uid . "\n";
  543. self::$db->query($sql);
  544. self::$db->update('ws_users')->cols(array('online_status' => 0, 'online_connectid' => ''))->where('id=' . $kfid)->query();
  545. self::writeLogKfStatus($uid, 0);
  546. return;
  547. }
  548. //用户下线了 系统调用,不能手动调用
  549. public static function guestOffline($client_id, $uid)
  550. {
  551. self::$redis->hset('loginTmp:' . $uid, 'uid', time());
  552. self::$redis->expire('loginTmp:' . $uid, 3);
  553. $uid = intval($uid);
  554. $krclient_id = 0;
  555. $data = self::$redis->hget(self::USERINFOKEY, $uid);
  556. if (empty($data)) {
  557. return;
  558. }
  559. $info = json_decode($data, true);
  560. self::$redis->hdel(self::USERLIST, $uid);
  561. self::$redis->hdel(self::USERINFOKEY, $uid);
  562. if (!empty($info['kfuid'])) {
  563. $kfinfo = self::$redis->hget(self::KFINFOKEY, $info['kfuid']);
  564. if (!empty($kfinfo)) {
  565. $kfinfoArr = json_decode($kfinfo, true);
  566. $krclient_id = $kfinfoArr['client_id'];
  567. /*$kfinfoArr['user_info'] = self::ArrayDataopt($kfinfoArr['user_info'], $client_id, 0);
  568. $kfinfoArr['task'] = count($kfinfoArr['user_info']);
  569. self::$redis->hset(self::KFINFOKEY, $info['kfuid'], json_encode($kfinfoArr, 256));*/
  570. }
  571. }
  572. $chat_message = [
  573. 'message_type' => 'userClose',
  574. 'data' => [
  575. 'content' => '用户连接已断开',
  576. 'id' => $uid,
  577. 'time' => date('H:i'),
  578. ]
  579. ];
  580. $now = time();
  581. $serverid = intval($info['serverid']);
  582. if ($serverid) {
  583. $sql = "update `ws_service_log` set `status` = '3' where servicelog_id=$serverid and `status` !=2 ";
  584. self::$db->query($sql);
  585. }
  586. if ($krclient_id) {
  587. Gateway::sendToClient($krclient_id, json_encode($chat_message, 256));
  588. }
  589. return;
  590. }
  591. /**
  592. * 客服结束会话
  593. *
  594. * tips: 未有$client_id的关闭
  595. */
  596. public static function closeUser($servicelog_id, $userId, $kf_id, $groupId)
  597. {
  598. }
  599. /**
  600. * 工单结束
  601. * @param int $client_id 连接id
  602. *
  603. * tips: 当服务端主动退出的时候,会出现 exit status 9.原因是:服务端主动断开之后,连接的客户端会走这个方法,而短时间内进程
  604. * 需要处理这多的逻辑,又有cas操作,导致进程退出会超时,然后会被内核杀死,从而报出错误 9.实际对真正的业务没有任何的影响。
  605. */
  606. public static function serverClose($servicelogId, $closeBy = 0)
  607. {
  608. // 获取当前工单数据.
  609. $data = json_decode(self::$redis->HGET('SERVICELOG', $servicelogId), true);
  610. if (empty($data)) {
  611. return;
  612. }
  613. // 获取当前客服.
  614. $kfInfo = json_decode(self::$redis->HGET('KFINFO', 'KF' . $data['kf_id']), true);
  615. if (empty($kfInfo)) {
  616. return;
  617. }
  618. // 删除当前工单.
  619. self::$redis->hdel('SERVICELOG', $servicelogId);
  620. // 当前服务客服删除当前人员.
  621. //$kfUserList = self::ArrayDataopt($kfInfo['user_info'], $data['client_id'], 0);
  622. self::$redis->hdel(self::getKfServiceKey($kfInfo['id']), $data['client_id']);
  623. // 删除当前人员信息.
  624. self::$redis->hdel('USERINFO', $data['user_id']);
  625. // 当前客服所接待人员.
  626. //$kfInfo['user_info'] = $kfUserList;
  627. //$kfInfo['task'] = count($kfUserList);
  628. // 存入客服信息.
  629. self::$redis->HSET('KFINFO', 'KF' . $data['kf_id'], json_encode($kfInfo, 256));
  630. // 发送消息给用户.
  631. $chat_message = [
  632. 'message_type' => 'closeBysever',
  633. 'data' => [
  634. 'content' => '客服停止了该会话',
  635. 'time' => date('H:i'),
  636. ]
  637. ];
  638. Gateway::sendToClient($data['client_id'], json_encode($chat_message, 256));
  639. // 关闭用户连接.
  640. Gateway::closeClient($data['client_id']);
  641. // 发送消息给客服.
  642. $del_message = [
  643. 'message_type' => 'delUser',
  644. 'data' => [
  645. 'id' => $data['user_id']
  646. ]
  647. ];
  648. Gateway::sendToClient($data['kf_client_id'], json_encode($del_message, 256));
  649. // 查询工单会话总数.
  650. $chatCount = self::$db->select('count(*) as count')->from('ws_chat_log')->where("servicelog_id=$servicelogId")->row();
  651. // 将数据存入数据库.
  652. $updateServiceLogData = [
  653. 'status' => 2,
  654. 'evaluate_id' => isset($data['evaluate_id']) ? $data['evaluate_id'] : 0,
  655. 'evaluate_content' => isset($data['evaluate_content']) ? $data['evaluate_content'] : '',
  656. 'servicelog_close_type' => $closeBy,
  657. 'end_time' => time(),
  658. ];
  659. $updataAlarmData = [
  660. 'alarm_userSensitive' => $data['alarm_userSensitive'],
  661. 'alarm_serverSensitive' => $data['alarm_serverSensitive'],
  662. 'alarm_corresponding' => $data['alarm_corresponding'],
  663. 'alarm_cvtOvertime' => time() - $data['start_time'],
  664. 'alarm_respond' => $data['alarm_respond'],
  665. 'alarm_lineTime' => $data['start_time'] - $data['intime'],
  666. 'alarm_count' => $chatCount['count'],
  667. ];
  668. self::$db->update('ws_service_log')->cols($updateServiceLogData)->where("servicelog_id=$servicelogId")->query();
  669. self::$db->update('ws_alarm')->cols($updataAlarmData)->where("servicelog_id=$servicelogId")->query();
  670. }
  671. /**
  672. * 修改工单数据库数据
  673. * @param int $client_id 连接id
  674. *
  675. * tips: 当服务端主动退出的时候,会出现 exit status 9.原因是:服务端主动断开之后,连接的客户端会走这个方法,而短时间内进程
  676. * 需要处理这多的逻辑,又有cas操作,导致进程退出会超时,然后会被内核杀死,从而报出错误 9.实际对真正的业务没有任何的影响。
  677. */
  678. public static function insertServerLog($servicelogId, $closeBy = 0)
  679. {
  680. // 获取当前工单数据.
  681. $data = json_decode(self::$redis->HGET('SERVICELOG', $servicelogId), true);
  682. if (empty($data)) {
  683. return;
  684. }
  685. // 查询工单会话总数.
  686. $chatCount = self::$db->select('count(*) as count')->from('ws_chat_log')->where("servicelog_id=$servicelogId")->row();
  687. // 将数据存入数据库.
  688. $updateServiceLogData = [
  689. 'status' => 2,
  690. 'evaluate_id' => isset($data['evaluate_id']) ? $data['evaluate_id'] : 0,
  691. 'evaluate_content' => isset($data['evaluate_content']) ? $data['evaluate_content'] : '',
  692. 'servicelog_close_type' => $closeBy,
  693. 'end_time' => time(),
  694. ];
  695. $updataAlarmData = [
  696. 'alarm_userSensitive' => $data['alarm_userSensitive'],
  697. 'alarm_serverSensitive' => $data['alarm_serverSensitive'],
  698. 'alarm_corresponding' => $data['alarm_corresponding'],
  699. 'alarm_cvtOvertime' => time() - $data['start_time'],
  700. 'alarm_respond' => $data['alarm_respond'],
  701. 'alarm_lineTime' => $data['start_time'] - $data['intime'],
  702. 'alarm_count' => $chatCount['count'],
  703. ];
  704. self::$db->update('ws_service_log')->cols($updateServiceLogData)->where("servicelog_id=$servicelogId")->query();
  705. self::$db->update('ws_alarm')->cols($updataAlarmData)->where("servicelog_id=$servicelogId")->query();
  706. }
  707. /**
  708. * 有人退出
  709. * @param $group
  710. */
  711. private static function userOfflineTask($group)
  712. {
  713. }
  714. /**
  715. * 有人进入执行分配
  716. * @param $client_id
  717. * @param $group
  718. * @param $uid
  719. */
  720. private static function userOnlineTask($group = 0, $uid = 0, $last = [], $client_id = '')
  721. {
  722. $allusergkarr = self::getUserListData();
  723. if (empty($allusergkarr)) {
  724. return;
  725. }
  726. $allkfgkarr = self::getWorkKfData();
  727. if (empty($allkfgkarr)) {
  728. return;
  729. }
  730. $maxset = intval((self::$global->systemconfig)['KFMaxServices']);
  731. if ($group && $uid) {
  732. // 指定用指定组 [可能存在断线重连的情况] 如果存在旧的会话,直接连线客服和用户
  733. //否则按先到后到以及客服最大服务数限制
  734. if ($last) {
  735. self::BeginOldTalk(self::getkfuid($last['kf_id']), $uid, $last['group_id'], $last['servicelog_id']);
  736. $toOld_message = [
  737. 'message_type' => 'toOld',
  738. 'data' => [
  739. 'content' => '接入至未结束的会话'
  740. ]
  741. ];
  742. Gateway::sendToCurrentClient(json_encode($toOld_message, 256));
  743. return;
  744. }
  745. }
  746. //系统定时调用时,无组,无用户
  747. foreach ($allusergkarr as $group => $gusersArr) {
  748. if (!isset($allkfgkarr[$group]) || count($allkfgkarr[$group]) <= 0) {
  749. //所属客服组无人在线
  750. continue;
  751. }
  752. $nowkfs = $allkfgkarr[$group];
  753. $count = count($nowkfs);
  754. $i = 0;
  755. foreach ($gusersArr as $user) {
  756. if ($nowkfs[$i]['task'] > $maxset) {
  757. break;
  758. }
  759. $nowkfs[$i]['task']++;
  760. self::BeginTalk($nowkfs[$i]['id'], $user['id'], $group, 0, $user);
  761. self::$redis->hdel(self::USERLIST, $user['id']);
  762. $i++;
  763. if ($i >= $count) {
  764. $i = 0;
  765. }
  766. }
  767. }
  768. return;
  769. }
  770. //开启一个会话
  771. private static function BeginTalk($kfuid, $uid, $group, $serviceid = 0, $userInfo = false)
  772. {
  773. $serviceid = intval($serviceid);
  774. if (!$userInfo) {
  775. $userInfo = json_decode(self::$redis->hget(self::USERINFOKEY, $uid), true);
  776. }
  777. $kfinfo = json_decode(self::$redis->hget(self::KFINFOKEY, $kfuid), true);
  778. if (empty($userInfo) || empty($kfinfo)) {
  779. return false;
  780. }
  781. $server = [];
  782. $armarr = [];
  783. if ($serviceid) {
  784. $server = self::$db->select('*')->from('ws_service_log')->where("servicelog_id=$serviceid ")->row();
  785. if ($server) {
  786. $armarr = self::$db->select('*')->from('ws_alarm')->where("servicelog_id=$serviceid ")->row();
  787. }
  788. }
  789. if (empty($server)) {
  790. $array = [
  791. 'user_id' => intval($uid),
  792. 'client_id' => $userInfo['client_id'],
  793. 'user_name' => $userInfo['name'],
  794. 'user_avatar' => $userInfo['avatar'],
  795. 'user_ip' => $userInfo['ip'],
  796. 'kf_id' => self::getkfid($kfuid),
  797. 'start_time' => time(),
  798. 'group_id' => $group ? $group : $userInfo['group'],
  799. 'website' => $userInfo['website'],
  800. 'system' => $userInfo['system'],
  801. 'browse' => $userInfo['browse'],
  802. 'intime' => $userInfo['intime'],
  803. 'status' => 1,
  804. 'evaluate_id' => 0,
  805. 'servicelog_close_type' => 0
  806. ];
  807. $serviceid = self::$db->insert('ws_service_log')->cols($array)->query();
  808. $server = array_merge(['servicelog_id' => $serviceid], $array);
  809. $armid = self::$db->insert('ws_alarm')->cols(['servicelog_id' => $serviceid])->query();
  810. $armarr = self::$db->select('*')->from('ws_alarm')->where("alarm_id=$armid")->row();
  811. }
  812. $redisData = array_merge($server, $armarr, ['kf_client_id' => $kfinfo['client_id'], 'server_name' => $kfinfo['name']]);
  813. self::$redis->hset(self::SERVICELOG, $serviceid, json_encode($redisData, 256));
  814. self::setKfTasks($kfuid, $userInfo['client_id'], 1, $serviceid);
  815. $userInfo['serverid'] = $serviceid;
  816. $userInfo['kfuid'] = $kfuid;
  817. self::$redis->hset(self::USERINFOKEY, $uid, json_encode($userInfo, 256));
  818. // 通知会员发送信息绑定客服的id
  819. $noticeUser = [
  820. 'message_type' => 'connect',
  821. 'data' => [
  822. 'kf_id' => $kfuid,
  823. 'conversationId' => $serviceid,
  824. 'serverInfo' => $kfinfo,
  825. 'kf_name' => $kfinfo['job_name']
  826. ]
  827. ];
  828. self::MySendMsg($userInfo['client_id'], json_encode($noticeUser, 256));
  829. $sayHello = (self::$global->replay)['2'];
  830. if (!empty($sayHello) && 1 == $sayHello['status']) {
  831. $chat_message = [
  832. 'message_type' => 'chatMessage',
  833. 'data' => [
  834. 'id' => self::getkfuid($kfinfo['id']),
  835. 'name' => $kfinfo['name'],
  836. 'time' => date('H:i'),
  837. 'content' => $sayHello['word']
  838. ]
  839. ];
  840. self::MySendMsg($userInfo['client_id'], json_encode($chat_message, 256));
  841. unset($chat_message);
  842. }
  843. $noticeKf = [
  844. 'message_type' => 'connect',
  845. 'data' => [
  846. 'user_info' => $userInfo,
  847. 'conversationId' => $serviceid,
  848. ]
  849. ];
  850. self::MySendMsg($kfinfo['client_id'], json_encode($noticeKf, 256));
  851. unset($noticeKf);
  852. $key = date('Ymd') . 'success_in';
  853. self::$global->increment($key);
  854. return;
  855. }
  856. //连接至上一个会话
  857. private static function BeginOldTalk($kfuid, $uid, $group, $serviceid = 0, $userInfo = false)
  858. {
  859. $serviceid = intval($serviceid);
  860. $userInfo = json_decode(self::$redis->hget(self::USERINFOKEY, $uid), true);
  861. $kfinfo = json_decode(self::$redis->hget(self::KFINFOKEY, $kfuid), true);
  862. if (empty($userInfo) || empty($kfinfo)) {
  863. return false;
  864. }
  865. // 获取旧工单信息.
  866. $data = json_decode(self::$redis->HGET('SERVICELOG', $serviceid), true);
  867. if (empty($data)) {
  868. return;
  869. }
  870. // 修改工单数据.
  871. $data['user_avatar'] = $userInfo['avatar'];
  872. $data['client_id'] = $userInfo['client_id'];
  873. $data['user_ip'] = $userInfo['ip'];
  874. $data['website'] = $userInfo['website'];
  875. $data['system'] = $userInfo['system'];
  876. $data['browse'] = $userInfo['browse'];
  877. $data['status'] = $userInfo['status'];
  878. self::$redis->hset(self::SERVICELOG, $serviceid, json_encode($data, 256));
  879. // 更改用户连接客服信息
  880. $userInfo['serverid'] = $serviceid;
  881. $userInfo['kfuid'] = $kfuid;
  882. self::$redis->hset(self::USERINFOKEY, $uid, json_encode($userInfo, 256));
  883. // 更改客服连接信息.
  884. $kfinfo = json_decode(self::$redis->hget(self::KFINFOKEY, $kfuid), true);
  885. //$kfUsers = json_decode($kfinfo['user_info'], true);
  886. $kfUsers = self::$redis->hgetall(self::getKfServiceKey($kfuid));
  887. foreach ($kfUsers as $key => $value) {
  888. if ($value == $uid) {
  889. // 删除之前的当前用户连接
  890. unset($kfUsers[$key]);
  891. }
  892. }
  893. // 增加现在用户的连接到客服
  894. $kfUsers[$userInfo['client_id']] = $uid;
  895. $kfinfo['user_info'] = $kfUsers;
  896. // 将数据存入redis
  897. self::$redis->hset('KFINFO', $kfuid, json_encode($kfinfo, 256));
  898. // 通知会员发送信息绑定客服的id
  899. $noticeUser = [
  900. 'message_type' => 'connect',
  901. 'data' => [
  902. 'kf_id' => $kfuid,
  903. 'conversationId' => $serviceid,
  904. 'serverInfo' => $kfinfo,
  905. 'kf_name' => $kfinfo['job_name']
  906. ]
  907. ];
  908. self::MySendMsg($userInfo['client_id'], json_encode($noticeUser, 256));
  909. // 发送给客服用户信息.
  910. $noticeKf = [
  911. 'message_type' => 'connect',
  912. 'data' => [
  913. 'user_info' => $userInfo,
  914. 'conversationId' => $serviceid,
  915. ]
  916. ];
  917. self::MySendMsg($kfinfo['client_id'], json_encode($noticeKf, 256));
  918. unset($noticeKf);
  919. $key = date('Ymd') . 'success_in';
  920. self::$global->increment($key);
  921. return;
  922. }
  923. //用户排队数据 按组
  924. private static function getUserListData()
  925. {
  926. $alluser = self::$redis->hgetall(self::USERLIST);
  927. if (empty($alluser)) {
  928. return false;
  929. }
  930. $allusergkarr = [];
  931. foreach ($alluser as $val) {
  932. $now = json_decode($val, true);
  933. if ($now) {
  934. //用户分组后的数组
  935. $allusergkarr[$now['group']][] = $now;
  936. }
  937. }
  938. foreach ($allusergkarr as $group => $nowgroups) {
  939. usort($allusergkarr[$group], function ($a, $b) {
  940. if ($a['intime'] == $b['intime']) {
  941. return 0;
  942. }
  943. return ($a['intime'] > $b['intime']) ? 1 : -1;
  944. });
  945. }
  946. if (!$allusergkarr) {
  947. return false;
  948. }
  949. unset($alluser);
  950. return $allusergkarr;
  951. }
  952. //找到可以接工单的客服 按组
  953. private static function getWorkKfData()
  954. {
  955. $allkfs = self::$redis->hgetall(self::KFINFOKEY);
  956. if (empty($allkfs)) {
  957. return false;
  958. }
  959. $allkfgkarr = [];
  960. foreach ($allkfs as $val) {
  961. $now = json_decode($val, true);
  962. if ($now && $now['status'] == 1) {
  963. //客分组后的数组
  964. $tmp = self::getKfTasks($now['id']);
  965. $now['task'] = $tmp ? count($tmp) : 0;
  966. $allkfgkarr[$now['group']][] = $now;
  967. }
  968. }
  969. if (!$allkfgkarr) {
  970. return false;
  971. }
  972. //客服每组按任务数由小到大排序 任务相同时按时间先后顺序
  973. foreach ($allkfgkarr as $group => $nowgroups) {
  974. usort($allkfgkarr[$group], function ($a, $b) {
  975. if ($a['task'] == $b['task']) {
  976. if ($a['intime'] == $b['intime']) {
  977. return 0;
  978. }
  979. return ($a['intime'] > $b['intime']) ? 1 : -1;
  980. }
  981. return ($a['task'] > $b['task']) ? 1 : -1;
  982. });
  983. }
  984. unset($allkfs);
  985. return $allkfgkarr;
  986. }
  987. //找到用户是否有一条未关闭的会话
  988. private static function UserHasOldTalk($uid)
  989. {
  990. $uid = intval($uid);
  991. $start_time = time() - 86400;
  992. $ret = self::$db->select('*')->from('ws_service_log')->where("start_time>=$start_time and user_id=$uid and status!=2 ")->orderByDESC(['servicelog_id'])->row();
  993. return $ret;
  994. }
  995. //今天排序累加
  996. private static function todayqueuelength()
  997. {
  998. $dtype = 'user.queue.day.length';
  999. $today = date("Y-m-d");
  1000. $sret = self::$db->select('*')->from('ws_countmidtable')->where('dtype=:dtype and mdate=:mdate')->bindValues(array('dtype' => $dtype, 'mdate' => $today))->row();
  1001. if ($sret) {
  1002. self::$db->update('ws_countmidtable')->cols(array('dcontent' => intval($sret['dcontent']) + 1))->where('id=' . $sret['id'])->query();
  1003. } else {
  1004. self::$db->insert('ws_countmidtable')->cols(array(
  1005. 'dtype' => $dtype,
  1006. 'mdate' => $today,
  1007. 'datatype' => 1,
  1008. 'dcontent' => 1))->query();
  1009. }
  1010. }
  1011. //客服工单转单
  1012. private static function servicetrutoother($type, $owen, $otherkfid, $serverid, $clientuid)
  1013. {
  1014. $owen = intval(substr($owen, 2));
  1015. $otherkfid = intval(substr($otherkfid, 2));
  1016. self::$db->insert('ws_serviceturn_log')->cols(array(
  1017. 'stype' => $type,
  1018. 'uid' => $owen,
  1019. 'tuid' => $otherkfid,
  1020. 'serverid' => $serverid,
  1021. 'guestuid' => $clientuid
  1022. ))->query();
  1023. }
  1024. /**
  1025. * 给客服分配会员【均分策略】
  1026. * @param $kfList
  1027. * @param $userList
  1028. * @param $group
  1029. * @param $total
  1030. */
  1031. private static function assignmentTask($kfList, $userList, $group, $total, $uid = 0)
  1032. {
  1033. }
  1034. /**
  1035. * 获取最大的服务人数
  1036. * @return int
  1037. */
  1038. private static function getMaxServiceNum()
  1039. {
  1040. $maxNumber = self::$db->query('select `max_service` from `ws_kf_config` where `id` = 1');
  1041. if (!empty($maxNumber)) {
  1042. $maxNumber = 5;
  1043. } else {
  1044. $maxNumber = $maxNumber['0']['max_service'];
  1045. }
  1046. return $maxNumber;
  1047. }
  1048. /**
  1049. * 将内存中的数据写入统计表
  1050. * @param int $flag
  1051. */
  1052. private static function writeLog($flag = 1)
  1053. {
  1054. // 上午 8点 到 22 点开始统计
  1055. if (date('H') < 8 || date('H') > 22) {
  1056. return;
  1057. }
  1058. $inQueue_1 = self::$redis->hgetall(self::USERLIST);
  1059. $inQueue = empty($inQueue_1) ? 0 : count($inQueue_1);
  1060. $allkf = self::$redis->hgetall(self::KFINFOKEY);
  1061. $nowTalking = $onlineKf = 0;
  1062. if (!empty($allkf)) {
  1063. foreach ($allkf as $kfuid => $val) {
  1064. $tmp = json_decode($val, true);
  1065. $onlineKf++;
  1066. $nowTalking += count($tmp['user_info']);
  1067. }
  1068. }
  1069. $key = date('Ymd') . 'total_in';
  1070. $key2 = date('Ymd') . 'success_in';
  1071. $param = [
  1072. 'is_talking' => $nowTalking,
  1073. 'in_queue' => $inQueue,
  1074. 'online_kf' => $onlineKf,
  1075. 'success_in' => self::$global->$key2,
  1076. 'total_in' => self::$global->$key,
  1077. 'now_date' => date('Y-m-d')
  1078. ];
  1079. self::$db->update('ws_now_data')->cols($param)->where('id=1')->query();
  1080. if (2 == $flag) {
  1081. $param = [
  1082. 'is_talking' => $nowTalking,
  1083. 'in_queue' => $inQueue,
  1084. 'online_kf' => $onlineKf,
  1085. 'success_in' => self::$global->$key2,
  1086. 'total_in' => self::$global->$key,
  1087. 'add_date' => date('Y-m-d'),
  1088. 'add_hour' => date('H'),
  1089. 'add_minute' => date('i'),
  1090. ];
  1091. self::$db->insert('ws_service_data')->cols($param)->query();
  1092. }
  1093. unset($allkf, $nowTalking, $inQueue, $onlineKf, $key, $key2, $param);
  1094. }
  1095. /**
  1096. * 机器人问答
  1097. * @param $client_id 服务ID
  1098. * @param $message 数据
  1099. */
  1100. private static function toRobot($client_id, $message)
  1101. {
  1102. $groups_id = $message['data']['groups_id'];
  1103. $robot_name = $message['data']['robot_name'];
  1104. $robotgroups_id = $message['data']['robotgroups_id'];
  1105. // 查询问题.
  1106. $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 . "'");
  1107. $chat_message = [
  1108. 'message_type' => 'robotMessage',
  1109. //'message_type' => 'chatMessage',
  1110. 'data' => [
  1111. 'name' => '智能助手',
  1112. 'time' => date('H:i'),
  1113. 'content' => $getRobot ? $getRobot[0]['robot_content'] : 'error',
  1114. ]
  1115. ];
  1116. Gateway::sendToClient($client_id, json_encode($chat_message, 256));
  1117. }
  1118. /**
  1119. * 评价
  1120. * @param $client_id 服务ID
  1121. * @param $message 数据
  1122. */
  1123. private static function evaluate($message)
  1124. {
  1125. // 获取当前会话工单.
  1126. $data = json_decode(self::$redis->HGET('SERVICELOG', $message['conversationId']), true);
  1127. if (empty($data)) {
  1128. return;
  1129. }
  1130. $data['evaluate_id'] = $message['evaluate_id'];
  1131. $data['evaluate_content'] = $message['evaluate_content'];
  1132. self::$redis->HSET('SERVICELOG', $data['client_id'], json_encode($data, 256));
  1133. $chat_message = [
  1134. 'message_type' => 'evaluate',
  1135. 'data' => [
  1136. 'status' => 1,
  1137. 'time' => date('H:i'),
  1138. ]
  1139. ];
  1140. Gateway::sendToClient($message['client_id'], json_encode($chat_message, 256));
  1141. }
  1142. //获取系统配置
  1143. private static function upsystemconfig()
  1144. {
  1145. $systemConfigData = self::$db->query("SELECT * FROM `ws_systemconfig`");
  1146. $arr = [];
  1147. if ($systemConfigData) {
  1148. foreach ($systemConfigData as $item) {
  1149. $arr[$item['systemconfig_enName']] = $item;
  1150. }
  1151. self::$global->systemconfig = $arr;
  1152. }
  1153. $group = self::$db->query("SELECT * FROM `ws_groups`");
  1154. $arr = [];
  1155. if ($group) {
  1156. foreach ($group as $val) {
  1157. $arr[$val['id']] = $val['name'];
  1158. }
  1159. self::$global->groupmap = $arr;
  1160. }
  1161. $arr = [];
  1162. $replay = self::$db->query('select * from `ws_reply`');
  1163. if ($replay) {
  1164. foreach ($replay as $val) {
  1165. $arr[$val['id']] = $val;
  1166. }
  1167. self::$global->replay = $arr;
  1168. }
  1169. }
  1170. /**
  1171. * 超时
  1172. * @param $client_id 服务ID
  1173. * @param $message 数据
  1174. */
  1175. private static function overTime()
  1176. {
  1177. // 查询对话时效设置.
  1178. $systemConfigData = self::$db->query("SELECT `systemconfig_data`,`systemconfig_enName`,`systemconfig_content` FROM `ws_systemconfig`");
  1179. foreach ($systemConfigData as $k => $v) {
  1180. if ($v['systemconfig_enName'] == 'overtime') {
  1181. $configOvertime = $v;
  1182. } elseif ($v['systemconfig_enName'] == 'unoperated') {
  1183. $configUnoperated = $v;
  1184. }
  1185. }
  1186. // 查询未断开的工单.
  1187. $serviceLog = self::$redis->hGetall('SERVICELOG');
  1188. $setOvertime = strtotime('-' . ($configOvertime['systemconfig_data'] - 60) . ' second');
  1189. $overtime = strtotime('-' . ($configOvertime['systemconfig_data']) . ' second');
  1190. $setUnoperated = strtotime('-' . ($configUnoperated['systemconfig_data'] - 60) . ' second');
  1191. $unoperated = strtotime('-' . ($configUnoperated['systemconfig_data']) . ' second');
  1192. foreach ($serviceLog as $k => $v) {
  1193. // 无效会话关闭.如果没有说一句话.
  1194. $data = json_decode($v, true);
  1195. if (!isset($data['userLastTime'])) {
  1196. if ($data['start_time'] <= $unoperated) {
  1197. self::serverClose($k, 1);
  1198. // 如果小于设定时间前一分钟则给出提示.
  1199. } elseif ($data['start_time'] <= $setUnoperated) {
  1200. $chat_message = [
  1201. 'message_type' => 'overtime',
  1202. 'data' => [
  1203. 'content' => $configUnoperated['systemconfig_content'],
  1204. ]
  1205. ];
  1206. Gateway::sendToClient($data['client_id'], json_encode($chat_message, 256));
  1207. }
  1208. // 双方静默超时.
  1209. } elseif ($data['userLastTime'] <= $overtime && $data['serverLastTime'] <= $overtime) {
  1210. self::serverClose($k, 2);
  1211. // 如果小于设定时间前一分钟则给出提示.
  1212. } elseif ($data['userLastTime'] <= $setOvertime && $data['serverLastTime'] <= $setOvertime) {
  1213. $chat_message = [
  1214. 'message_type' => 'overtime',
  1215. 'data' => [
  1216. 'content' => $configOvertime['systemconfig_content'],
  1217. ]
  1218. ];
  1219. Gateway::sendToClient($data['client_id'], json_encode($chat_message, 256));
  1220. }
  1221. }
  1222. }
  1223. /**
  1224. * 系统监控
  1225. * @param $message 数据
  1226. */
  1227. private static function systemMonitoring($adminList)
  1228. {
  1229. // 查询正进行的工单.
  1230. $serviceLog = self::$redis->hGetall('SERVICELOG');
  1231. // 查询系统设置表.
  1232. $systemconfig = self::$db->query("SELECT `systemconfig_data`,`systemconfig_enName` FROM `ws_systemconfig` WHERE `systemconfig_enName`='verifyReturnTime' or `systemconfig_enName`='verifyAllTime'");
  1233. // 质检会话响应时长.
  1234. $returnTimeKey = array_search('verifyReturnTime', array_column($systemconfig, 'systemconfig_enName'));
  1235. $verifyReturnTime = $systemconfig[$returnTimeKey]['systemconfig_data'];
  1236. // 质检会话时长.
  1237. $allTimeKey = array_search('verifyAllTime', array_column($systemconfig, 'systemconfig_enName'));
  1238. $verifyAllTime = $systemconfig[$allTimeKey]['systemconfig_data'];
  1239. $evaluateCount = 0; // 差评总次数.
  1240. $overtimeNumber = 0; // 会话超时总次数.
  1241. $overtimeTime = []; // 每次会话超时时间.
  1242. $userSensitive = 0; // 用户敏感词报警总次数.
  1243. $serverSensitive = 0; // 客服敏感词报警总次数.
  1244. $csdNumber = 0; // 响应超时总次数.
  1245. $csdTime = []; // 每次响应超时时间.
  1246. foreach ($serviceLog as $k => $v) {
  1247. $data = json_decode($v, true);
  1248. // 工单报警次数.
  1249. $allCount = 0;
  1250. if ($data['evaluate_id'] == 3) {
  1251. $evaluateCount++; // 差评次数.
  1252. $allCount++; // 工单报警次数.
  1253. }
  1254. // 会话超时.
  1255. $duration = time() - $data['start_time'];
  1256. if ($duration > $verifyAllTime) {
  1257. $overtimeNumber++; // 会话超时总次数.
  1258. $allCount++; // 工单报警次数.
  1259. $overtimeTime[] = $duration; // 响应超时时间.
  1260. }
  1261. // 敏感词报警.
  1262. $userSensitive += $data['alarm_userSensitive'];
  1263. $allCount += $data['alarm_userSensitive'];
  1264. $serverSensitive += $data['alarm_serverSensitive'];
  1265. $allCount += $data['alarm_serverSensitive'];
  1266. // 响应超时.
  1267. if ($data['alarm_corresponding'] > $verifyReturnTime) {
  1268. $csdTime[] = $data['alarm_corresponding']; // 响应超时时间.
  1269. $csdNumber++; // 响应超时总次数.
  1270. $allCount++; // 工单报警次数.
  1271. }
  1272. $serviceLog[$k] = $data;
  1273. $serviceLog[$k]['allCount'] = $allCount; // 工单报警次数.
  1274. }
  1275. self::DebugOut([$serviceLog, $csdTime, $verifyReturnTime], 'systemMonitoring');
  1276. $chat_message = [
  1277. 'message_type' => 'monitor',
  1278. 'data' => [
  1279. 'cvtList' => $serviceLog,
  1280. 'userSensitive' => $userSensitive,
  1281. 'serverSensitive' => $serverSensitive,
  1282. 'csdNumber' => $csdNumber,
  1283. 'csdTime' => $csdTime,
  1284. 'overtimeNumber' => $overtimeNumber,
  1285. 'overtimeTime' => $overtimeTime,
  1286. 'evaluateCount' => $evaluateCount,
  1287. ]
  1288. ];
  1289. // 查询对话时效设置.
  1290. foreach ($adminList as $v) {
  1291. Gateway::sendToClient($v, json_encode($chat_message, 256));
  1292. }
  1293. }
  1294. //客户工单内部组转接
  1295. public static function changeOtherhKeFu($client_id, $smessage)
  1296. {
  1297. $message = $smessage['data'];
  1298. $groupid = isset($message['fromgroup']) ? intval($message['fromgroup']) : 0;
  1299. $groupidto = isset($message['togroup']) ? intval($message['togroup']) : 0;
  1300. $toukfid = isset($message['toukfuid']) ? $message['toukfuid'] : 0;
  1301. $fromkfuid = isset($message['fromkfuid']) ? $message['fromkfuid'] : 0;
  1302. $uid = isset($message['uid']) ? intval($message['uid']) : 0;
  1303. $word = isset($message['word']) ? $message['word'] : '';
  1304. if (empty($groupid) || empty($groupidto) || empty($toukfid) || empty($fromkfuid) || empty($uid) || ($toukfid == $fromkfuid)) {
  1305. self::DebugOut('changeOtherhKeFu exit1...');
  1306. return false;
  1307. }
  1308. if (!Gateway::isUidOnline($toukfid) || !Gateway::isUidOnline($uid)) {
  1309. self::DebugOut('changeOtherhKeFu exit2...');
  1310. return false;
  1311. }
  1312. $kf_info_from = json_decode(self::$redis->hget(self::KFINFOKEY, $fromkfuid), true);
  1313. $kf_info_to = json_decode(self::$redis->hget(self::KFINFOKEY, $toukfid), true);
  1314. $user_info = json_decode(self::$redis->hget(self::USERINFOKEY, $uid), true);
  1315. $serviceid = intval($user_info['serverid']);
  1316. if (empty($kf_info_from) || empty($kf_info_to) || empty($user_info) || empty($serviceid)) {
  1317. self::DebugOut('changeOtherhKeFu exit23...');
  1318. return false;
  1319. }
  1320. if ($kf_info_to['status'] != 1) {
  1321. self::DebugOut('changeOtherhKeFu exit4...');
  1322. return false;
  1323. }
  1324. /////////取消原有会话,开启新会话
  1325. $oldlog = self::$db->select('*')->from('ws_service_log')->where('servicelog_id=:servicelog_id ')->bindValues(['servicelog_id' => $serviceid])->orderByDESC(['servicelog_id'])->row();
  1326. if (!$oldlog) {
  1327. self::DebugOut('changeOtherhKeFu exit5...');
  1328. return false;
  1329. }
  1330. self::insertServerLog($serviceid, 5);
  1331. self::$redis->hdel(self::SERVICELOG, $serviceid);
  1332. unset($oldlog['servicelog_id']);
  1333. ///更新redis数据
  1334. $kf_info_from['user_info'] = self::ArrayDataopt($kf_info_from['user_info'], $user_info['client_id'], 0);
  1335. $kf_info_from['task'] = count($kf_info_from['user_info']);
  1336. self::$redis->hset(self::KFINFOKEY, $fromkfuid, json_encode($kf_info_from, 256));
  1337. ///////旧工单部分数据更新回库
  1338. /// 查询工单会话总数.
  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. }