Events.php 75 KB

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