Events.php 78 KB

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