Events.php 74 KB

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