Events.php 83 KB

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