Events.php 64 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778
  1. <?php
  2. /**
  3. * This file is part of workerman.
  4. *
  5. * Licensed under The MIT License
  6. * For full copyright and license information, please see the MIT-LICENSE.txt
  7. * Redistributions of files must retain the above copyright notice.
  8. *
  9. * @author walkor<walkor@workerman.net>
  10. * @copyright walkor<walkor@workerman.net>
  11. * @link http://www.workerman.net/
  12. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  13. */
  14. /**
  15. * 用于检测业务代码死循环或者长时间阻塞等问题
  16. * 如果发现业务卡死,可以将下面declare打开(去掉//注释),并执行php start.php reload
  17. * 然后观察一段时间workerman.log看是否有process_timeout异常
  18. */
  19. //declare(ticks=1);
  20. use \GatewayWorker\Lib\Gateway;
  21. use Workerman\Lib\Timer;
  22. use Workerman\Worker;
  23. /**
  24. * 主逻辑
  25. * 主要是处理 onConnect onMessage onClose 三个方法
  26. * onConnect 和 onClose 如果不需要可以不用实现并删除
  27. */
  28. class Events
  29. {
  30. /**
  31. * 新建一个类的静态成员,用来保存数据库实例
  32. */
  33. public static $db = null;
  34. public static $global = null;
  35. public static $redis = null;
  36. public static $logic = null;
  37. const KFINFOKEY = 'KFINFO'; //客服信息hash表
  38. const USERINFOKEY = 'USERINFO'; //用户信息hash表
  39. const USERLIST = 'USERLIST'; //用户排队表
  40. const SERVICELOG = 'SERVICELOG'; //工单信息
  41. const WEBSOCKALLUSER = 'WEBSOCKALLUSER'; //所有连接
  42. /**
  43. * 进程启动后初始化数据库连接
  44. */
  45. public static function onWorkerStart($worker)
  46. {
  47. include_once(__DIR__ . DIRECTORY_SEPARATOR . "Mlogic.php");
  48. self::$logic = Mlogic::GetInstance();
  49. self::$db = self::$logic->getDb();
  50. self::$redis = self::$logic->getRedis();
  51. self::$global = self::$logic->getGlbData();
  52. self::TimerThing($worker);
  53. }
  54. /**
  55. * 每分钟定时向客服发送一次排队情况
  56. */
  57. public static function lineup()
  58. {
  59. $group = self::$global->groupmap;
  60. foreach ($group as $groupid => $gname) {
  61. $users = self::getUselistData($groupid);
  62. if (!empty($users)) {
  63. Gateway::sendToGroup('group_' . $groupid, json_encode(['type' => 'lineupCount', count($users)], 256));
  64. }
  65. }
  66. }
  67. /**
  68. * 当客户端连接时触发
  69. * 如果业务不需此回调可以删除onConnect
  70. *
  71. * @param int $client_id 连接id
  72. */
  73. public static function onConnect($client_id)
  74. {
  75. // 检测是否开启自动应答
  76. $sayHello = self::$global->replay['1'];
  77. if (!empty($sayHello) && 1 == $sayHello['status']) {
  78. $hello = [
  79. 'message_type' => 'helloMessage',
  80. 'data' => [
  81. 'name' => '智能助手',
  82. 'time' => date('H:i'),
  83. 'content' => $sayHello['word']
  84. ]
  85. ];
  86. Gateway::sendToClient($client_id, json_encode($hello, 256));
  87. unset($hello);
  88. }
  89. unset($sayHello);
  90. // 检测是否开启广告
  91. $advertisement = self::$db->query('select * from `ws_advertisement` where `advertisement_status` = 1');
  92. if (!empty($advertisement)) {
  93. $chat_message = [
  94. 'message_type' => 'advertisement',
  95. 'data' => $advertisement
  96. ];
  97. Gateway::sendToClient($client_id, json_encode($chat_message, 256));
  98. unset($chat_message);
  99. }
  100. unset($advertisement);
  101. self::$redis->hset(self::WEBSOCKALLUSER, $client_id, json_encode(array_merge($_SERVER, ['time' => date('H:i:s')])));
  102. }
  103. /**
  104. * 当客户端发来消息时触发
  105. * @param int $client_id 连接id
  106. * @param mixed $message 具体消息
  107. */
  108. public static function onMessage($client_id, $message)
  109. {
  110. if ($message == '{"type":"ping"}') {
  111. Gateway::sendToCurrentClient('{"type":"pong"}');
  112. return;
  113. } else {
  114. self::DebugOut($message, "OnMessage");
  115. }
  116. //echo(Gateway::getAllClientCount());
  117. $message = json_decode($message, true);
  118. if (isset($message['type'])) {
  119. switch ($message['type']) {
  120. case 'mydebug':
  121. self::mydebug($client_id, $message['data']);
  122. break;
  123. // 管理员初始化
  124. case 'adminInit':
  125. $token = $message['token'];
  126. self::adminInit($client_id, $token);
  127. break;
  128. // 客服初始化
  129. case 'init':
  130. $data = $message['data'];
  131. self::Kfinit($client_id, $data);
  132. break;
  133. // 顾客初始化
  134. case 'userInit';
  135. $data = $message['data'];
  136. self::userInitEnt($client_id, $data);
  137. break;
  138. //在线客服信息
  139. case 'getkfonlines':
  140. Gateway::sendToCurrentClient(json_encode(self::getkfonlines(), 256));
  141. break;
  142. //客服获取用户详细信息
  143. case 'kfgetuserinfo':
  144. $tmp_id = isset($message['data']['id']) ? $message['data']['id'] : 0;
  145. self::kfgetuserinfo($client_id, intval($tmp_id));
  146. break;
  147. // 客服聊天
  148. case 'chatMessage':
  149. self::chatMessage($message['data']);
  150. break;
  151. // 机器人问答.
  152. case 'toRobot':
  153. self::toRobot($client_id, $message);
  154. break;
  155. // 评价.
  156. case 'evaluate':
  157. self::evaluate($message['data']);
  158. break;
  159. // 客服关闭会话.
  160. case 'kfCloseUser':
  161. self::serverClose($message['data']['conversationId'], 3);
  162. break;
  163. // 客服更改状态.
  164. case 'kfOnline':
  165. self::KFStatusCg($client_id, $message);
  166. break;
  167. case 'changeOtherhKeFu';
  168. self::changeOtherhKeFu($client_id, $message);
  169. break;
  170. // 弹出评价.
  171. case 'getEvaluate';
  172. self::getEvaluate($message['data']);
  173. break;
  174. }
  175. }
  176. return true;
  177. }
  178. // 弹出评价.
  179. public static function getEvaluate($message)
  180. {
  181. // 获取当前会话工单.
  182. $data = json_decode(self::$redis->HGET('SERVICELOG', $message['conversationId']), true);
  183. if (empty($data)) {
  184. return;
  185. }
  186. $chat_message = [
  187. 'message_type' => 'getEvaluate',
  188. 'data' => [
  189. 'content' => '欢迎你的咨询,请对我们的服务做出评价',
  190. ]
  191. ];
  192. Gateway::sendToClient($data['client_id'], json_encode($chat_message, 256));
  193. }
  194. //客服聊天
  195. public static function chatMessage($message)
  196. {
  197. // 获取当前会话工单.
  198. $data = json_decode(self::$redis->HGET('SERVICELOG', $message['conversationId']), true);
  199. if (empty($data)) {
  200. return;
  201. }
  202. $chat_message = [
  203. 'message_type' => 'chatMessage',
  204. 'data' => [
  205. 'name' => $message['from_name'],
  206. 'id' => $message['from_id'],
  207. 'time' => date('H:i'),
  208. 'content' => $message['content'],
  209. ]
  210. ];
  211. // 是否为第一次回复.
  212. if (isset($message['isFirst']) && $message['isFirst']) {
  213. $data['alarm_corresponding'] = time() - $data['start_time'];
  214. $data['alarm_respond'] = 2;
  215. }
  216. // 发送消息.
  217. if (substr($message['from_id'], 0, 2) === 'KF') {
  218. // 统计敏感词.
  219. $data['alarm_serverSensitive'] += $message['sensitiveNumber'];
  220. $data['serverLastTime'] = time();
  221. Gateway::sendToClient($data['client_id'], json_encode($chat_message, 256));
  222. } else {
  223. // 统计敏感词.
  224. $data['alarm_userSensitive'] += $message['sensitiveNumber'];
  225. $data['userLastTime'] = time();
  226. Gateway::sendToClient($data['kf_client_id'], json_encode($chat_message, 256));
  227. }
  228. // 返回当前时间
  229. $chat_message = [
  230. 'message_type' => 'webTime',
  231. 'data' => [
  232. 'webTime' => date('H:i'),
  233. ]
  234. ];
  235. Gateway::sendToCurrentClient(json_encode($chat_message, 256));
  236. // 保存修改后的工单信息.
  237. self::$redis->HSET('SERVICELOG', $message['conversationId'], json_encode($data, 256));
  238. // 聊天信息入库
  239. $insertChatData = [
  240. 'from_id' => $message['from_id'],
  241. 'from_name' => $message['from_name'],
  242. 'to_id' => $message['to_id'],
  243. 'to_name' => $message['to_name'],
  244. 'content' => $message['content'],
  245. 'servicelog_id' => $message['conversationId'],
  246. 'time_line' => time()
  247. ];
  248. self::$db->insert('ws_chat_log')->cols($insertChatData)->query();
  249. }
  250. //得到一个用户详细信息
  251. public static function kfgetuserinfo($clientid, $id)
  252. {
  253. $ret = self::$db->select('*')->from('ws_account')->where('id=:id')->bindValues(['id' => $id])->row();
  254. Gateway::sendToClient($clientid, json_encode(['message_type' => 'userdetailinfo', 'data' => $ret]));
  255. return;
  256. }
  257. //获取在线客服列表
  258. public static function getkfonlines()
  259. {
  260. $return = [
  261. 'message_type' => 'onlinekfs',
  262. 'data' => [],
  263. ];
  264. $nowkfid = isset($_SESSION['uid']) ? $_SESSION['uid'] : 0;
  265. $fromgrouupid = isset($_SESSION['group']) ? $_SESSION['group'] : 0;
  266. if (empty($fromgrouupid) || empty($nowkfid)) {
  267. return $return;
  268. }
  269. $online = self::getOnlineKfData(0, 1);
  270. if (empty($online)) {
  271. return $return;
  272. }
  273. $groupnamemap = self::$global->groupmap;
  274. $ret = [];
  275. foreach ($online as $uinfo) {
  276. if ($nowkfid == $uinfo['id']) {
  277. continue;
  278. }
  279. $ret[] = ['groupid' => $uinfo['group'], 'groupname' => $groupnamemap[$uinfo['group']], 'kfuid' => $uinfo['id'], 'kfname' => $uinfo['name'], 'kfjobname' => $uinfo['job_name']];
  280. }
  281. $return['data'] = $ret;
  282. return $return;
  283. }
  284. public static function KFStatusCg($client_id, $message)
  285. {
  286. if (!isset($_SESSION['iskefu']) || $_SESSION['iskefu'] != 1) {
  287. return;
  288. }
  289. $userId = $message['data']['uid'];
  290. $status = intval($message['data']['status']);
  291. if (!in_array($status, [1, 2, 3])) {
  292. return false;
  293. }
  294. $oldstatus = '';
  295. $kfinfo = self::$redis->hget(self::KFINFOKEY, $userId);
  296. if (empty($kfinfo)) {
  297. return false;
  298. }
  299. $kfinfo = json_decode($kfinfo, true);
  300. if (!$kfinfo) {
  301. return false;
  302. }
  303. if ($kfinfo['status'] != $status) {
  304. $oldstatus = $kfinfo['status'];
  305. $kfinfo['status'] = $status;
  306. self::$redis->hset(self::KFINFOKEY, $userId, json_encode($kfinfo, 256));
  307. }
  308. self::writeLogKfStatus($userId, $status);
  309. Gateway::sendToCurrentClient(json_encode(['message_type' => 'cgstatus', 'data' => ['new_status' => $status, 'old_status' => $oldstatus]]));
  310. return;
  311. }
  312. //获取某个用户全部信息
  313. public static function getClientIndo($id)
  314. {
  315. $ret = self::$db->from('ws_accounts')->select("*")->where(['id' => $id])->row();
  316. return $ret;
  317. }
  318. //客服接入sock,及初始化
  319. public static function Kfinit($client_id, $message)
  320. {
  321. $uid = self::getPars($message, 'uid');
  322. $group = intval(self::getPars($message, 'group', 0));
  323. if (empty($uid) || empty($group) || !isset(self::$global->groupmap[$group])) {
  324. self::MySendMsg($client_id, json_encode(["message_type" => 'checkfalse', 'data' => "客服登陆参数错误"], 256));
  325. Gateway::closeCurrentClient();
  326. return;
  327. }
  328. $loginstate = self::$logic->userIsLogin($client_id, $uid, $group);
  329. if ($loginstate == 1) {
  330. self::MySendMsg($client_id, (json_encode(['message_type' => 'reLoginErr', 'msg' => '正在登陆中,请稍后...'], 256)));
  331. Gateway::closeClient($client_id);
  332. return;
  333. }
  334. //客服登陆验证 不符合的直接断掉
  335. $kfinfo = self::KfloginCheck($client_id, $message);
  336. if (empty($kfinfo)) {
  337. self::MySendMsg($client_id, json_encode(["message_type" => 'checkfalse', 'data' => "验证失败"], 256));
  338. Gateway::closeCurrentClient();
  339. return true;
  340. } elseif ($kfinfo['status'] != 1) {
  341. self::MySendMsg($client_id, json_encode(["message_type" => 'checkfalse', 'data' => "禁用中..."], 256));
  342. Gateway::closeCurrentClient();
  343. return true;
  344. }
  345. if ($loginstate == 2) {
  346. $oldcontids = Gateway::getClientIdByUid($uid);
  347. Gateway::sendToClient($oldcontids['0'], (json_encode(['message_type' => 'reLoginErr', 'msg' => '你的账号在其它登陆,本次下线'], 256)));
  348. Gateway::closeClient($oldcontids['0']);
  349. sleep(2);
  350. }
  351. self::$redis->hset('loginTmp:' . $uid, 'uid', time());
  352. self::$redis->expire('loginTmp:' . $uid, 5);
  353. $newinfo =
  354. [
  355. 'id' => 'KF' . $kfinfo['id'],
  356. 'name' => $kfinfo['user_name'],
  357. 'job_name' => $kfinfo['user_job_number'],
  358. 'avatar' => $kfinfo['user_avatar'],
  359. 'group' => $group,
  360. 'client_id' => $client_id,
  361. 'task' => 0,
  362. 'intime' => time(),
  363. 'signature' => $kfinfo['signature'],
  364. 'status' => 2, // 1为在线(接收分配、接收消息)2为隐身(不接收分配、只接收消息)3、休息
  365. 'user_info' => [], //在会话的用户cid key为clientid ,值为工单号
  366. ];
  367. self::$redis->hset(self::KFINFOKEY, $uid, json_encode($newinfo, 256));
  368. $_SESSION['info'] = $newinfo;
  369. // 绑定 client_id 和 uid
  370. Gateway::bindUid($client_id, $message['uid']);
  371. $_SESSION['group'] = $message['group'];
  372. $_SESSION['iskefu'] = 1;
  373. $_SESSION['uid'] = $message['uid'];
  374. $_SESSION['name'] = $message['name'];
  375. Gateway::joinGroup($client_id, 'group_' . $message['group']);
  376. $chat_message = [
  377. 'message_type' => 'loginSuccess',
  378. ];
  379. self::MySendMsg($client_id, json_encode($chat_message, 256));
  380. unset($chat_message);
  381. self::writeLogKfStatus($message['uid'], 2);
  382. return;
  383. }
  384. /**
  385. * 管理员登陆验证
  386. * @param $client_id 服务ID
  387. * @param $message 数据
  388. */
  389. public static function adminInit($client_id, $token)
  390. {
  391. // 查询token是否存在.
  392. $systemConfigData = self::$db->query("SELECT `id` FROM `ws_admins` where `token`= '$token'");
  393. if ($systemConfigData) {
  394. self::$redis->sadd('adminList', $client_id);
  395. self::systemMonitoring([$client_id]);
  396. } else {
  397. $chat_message = [
  398. 'message_type' => 'tips',
  399. 'data' => '管理员不存在'
  400. ];
  401. Gateway::sendToClient($client_id, json_encode($chat_message, 256));
  402. Gateway::closeClient($client_id);
  403. }
  404. }
  405. //客服登陆验证
  406. public static function KfloginCheck($client, $messageArray)
  407. {
  408. $uid = isset($messageArray['uid']) ? $messageArray['uid'] : '';
  409. $token = isset($messageArray['token']) ? $messageArray['token'] : '';
  410. if (empty($uid) || empty($token)) {
  411. return false;
  412. }
  413. $expire_time_vali = time() - 60 * 60 * 24;
  414. $kfid = intval(substr($uid, 2));
  415. $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();
  416. if ($ret) {
  417. self::$db->update('ws_users')->cols(array('online_status' => 1, 'online_connectid' => $client))->where('id=' . $kfid)->query();
  418. return $ret;
  419. }
  420. return false;
  421. }
  422. //用户发送邦定用户事件
  423. public static function userInitEnt($client_id, $message)
  424. {
  425. $uid = intval($message['uid']);
  426. $group = intval($message['group']);
  427. $last = self::UserHasOldTalk($uid);
  428. if (!isset(self::$global->groupmap[$group])&&!$last) {
  429. self::MySendMsg($client_id, (json_encode(['message_type' => 'reLoginErr', 'msg' => '不存在客服组....'], 256)));
  430. return true;
  431. //Gateway::closeCurrentClient();
  432. }
  433. $loginstate = self::$logic->userIsLogin($client_id, $uid, $group);
  434. if ($loginstate == 1) {
  435. self::MySendMsg($client_id, (json_encode(['message_type' => 'reLoginErr', 'msg' => '正在登陆中,请稍后...'], 256)));
  436. Gateway::closeCurrentClient();
  437. return;
  438. }
  439. $hisdata = self::$redis->hget(self::USERINFOKEY, $uid);
  440. if ($hisdata) {
  441. $hisdata = json_decode($hisdata, true);
  442. $oldclientid = $hisdata['client_id'];
  443. self::MySendMsg($oldclientid, json_encode(['type' => 'reLoginErr', 'msg' => '相同账号登陆,本次退出'], 256));
  444. self::MySendMsg($client_id, json_encode(['type' => 'reLoginErr', 'msg' => '相同账号登陆,本次退出'], 256));
  445. Gateway::closeClient($oldclientid);
  446. Gateway::closeCurrentClient();
  447. return;
  448. }
  449. $onlinekf = self::getOnlineKfData($group, 1);
  450. if (empty($onlinekf)&&empty($last)) {
  451. Gateway::sendToClient($client_id, json_encode(['message_type' => 'notice', 'content' => '暂时没有客服上班,请稍后再咨询。'], 256));
  452. //Gateway::closeClient($client_id);
  453. return;
  454. }
  455. self::$redis->hset('loginTmp:' . $uid, 'uid', time());
  456. self::$redis->expire('loginTmp:' . $uid, 5);
  457. $data = [
  458. 'id' => $uid,
  459. 'name' => $message['name'],
  460. 'avatar' => $message['avatar'],
  461. 'website' => $_SESSION['origin'],//$message['website'],
  462. 'browse' => Gateway::browse_info(),
  463. 'system' => Gateway::get_os(),//$message['system'],
  464. 'ip' => isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '',//message['ip'],
  465. 'group' => $message['group'],
  466. 'intime' => time(),
  467. 'kfuid' => '',
  468. 'serverid' => 0,
  469. 'client_id' => $client_id
  470. ];
  471. if ($last) {
  472. $data['group'] = $last['group_id'];
  473. $data['intime'] = $last['intime'];
  474. $data['kfuid'] = $last['kf_id'];
  475. $data['serverid'] = $last['servicelog_id'];
  476. }
  477. self::$redis->hset(self::USERLIST, $uid, json_encode($data, 256));
  478. self::$redis->hset(self::USERINFOKEY, $uid, json_encode($data, 256));
  479. // 写入接入值
  480. $key = date('Ymd') . 'total_in';
  481. self::$global->increment($key);
  482. // 绑定 client_id 和 uid
  483. Gateway::bindUid($client_id, $uid);
  484. $_SESSION['iskefu'] = 0;
  485. $_SESSION['uid'] = $message['uid'];
  486. // 尝试分配新会员进入服务
  487. self::userOnlineTask($group, $uid, $last, $client_id);
  488. }
  489. /**
  490. * 当用户断开连接时触发
  491. * @param int $client_id 连接id
  492. *
  493. * tips: 当服务端主动退出的时候,会出现 exit status 9.原因是:服务端主动断开之后,连接的客户端会走这个方法,而短时间内进程
  494. * 需要处理这多的逻辑,又有cas操作,导致进程退出会超时,然后会被内核杀死,从而报出错误 9.实际对真正的业务没有任何的影响。
  495. */
  496. public static function onClose($client_id)
  497. {
  498. self::$redis->hdel(self::WEBSOCKALLUSER, $client_id);
  499. $isKefuoff = isset($_SESSION['iskefu']) ? $_SESSION['iskefu'] : 0;
  500. $uid = isset($_SESSION['uid']) ? $_SESSION['uid'] : false;
  501. echo "下线:uid: $uid - cid: $client_id - iskf: $isKefuoff \n";
  502. $isAdmin = self::$redis->sismember('adminList', $client_id);
  503. if ($isAdmin) {
  504. self::$redis->srem('adminList', $client_id);
  505. }
  506. if (empty($uid)) {
  507. return true;
  508. }
  509. if ($isKefuoff) {
  510. self::serviceOffline($client_id, $uid);
  511. } else {
  512. self::guestOffline($client_id, $uid);
  513. }
  514. return true;
  515. }
  516. //客服下线了 系统调用,不能手动调用
  517. public static function serviceOffline($client_id, $uid)
  518. {
  519. $group = $_SESSION['group'];
  520. $uinfo = self::$redis->hget(self::KFINFOKEY, $uid);
  521. self::$redis->hdel(self::KFINFOKEY, $uid);
  522. $uinfo = json_decode($uinfo, true);
  523. if (empty($uinfo)) {
  524. echo "客服发生异常退出\n";
  525. return;
  526. }
  527. $user_info = $uinfo['user_info'];
  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. // 删除当前人员信息.
  623. self::$redis->hdel('USERINFO', $data['user_id']);
  624. // 当前客服所接待人员.
  625. $kfInfo['user_info'] = $kfUserList;
  626. $kfInfo['task'] = count($kfUserList);
  627. // 存入客服信息.
  628. self::$redis->HSET('KFINFO', 'KF' . $data['kf_id'], json_encode($kfInfo, 256));
  629. // 发送消息给用户.
  630. $chat_message = [
  631. 'message_type' => 'closeBysever',
  632. 'data' => [
  633. 'content' => '客服停止了该会话',
  634. 'time' => date('H:i'),
  635. ]
  636. ];
  637. Gateway::sendToClient($data['client_id'], json_encode($chat_message, 256));
  638. // 关闭用户连接.
  639. Gateway::closeClient($data['client_id']);
  640. // 发送消息给客服.
  641. $del_message = [
  642. 'message_type' => 'delUser',
  643. 'data' => [
  644. 'id' => $data['user_id']
  645. ]
  646. ];
  647. Gateway::sendToClient($data['kf_client_id'], json_encode($del_message, 256));
  648. // 查询工单会话总数.
  649. $chatCount = self::$db->select('count(*) as count')->from('ws_chat_log')->where("servicelog_id=$servicelogId")->row();
  650. // 将数据存入数据库.
  651. $updateServiceLogData = [
  652. 'status' => 2,
  653. 'evaluate_id' => isset($data['evaluate_id']) ? $data['evaluate_id'] : 0,
  654. 'evaluate_content' => isset($data['evaluate_content']) ? $data['evaluate_content'] : '',
  655. 'servicelog_close_type' => $closeBy,
  656. 'end_time' => time(),
  657. ];
  658. $updataAlarmData = [
  659. 'alarm_userSensitive' => $data['alarm_userSensitive'],
  660. 'alarm_serverSensitive' => $data['alarm_serverSensitive'],
  661. 'alarm_corresponding' => $data['alarm_corresponding'],
  662. 'alarm_cvtOvertime' => time() - $data['start_time'],
  663. 'alarm_respond' => $data['alarm_respond'],
  664. 'alarm_lineTime' => $data['start_time'] - $data['intime'],
  665. 'alarm_count' => $chatCount['count'],
  666. ];
  667. self::$db->update('ws_service_log')->cols($updateServiceLogData)->where("servicelog_id=$servicelogId")->query();
  668. self::$db->update('ws_alarm')->cols($updataAlarmData)->where("servicelog_id=$servicelogId")->query();
  669. }
  670. /**
  671. * 修改工单数据库数据
  672. * @param int $client_id 连接id
  673. *
  674. * tips: 当服务端主动退出的时候,会出现 exit status 9.原因是:服务端主动断开之后,连接的客户端会走这个方法,而短时间内进程
  675. * 需要处理这多的逻辑,又有cas操作,导致进程退出会超时,然后会被内核杀死,从而报出错误 9.实际对真正的业务没有任何的影响。
  676. */
  677. public static function insertServerLog($servicelogId, $closeBy = 0)
  678. {
  679. // 获取当前工单数据.
  680. $data = json_decode(self::$redis->HGET('SERVICELOG', $servicelogId), true);
  681. if (empty($data)) {
  682. return;
  683. }
  684. // 查询工单会话总数.
  685. $chatCount = self::$db->select('count(*) as count')->from('ws_chat_log')->where("servicelog_id=$servicelogId")->row();
  686. // 将数据存入数据库.
  687. $updateServiceLogData = [
  688. 'status' => 2,
  689. 'evaluate_id' => isset($data['evaluate_id']) ? $data['evaluate_id'] : 0,
  690. 'evaluate_content' => isset($data['evaluate_content']) ? $data['evaluate_content'] : '',
  691. 'servicelog_close_type' => $closeBy,
  692. 'end_time' => time(),
  693. ];
  694. $updataAlarmData = [
  695. 'alarm_userSensitive' => $data['alarm_userSensitive'],
  696. 'alarm_serverSensitive' => $data['alarm_serverSensitive'],
  697. 'alarm_corresponding' => $data['alarm_corresponding'],
  698. 'alarm_cvtOvertime' => time() - $data['start_time'],
  699. 'alarm_respond' => $data['alarm_respond'],
  700. 'alarm_lineTime' => $data['start_time'] - $data['intime'],
  701. 'alarm_count' => $chatCount['count'],
  702. ];
  703. self::$db->update('ws_service_log')->cols($updateServiceLogData)->where("servicelog_id=$servicelogId")->query();
  704. self::$db->update('ws_alarm')->cols($updataAlarmData)->where("servicelog_id=$servicelogId")->query();
  705. }
  706. /**
  707. * 有人退出
  708. * @param $group
  709. */
  710. private static function userOfflineTask($group)
  711. {
  712. }
  713. /**
  714. * 有人进入执行分配
  715. * @param $client_id
  716. * @param $group
  717. * @param $uid
  718. */
  719. private static function userOnlineTask($group = 0, $uid = 0, $last=[], $client_id='')
  720. {
  721. $allusergkarr = self::getUserListData();
  722. if (empty($allusergkarr)) {
  723. return;
  724. }
  725. $allkfgkarr = self::getWorkKfData();
  726. if (empty($allkfgkarr)&&!$last) {
  727. return;
  728. }
  729. $maxset = (self::$global->systemconfig)['KFMaxServices'] ?? 5;
  730. $maxset = intval($maxset);
  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. // 查询工单历史会话.
  737. $serviceid = $last['servicelog_id'];
  738. $chatLog = self::$db->select('*')->from('ws_chat_log')->where("servicelog_id=$serviceid")->orderByDESC(['time_line'])->row();
  739. $toOld_message = [
  740. 'message_type' => 'toOld',
  741. 'data' => [
  742. 'chatLog' => $chatLog??[],
  743. 'content' => '接入至未结束的会话'
  744. ]
  745. ];
  746. Gateway::sendToCurrentClient(json_encode($toOld_message, 256));
  747. return;
  748. } else {
  749. //系统定时调用时,无组,无用户
  750. foreach ($allusergkarr as $group => $gusersArr) {
  751. if (!isset($allkfgkarr[$group]) || count($allkfgkarr[$group]) <= 0) {
  752. //所属客服组无人在线
  753. continue;
  754. }
  755. $nowkfs = $allkfgkarr[$group];
  756. $count = count($nowkfs);
  757. $i = 0;
  758. foreach ($gusersArr as $user) {
  759. if ($nowkfs[$i]['task'] > $maxset) {
  760. break;
  761. }
  762. $nowkfs[$i]['task']++;
  763. self::BeginTalk($nowkfs[$i]['id'], $user['id'], $group, 0, $user);
  764. self::$redis->hdel(self::USERLIST, $user['id']);
  765. $i++;
  766. if ($i >= $count) {
  767. $i = 0;
  768. }
  769. }
  770. }
  771. return;
  772. }
  773. }
  774. }
  775. //开启一个会话
  776. private static function BeginTalk($kfuid, $uid, $group, $serviceid = 0, $userInfo = false)
  777. {
  778. $serviceid = intval($serviceid);
  779. if (!$userInfo) {
  780. $userInfo = json_decode(self::$redis->hget(self::USERINFOKEY, $uid), true);
  781. }
  782. $kfinfo = json_decode(self::$redis->hget(self::KFINFOKEY, $kfuid), true);
  783. if (empty($userInfo) || empty($kfinfo)) {
  784. return false;
  785. }
  786. $server = [];
  787. $armarr = [];
  788. if ($serviceid) {
  789. $server = self::$db->select('*')->from('ws_service_log')->where("servicelog_id=$serviceid ")->row();
  790. if ($server) {
  791. $armarr = self::$db->select('*')->from('ws_alarm')->where("servicelog_id=$serviceid ")->row();
  792. }
  793. }
  794. if (empty($server)) {
  795. $array = [
  796. 'user_id' => intval($uid),
  797. 'client_id' => $userInfo['client_id'],
  798. 'user_name' => $userInfo['name'],
  799. 'user_avatar' => $userInfo['avatar'],
  800. 'user_ip' => $userInfo['ip'],
  801. 'kf_id' => self::getkfid($kfuid),
  802. 'start_time' => time(),
  803. 'group_id' => $group ? $group : $userInfo['group'],
  804. 'website' => $userInfo['website'],
  805. 'system' => $userInfo['system'],
  806. 'browse' => $userInfo['browse'],
  807. 'intime' => $userInfo['intime'],
  808. 'status' => 1,
  809. 'evaluate_id' => 0,
  810. 'servicelog_close_type' => 0
  811. ];
  812. $serviceid = self::$db->insert('ws_service_log')->cols($array)->query();
  813. $server = array_merge(['servicelog_id' => $serviceid], $array);
  814. $armid = self::$db->insert('ws_alarm')->cols(['servicelog_id' => $serviceid])->query();
  815. $armarr = self::$db->select('*')->from('ws_alarm')->where("alarm_id=$armid")->row();
  816. }
  817. $redisData = array_merge($server, $armarr, ['kf_client_id' => $kfinfo['client_id'], 'server_name' => $kfinfo['name']]);
  818. self::$redis->hset(self::SERVICELOG, $serviceid, json_encode($redisData, 256));
  819. $kfinfo['user_info'] = array_merge($kfinfo['user_info'], [$userInfo['client_id'] => $serviceid]);
  820. $kfinfo['task'] = count($kfinfo['user_info']);
  821. self::$redis->hset(self::KFINFOKEY, $kfuid, json_encode($kfinfo, 256));
  822. $userInfo['serverid'] = $serviceid;
  823. $userInfo['kfuid'] = $kfuid;
  824. self::$redis->hset(self::USERINFOKEY, $uid, json_encode($userInfo, 256));
  825. // 通知会员发送信息绑定客服的id
  826. $noticeUser = [
  827. 'message_type' => 'connect',
  828. 'data' => [
  829. 'kf_id' => $kfuid,
  830. 'conversationId' => $serviceid,
  831. 'serverInfo' => $kfinfo,
  832. 'kf_name' => $kfinfo['job_name']
  833. ]
  834. ];
  835. self::MySendMsg($userInfo['client_id'], json_encode($noticeUser, 256));
  836. $sayHello = (self::$global->replay)['2'];
  837. if (!empty($sayHello) && 1 == $sayHello['status']) {
  838. $chat_message = [
  839. 'message_type' => 'chatMessage',
  840. 'data' => [
  841. 'id' => self::getkfuid($kfinfo['id']),
  842. 'name' => $kfinfo['name'],
  843. 'time' => date('H:i'),
  844. 'content' => $sayHello['word']
  845. ]
  846. ];
  847. self::MySendMsg($userInfo['client_id'], json_encode($chat_message, 256));
  848. unset($chat_message);
  849. }
  850. $noticeKf = [
  851. 'message_type' => 'connect',
  852. 'data' => [
  853. 'user_info' => $userInfo,
  854. 'conversationId' => $serviceid,
  855. ]
  856. ];
  857. self::MySendMsg($kfinfo['client_id'], json_encode($noticeKf, 256));
  858. unset($noticeKf);
  859. $key = date('Ymd') . 'success_in';
  860. self::$global->increment($key);
  861. return;
  862. }
  863. //连接至上一个会话
  864. private static function BeginOldTalk($kfuid, $uid, $group, $serviceid = 0, $userInfo = false)
  865. {
  866. $serviceid = intval($serviceid);
  867. $userInfo = json_decode(self::$redis->hget(self::USERINFOKEY, $uid), true);
  868. $kfinfo = json_decode(self::$redis->hget(self::KFINFOKEY, $kfuid), true);
  869. if (empty($userInfo) || empty($kfinfo)) {
  870. return false;
  871. }
  872. // 获取旧工单信息.
  873. $data = json_decode(self::$redis->HGET('SERVICELOG', $serviceid), true);
  874. if (empty($data)) {
  875. return;
  876. }
  877. // 修改工单数据.
  878. $data['user_avatar'] = $userInfo['avatar'];
  879. $data['client_id'] = $userInfo['client_id'];
  880. $data['user_ip'] = $userInfo['ip'];
  881. $data['website'] = $userInfo['website'];
  882. $data['system'] = $userInfo['system'];
  883. $data['browse'] = $userInfo['browse'];
  884. $data['status'] = 1;
  885. self::$redis->hset(self::SERVICELOG, $serviceid, json_encode($data, 256));
  886. // 更改用户连接客服信息
  887. $userInfo['serverid'] = $serviceid;
  888. $userInfo['kfuid'] = $kfuid;
  889. self::$redis->hset(self::USERINFOKEY, $uid, json_encode($userInfo, 256));
  890. // 更改客服连接信息.
  891. $kfinfo = json_decode(self::$redis->hget(self::KFINFOKEY, $kfuid), true);
  892. $kfUsers = $kfinfo['user_info'];
  893. foreach ($kfUsers as $key => $value) {
  894. if ($value == $serviceid) {
  895. // 删除之前的当前用户连接
  896. unset($kfUsers[$key]);
  897. }
  898. }
  899. // 增加现在用户的连接到客服
  900. $kfUsers[$userInfo['client_id']] = $serviceid;
  901. $kfinfo['user_info'] = $kfUsers;
  902. // 将数据存入redis
  903. self::$redis->hset('KFINFO', $kfuid, json_encode($kfinfo, 256));
  904. // 通知会员发送信息绑定客服的id
  905. $noticeUser = [
  906. 'message_type' => 'connect',
  907. 'data' => [
  908. 'kf_id' => $kfuid,
  909. 'conversationId' => $serviceid,
  910. 'serverInfo' => $kfinfo,
  911. 'kf_name' => $kfinfo['job_name']
  912. ]
  913. ];
  914. self::MySendMsg($userInfo['client_id'], json_encode($noticeUser, 256));
  915. // 发送给客服用户信息.
  916. $noticeKf = [
  917. 'message_type' => 'connect',
  918. 'data' => [
  919. 'user_info' => $userInfo,
  920. 'conversationId' => $serviceid,
  921. ]
  922. ];
  923. self::MySendMsg($kfinfo['client_id'], json_encode($noticeKf, 256));
  924. unset($noticeKf);
  925. $key = date('Ymd') . 'success_in';
  926. self::$global->increment($key);
  927. return;
  928. }
  929. //用户排队数据 按组
  930. private static function getUserListData()
  931. {
  932. $alluser = self::$redis->hgetall(self::USERLIST);
  933. if (empty($alluser)) {
  934. return false;
  935. }
  936. $allusergkarr = [];
  937. foreach ($alluser as $val) {
  938. $now = json_decode($val, true);
  939. if ($now) {
  940. //用户分组后的数组
  941. $allusergkarr[$now['group']][] = $now;
  942. }
  943. }
  944. foreach ($allusergkarr as $group => $nowgroups) {
  945. usort($allusergkarr[$group], function ($a, $b) {
  946. if ($a['intime'] == $b['intime']) {
  947. return 0;
  948. }
  949. return ($a['intime'] > $b['intime']) ? 1 : -1;
  950. });
  951. }
  952. if (!$allusergkarr) {
  953. return false;
  954. }
  955. unset($alluser);
  956. return $allusergkarr;
  957. }
  958. //找到可以接工单的客服 按组
  959. private static function getWorkKfData()
  960. {
  961. $allkfs = self::$redis->hgetall(self::KFINFOKEY);
  962. if (empty($allkfs)) {
  963. return false;
  964. }
  965. $allkfgkarr = [];
  966. foreach ($allkfs as $val) {
  967. $now = json_decode($val, true);
  968. if ($now && $now['status'] == 1) {
  969. //客分组后的数组
  970. $allkfgkarr[$now['group']][] = $now;
  971. }
  972. }
  973. if (!$allkfgkarr) {
  974. return false;
  975. }
  976. //客服每组按任务数由小到大排序 任务相同时按时间先后顺序
  977. foreach ($allkfgkarr as $group => $nowgroups) {
  978. usort($allkfgkarr[$group], function ($a, $b) {
  979. if ($a['task'] == $b['task']) {
  980. if ($a['intime'] == $b['intime']) {
  981. return 0;
  982. }
  983. return ($a['intime'] > $b['intime']) ? 1 : -1;
  984. }
  985. return ($a['task'] > $b['task']) ? 1 : -1;
  986. });
  987. }
  988. unset($allkfs);
  989. return $allkfgkarr;
  990. }
  991. //找到用户是否有一条未关闭的会话
  992. private static function UserHasOldTalk($uid)
  993. {
  994. $uid = intval($uid);
  995. $start_time = time() - 86400;
  996. $ret = self::$db->select('*')->from('ws_service_log')->where("start_time>=$start_time and user_id=$uid and status!=2 ")->orderByDESC(['servicelog_id'])->row();
  997. return $ret;
  998. }
  999. //今天排序累加
  1000. private static function todayqueuelength()
  1001. {
  1002. $dtype = 'user.queue.day.length';
  1003. $today = date("Y-m-d");
  1004. $sret = self::$db->select('*')->from('ws_countmidtable')->where('dtype=:dtype and mdate=:mdate')->bindValues(array('dtype' => $dtype, 'mdate' => $today))->row();
  1005. if ($sret) {
  1006. self::$db->update('ws_countmidtable')->cols(array('dcontent' => intval($sret['dcontent']) + 1))->where('id=' . $sret['id'])->query();
  1007. } else {
  1008. self::$db->insert('ws_countmidtable')->cols(array(
  1009. 'dtype' => $dtype,
  1010. 'mdate' => $today,
  1011. 'datatype' => 1,
  1012. 'dcontent' => 1))->query();
  1013. }
  1014. }
  1015. //客服工单转单
  1016. private static function servicetrutoother($type, $owen, $otherkfid, $serverid, $clientuid)
  1017. {
  1018. $owen = intval(substr($owen, 2));
  1019. $otherkfid = intval(substr($otherkfid, 2));
  1020. self::$db->insert('ws_serviceturn_log')->cols(array(
  1021. 'stype' => $type,
  1022. 'uid' => $owen,
  1023. 'tuid' => $otherkfid,
  1024. 'serverid' => $serverid,
  1025. 'guestuid' => $clientuid
  1026. ))->query();
  1027. }
  1028. /**
  1029. * 给客服分配会员【均分策略】
  1030. * @param $kfList
  1031. * @param $userList
  1032. * @param $group
  1033. * @param $total
  1034. */
  1035. private static function assignmentTask($kfList, $userList, $group, $total, $uid = 0)
  1036. {
  1037. }
  1038. /**
  1039. * 获取最大的服务人数
  1040. * @return int
  1041. */
  1042. private static function getMaxServiceNum()
  1043. {
  1044. $maxNumber = self::$db->query('select `max_service` from `ws_kf_config` where `id` = 1');
  1045. if (!empty($maxNumber)) {
  1046. $maxNumber = 5;
  1047. } else {
  1048. $maxNumber = $maxNumber['0']['max_service'];
  1049. }
  1050. return $maxNumber;
  1051. }
  1052. /**
  1053. * 将内存中的数据写入统计表
  1054. * @param int $flag
  1055. */
  1056. private static function writeLog($flag = 1)
  1057. {
  1058. // 上午 8点 到 22 点开始统计
  1059. if (date('H') < 8 || date('H') > 22) {
  1060. return;
  1061. }
  1062. $inQueue_1 = self::$redis->hgetall(self::USERLIST);
  1063. $inQueue = empty($inQueue_1) ? 0 : count($inQueue_1);
  1064. $allkf = self::$redis->hgetall(self::KFINFOKEY);
  1065. $nowTalking = $onlineKf = 0;
  1066. if (!empty($allkf)) {
  1067. foreach ($allkf as $kfuid => $val) {
  1068. $tmp = json_decode($val, true);
  1069. $onlineKf++;
  1070. $nowTalking += count($tmp['user_info']);
  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. $kf_info_from['user_info'] = self::ArrayDataopt($kf_info_from['user_info'], $user_info['client_id'], 0);
  1339. $kf_info_from['task'] = count($kf_info_from['user_info']);
  1340. self::$redis->hset(self::KFINFOKEY, $fromkfuid, json_encode($kf_info_from, 256));
  1341. ///////旧工单部分数据更新回库
  1342. /// 查询工单会话总数.
  1343. self:: BeginTalk($toukfid, $uid, $groupidto, 0, $user_info);
  1344. self::servicetrutoother('OUT', $fromkfuid, $toukfid, $serviceid, $uid);
  1345. $newUserInfo = json_decode(self::$redis->hget(self::USERINFOKEY, $uid), true);
  1346. self::servicetrutoother('IN', $toukfid, $fromkfuid, $newUserInfo['serverid'], $uid);
  1347. //回转接人,转接成功
  1348. Gateway::sendToCurrentClient(json_encode(['message_type' => 'trunconnect', 'data' => ['status' => 1]], 256));
  1349. // 发送给用户转接消息
  1350. Gateway::sendToClient($user_info['client_id'], json_encode(['message_type' => 'changeKeFuSuccess', 'data' => ['content' => "会话转接成功"]], 256));
  1351. self::DebugOut('changekf 转换成功!');
  1352. return;
  1353. }
  1354. //客服在线状态写组
  1355. private static function writeLogKfStatus($kf, $status, $flag = 1)
  1356. {
  1357. if ($flag == 1) {
  1358. $status = intval($status);
  1359. if ($status == 0) {
  1360. self::$db->delete('ws_kfonline')->where("uid='$kf'")->query();
  1361. } else {
  1362. $now = date('Y-m-d H:i;s');
  1363. $ip = isset($_SESSION['remotip']) ? $_SESSION['remotip'] : '';
  1364. $sql = "insert into ws_kfonline(uid,status,uptime,ip) values('$kf',$status,'$now','$ip') ON DUPLICATE KEY UPDATE status=$status,uptime='$now' ";
  1365. self::$db->query($sql);
  1366. }
  1367. } else {
  1368. self::$db->query("delete from ws_kfonline ");
  1369. }
  1370. }
  1371. public static function resetServiceLog($kfid = 0)
  1372. {
  1373. $t = time() - 24 * 3600 * 7;
  1374. $now = time();
  1375. if ($kfid) {
  1376. if ((substr($kfid, 0, 2) == 'KF')) {
  1377. $kfid = intval(substr($kfid, 2));
  1378. }
  1379. $kfid = intval($kfid);
  1380. self::$db->query("update ws_service_log set status=2,end_time=$now where start_time>=$t and kf_id=$kfid and status!=2");
  1381. self::$redis->hdel(self::KFINFOKEY, 'KF' . $kfid);
  1382. } else {
  1383. self::$redis->del(self::KFINFOKEY);
  1384. self::$redis->del(self::USERLIST);
  1385. self::$redis->del(self::USERINFOKEY);
  1386. self::$redis->del('adminList');
  1387. self::$redis->del(self::WEBSOCKALLUSER);
  1388. self::$redis->del('SERVICELOG');
  1389. self::$db->query("update ws_service_log set status=2,end_time=$now where start_time>=$t and status!=2");
  1390. }
  1391. }
  1392. public static function onWorkerStop($businessWorker)
  1393. {
  1394. if ($businessWorker->id == 1) {
  1395. self::resetServiceLog();
  1396. }
  1397. }
  1398. //用户下线通知
  1399. private static function userCloseNotice($client_id, $cuid, $group)
  1400. {
  1401. }
  1402. //踢掉同一用户的旧用户
  1403. private static function tickOlduser($uid)
  1404. {
  1405. }
  1406. private static function DebugOut($msg, $title = '', $type = 'info')
  1407. {
  1408. $config = self::$global->systemconfig;
  1409. if (!isset($config['isdebug']) || empty($config['isdebug']['systemconfig_data'])) {
  1410. return;
  1411. }
  1412. if (!is_string($msg)) {
  1413. $msg = json_encode([$msg], 256);
  1414. }
  1415. $msg = date("Y-m-d H:i:s") . ' - ' . $type . ' - ' . $title . ' - ' . $msg . "\n";
  1416. echo $msg;
  1417. }
  1418. //定时器相关
  1419. private static function TimerThing($worker)
  1420. {
  1421. // 当天的累积接入值
  1422. $key = date('Ymd') . 'total_in';
  1423. if (is_null(self::$global->$key)) {
  1424. self::$global->$key = 0;
  1425. $oldKey = date('Ymd', strtotime('-1 day')); // 删除前一天的统计值
  1426. unset(self::$global->$oldKey);
  1427. unset($oldKey, $key);
  1428. }
  1429. // 成功接入值
  1430. $key = date('Ymd') . 'success_in';
  1431. if (is_null(self::$global->$key)) {
  1432. self::$global->$key = 0;
  1433. $oldKey = date('Ymd', strtotime('-1 day')); // 删除前一天的统计值
  1434. unset(self::$global->$oldKey);
  1435. unset($oldKey, $key);
  1436. }
  1437. // 定时统计数据
  1438. if (0 == $worker->id) {
  1439. self::writeLogKfStatus(0, 0, 0);
  1440. //每5秒更新进行一次人员分配
  1441. Timer::add(5, function () {
  1442. self::userOnlineTask();
  1443. });
  1444. //每1分钟报告一次本组排列人员(如果有人排队)
  1445. Timer::add(60, function () {
  1446. self::lineup();
  1447. });
  1448. // 1分钟统计一次实时数据
  1449. Timer::add(60 * 1, function () {
  1450. self::writeLog(1);
  1451. });
  1452. // 40分钟写一次当前日期点数的log数据
  1453. Timer::add(60 * 40, function () {
  1454. self::writeLog(2);
  1455. });
  1456. //初始化.....
  1457. self::upsystemconfig();
  1458. //每3分钟更新一次系统配置文件
  1459. Timer::add(60 * 3, function () {
  1460. self::upsystemconfig();
  1461. });
  1462. // 删除前一天的统计值
  1463. Timer::add(60 * 60 * 12, function () {
  1464. $oldKey = date('Ymd', strtotime('-1 day'));
  1465. unset(self::$global->$oldKey);
  1466. });
  1467. // 管理员实时监控.
  1468. Timer::add(20, function () {
  1469. // 获取在线管理员
  1470. $adminList = self::$redis->smembers('adminList');
  1471. if ($adminList) {
  1472. self::systemMonitoring($adminList);
  1473. }
  1474. });
  1475. // 检查对话时效给出.
  1476. Timer::add(40, function () {
  1477. self::overTime();
  1478. });
  1479. self::resetServiceLog();
  1480. }
  1481. }
  1482. //调试使用
  1483. public static function mydebug($client_id, $message)
  1484. {
  1485. }
  1486. public static function MySendMsg($clientId, $msg)
  1487. {
  1488. Gateway::sendToClient($clientId, $msg);
  1489. }
  1490. //得到客服的UID字符值
  1491. public static function getkfuid($uid)
  1492. {
  1493. if (substr($uid, 0, 2) == 'KF') {
  1494. return $uid;
  1495. } else {
  1496. return 'KF' . intval($uid);
  1497. }
  1498. }
  1499. //得到客服的ID整数值
  1500. public static function getkfid($id)
  1501. {
  1502. if (strtolower(substr($id, 0, 2)) == 'kf') {
  1503. return intval(substr($id, 2));
  1504. }
  1505. return intval($id);
  1506. }
  1507. //从数组中获取参数
  1508. public static function getPars($array, $key, $default = '')
  1509. {
  1510. if (isset($array[$key])) {
  1511. return $array[$key];
  1512. }
  1513. return $default;
  1514. }
  1515. //获取在线客服信息
  1516. public static function getOnlineKfData($group = 0, $status = 0)
  1517. {
  1518. $all = self::$redis->hgetall(self::KFINFOKEY);
  1519. if (!$all) {
  1520. return false;
  1521. }
  1522. $return = [];
  1523. foreach ($all as $val) {
  1524. $now = json_decode($val, true);
  1525. if ($group) {
  1526. if ($now['group'] != $group) {
  1527. continue;
  1528. }
  1529. }
  1530. if ($status) {
  1531. if ($now['status'] != $status) {
  1532. continue;
  1533. }
  1534. }
  1535. $return[$now['id']] = $now;
  1536. }
  1537. return $return;
  1538. }
  1539. //找到在排队的用户按时间先后顺序
  1540. public static function getUselistData($group)
  1541. {
  1542. $all = self::$redis->hgetall(self::USERLIST);
  1543. if (!$all) {
  1544. return false;
  1545. }
  1546. $return = [];
  1547. foreach ($all as $val) {
  1548. $now = json_decode($val, true);
  1549. if ($group == $now['group']) {
  1550. $return[] = $now;
  1551. }
  1552. }
  1553. usort($return, function ($a, $b) {
  1554. if ($a['intime'] == $b['intime']) {
  1555. return 0;
  1556. }
  1557. return $a['intime'] > $b['intime'] ? 1 : -1;
  1558. });
  1559. return $return;
  1560. }
  1561. //对客服的用户user_info数组进行加减操作 $clientid用户连接号 opt=1添加 0删除 $serverid服务工单号
  1562. public static function ArrayDataopt($array, $clientid, $opt, $serverid = 0)
  1563. {
  1564. if (!is_array($array)) {
  1565. return [];
  1566. }
  1567. if ($opt == 0) {
  1568. if (isset($array[$clientid])) {
  1569. unset($array[$clientid]);
  1570. }
  1571. return $array;
  1572. } else {
  1573. $array[$clientid] = $serverid;
  1574. return $array;
  1575. }
  1576. }
  1577. }