Events.php 77 KB

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