Events.php 82 KB

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