Events.php 82 KB

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