Events.php 81 KB

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