Events.php 80 KB

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