Events.php 80 KB

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