Events.php 77 KB

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