Events.php 71 KB

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