Events.php 78 KB

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