Events.php 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431
  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. /**
  23. * 主逻辑
  24. * 主要是处理 onConnect onMessage onClose 三个方法
  25. * onConnect 和 onClose 如果不需要可以不用实现并删除
  26. */
  27. class Events
  28. {
  29. /**
  30. * 新建一个类的静态成员,用来保存数据库实例
  31. */
  32. public static $db = null;
  33. public static $global = null;
  34. public static $redis = null;
  35. public static $logic = null;
  36. const KFINFOKEY = 'KFINFO'; //客服信息hash表
  37. const USERINFOKEY = 'USERINFO'; //用户信息hash表
  38. const USERLIST = 'USERLIST'; //用户排队表
  39. const SERVICELOG = 'SERVICELOG'; //工单信息
  40. /**
  41. * 进程启动后初始化数据库连接
  42. */
  43. public static function onWorkerStart($worker)
  44. {
  45. include_once(__DIR__ . DIRECTORY_SEPARATOR . "Mlogic.php");
  46. self::$logic = Mlogic::GetInstance();
  47. self::$db = self::$logic->getDb();
  48. self::$redis = self::$logic->getRedis();
  49. self::$global = self::$logic->getGlbData();
  50. self::TimerThing($worker);
  51. // 管理员实时监控.
  52. /*Timer::add(6, function () {
  53. // 获取在线管理员总数.
  54. $adminListCount = self::$redis->lLen('adminList');
  55. // 获取在线管理员
  56. $adminList = self::$redis->lrange('adminList', 0, $adminListCount);
  57. if ($adminList) {
  58. self::systemMonitoring($adminList);
  59. }
  60. });*/
  61. // 检查对话时效给出.
  62. Timer::add(6, function () {
  63. self::overTime();
  64. });
  65. }
  66. /**
  67. * 每分钟定时向客服发送一次排队情况
  68. */
  69. public static function lineup()
  70. {
  71. }
  72. /**
  73. * 当客户端连接时触发
  74. * 如果业务不需此回调可以删除onConnect
  75. *
  76. * @param int $client_id 连接id
  77. */
  78. public static function onConnect($client_id)
  79. {
  80. // 检测是否开启自动应答
  81. $sayHello = self::$db->query('select `word`,`status` from `ws_reply` where `id` = 1');
  82. if (!empty($sayHello) && 1 == $sayHello['0']['status']) {
  83. $hello = [
  84. 'message_type' => 'helloMessage',
  85. 'data' => [
  86. 'name' => '智能助手',
  87. 'time' => date('H:i'),
  88. 'content' => $sayHello['0']['word']
  89. ]
  90. ];
  91. Gateway::sendToClient($client_id, json_encode($hello, 256));
  92. unset($hello);
  93. }
  94. unset($sayHello);
  95. // 检测是否开启广告
  96. $advertisement = self::$db->query('select * from `ws_advertisement` where `advertisement_status` = 1');
  97. if (!empty($advertisement)) {
  98. $chat_message = [
  99. 'message_type' => 'advertisement',
  100. 'data' => $advertisement
  101. ];
  102. Gateway::sendToClient($client_id, json_encode($chat_message, 256));
  103. unset($chat_message);
  104. }
  105. unset($advertisement);
  106. }
  107. /**
  108. * 当客户端发来消息时触发
  109. * @param int $client_id 连接id
  110. * @param mixed $message 具体消息
  111. */
  112. public static function onMessage($client_id, $message)
  113. {
  114. if ($message == '{"type":"ping"}') {
  115. Gateway::sendToCurrentClient('{"type":"pong"}');
  116. return;
  117. } else {
  118. self::DebugOut($message, "OnMessage");
  119. }
  120. $message = json_decode($message, true);
  121. if (isset($message['type'])) {
  122. switch ($message['type']) {
  123. case 'mydebug':
  124. self::mydebug($client_id, $message['data']);
  125. break;
  126. // 管理员初始化
  127. case 'adminInit':
  128. $token = $message['token'];
  129. self::adminInit($client_id, $token);
  130. break;
  131. // 客服初始化
  132. case 'init':
  133. $data = $message['data'];
  134. self::Kfinit($client_id, $data);
  135. break;
  136. // 顾客初始化
  137. case 'userInit';
  138. $data = $message['data'];
  139. self::userInitEnt($client_id, $data);
  140. break;
  141. //在线客服信息
  142. case 'getkfonlines':
  143. Gateway::sendToCurrentClient(json_encode(self::getkfonlines(), 256));
  144. break;
  145. case 'kfgetuserinfo':
  146. $tmp_id = isset($message['data']['id']) ? $message['data']['id'] : 0;
  147. self::kfgetuserinfo($client_id, intval($tmp_id));
  148. break;
  149. // 客服聊天
  150. case 'chatMessage':
  151. self::chatMessage($message['data']);
  152. break;
  153. // 转接
  154. case 'changeGroup':
  155. break;
  156. case 'closeUser':
  157. break;
  158. // 机器人问答.
  159. case 'toRobot':
  160. self::toRobot($client_id, $message);
  161. break;
  162. // 评价.
  163. case 'evaluate':
  164. self::evaluate($client_id, $message);
  165. break;
  166. // 客服关闭会话.
  167. case 'kfCloseUser':
  168. break;
  169. // 客服更改状态.
  170. case 'kfOnline':
  171. self::KFStatusCg($client_id, $message);
  172. break;
  173. case 'changeOtherhKeFu';
  174. break;
  175. // 弹出评价.
  176. case 'getEvaluate';
  177. break;
  178. }
  179. }
  180. }
  181. //客服聊天
  182. public static function chatMessage($message)
  183. {
  184. // 获取当前会话工单.
  185. $data = json_decode(self::$redis->HGET('SERVICELOG',$message['conversationId']), true);
  186. $chat_message = [
  187. 'message_type' => 'chatMessage',
  188. 'data' => [
  189. 'name' => $message['from_name'],
  190. 'id' => $message['from_id'],
  191. 'time' => date('H:i'),
  192. 'content' => $message['content'],
  193. ]
  194. ];
  195. if (isset($message['isFirst']) && $message['isFirst']) {
  196. $data['alarm_corresponding'] = time() - $data['start_time'];
  197. }
  198. // 发送消息.
  199. if (substr($message['from_id'],0,2) === 'KF') {
  200. $data['userLastTime'] = time();
  201. Gateway::sendToClient($data['client_id'], json_encode($chat_message));
  202. } else {
  203. $data['serverLastTime'] = time();
  204. Gateway::sendToClient($data['kf_client_id'], json_encode($chat_message));
  205. }
  206. // 保存修改后的工单信息.
  207. self::$redis->HSET('SERVICELOG', $message['conversationId'], $data);
  208. // 聊天信息入库
  209. $insertChatData = [
  210. 'from_id' => $message['data']['from_id'],
  211. 'from_name' => $message['data']['from_name'],
  212. 'to_id' => $message['data']['to_id'],
  213. 'to_name' => $message['data']['to_name'],
  214. 'content' => $message['data']['content'],
  215. 'servicelog_id' => $message['data']['conversationId'],
  216. 'time_line' => time()
  217. ];
  218. self::$db->insert('ws_chat_log')->cols($insertChatData)->query();
  219. }
  220. //得到一个用户详细信息
  221. public static function kfgetuserinfo($clientid, $id)
  222. {
  223. $ret = self::$db->select('*')->from('ws_account')->where('id=:id')->bindValues(['id' => $id])->row();
  224. Gateway::sendToClient($clientid, json_encode(['message_type' => 'userdetailinfo', 'data' => $ret]));
  225. return;
  226. }
  227. //获取在线客服列表
  228. public static function getkfonlines()
  229. {
  230. $return = [
  231. 'message_type' => 'onlinekfs',
  232. 'data' => [],
  233. ];
  234. $nowkfid = isset($_SESSION['uid']) ? $_SESSION['uid'] : 0;
  235. $fromgrouupid = isset($_SESSION['group']) ? $_SESSION['group'] : 0;
  236. if (empty($fromgrouupid) || empty($nowkfid)) {
  237. return $return;
  238. }
  239. $online = self::getOnlineKfData(0, 1);
  240. if (empty($online)) {
  241. return $return;
  242. }
  243. $groupnamemap = self::$global->groupmap;
  244. $ret = [];
  245. foreach ($online as $uinfo) {
  246. if ($nowkfid == $uinfo['id']) {
  247. continue;
  248. }
  249. $ret[] = ['groupid' => $uinfo['group'], 'groupname' => $groupnamemap[$uinfo['group']], 'kfuid' => $uinfo['id'], 'kfname' => $uinfo['name'], 'kfjobname' => $uinfo['job_name']];
  250. }
  251. $return['data'] = $ret;
  252. return $return;
  253. }
  254. //客户工单内部组转接
  255. public static function changeOtherhKeFu($client_id, $smessage)
  256. {
  257. return;
  258. }
  259. public static function KFStatusCg($client_id, $message)
  260. {
  261. if (!isset($_SESSION['iskefu']) || $_SESSION['iskefu'] != 1) {
  262. return;
  263. }
  264. $userId = $message['data']['uid'];
  265. $status = intval($message['data']['status']);
  266. if (!in_array($status, [1, 2, 3])) {
  267. return false;
  268. }
  269. $oldstatus = '';
  270. $kfinfo = self::$redis->hget(self::KFINFOKEY, $userId);
  271. if (empty($kfinfo)) {
  272. return false;
  273. }
  274. $kfinfo = json_decode($kfinfo, true);
  275. if (!$kfinfo) {
  276. return false;
  277. }
  278. if ($kfinfo['status'] != $status) {
  279. $oldstatus = $kfinfo['status'];
  280. $kfinfo['status'] = $status;
  281. self::$redis->hset(self::KFINFOKEY, $userId, json_encode($kfinfo, 256));
  282. }
  283. self::writeLogKfStatus($userId, $status);
  284. Gateway::sendToCurrentClient(json_encode(['message_type' => 'cgstatus', 'data' => ['new_status' => $status, 'old_status' => $oldstatus]]));
  285. return;
  286. }
  287. //获取某个用户全部信息
  288. public static function getClientIndo($id)
  289. {
  290. $ret = self::$db->from('ws_accounts')->select("*")->where(['id' => $id])->row();
  291. return $ret;
  292. }
  293. //客服接入sock,及初始化
  294. public static function Kfinit($client_id, $message)
  295. {
  296. $uid = self::getPars($message, 'uid');
  297. $group = intval(self::getPars($message, 'group', 0));
  298. if (empty($uid) || empty($group) || !isset(self::$global->groupmap[$group])) {
  299. self::MySendMsg($client_id, json_encode(["message_type" => 'checkfalse', 'data' => "客服登陆参数错误"], 256));
  300. Gateway::closeCurrentClient();
  301. return;
  302. }
  303. //客服登陆验证 不符合的直接断掉
  304. $kfinfo = self::KfloginCheck($client_id, $message);
  305. if (empty($kfinfo)) {
  306. self::MySendMsg($client_id, json_encode(["message_type" => 'checkfalse', 'data' => "验证失败"], 256));
  307. Gateway::closeCurrentClient();
  308. return true;
  309. } elseif ($kfinfo['status'] != 1) {
  310. self::MySendMsg($client_id, json_encode(["message_type" => 'checkfalse', 'data' => "禁用中..."], 256));
  311. Gateway::closeCurrentClient();
  312. return true;
  313. }
  314. $loginstate = self::$logic->userIsLogin($client_id, $uid, $group);
  315. if ($loginstate == 1) {
  316. self::MySendMsg($oldcontid, (json_encode(['message_type' => 'reLoginErr', 'msg' => '正在登陆中,请稍后...'], 256)));
  317. Gateway::closeClient($oldcontid);
  318. return;
  319. }
  320. if ($loginstate == 2) {
  321. $oldcontids = Gateway::getClientIdByUid($uid);
  322. Gateway::sendToClient($oldcontids['0'], (json_encode(['message_type' => 'reLoginErr', 'msg' => '你的账号在其它登陆,本次下线'], 256)));
  323. Gateway::closeClient($oldcontids['0']);
  324. sleep(2);
  325. }
  326. self::$redis->hset('loginTmp:' . $uid, 'uid', time());
  327. self::$redis->expire('loginTmp:' . $uid, 5);
  328. $newinfo =
  329. [
  330. 'id' => 'KF' . $kfinfo['id'],
  331. 'name' => $kfinfo['user_name'],
  332. 'job_name' => $kfinfo['user_job_number'],
  333. 'avatar' => $kfinfo['user_avatar'],
  334. 'group' => $group,
  335. 'client_id' => $client_id,
  336. 'task' => 0,
  337. 'intime' => time(),
  338. 'signature' => $kfinfo['signature'],
  339. 'status' => 2, // 1为在线(接收分配、接收消息)2为隐身(不接收分配、只接收消息)3、休息
  340. 'user_info' => [], //在会话的用户cid key为clientid ,值为工单号
  341. ];
  342. self::$redis->hset(self::KFINFOKEY, $uid, json_encode($newinfo, 256));
  343. $_SESSION['info'] = $newinfo;
  344. // 绑定 client_id 和 uid
  345. Gateway::bindUid($client_id, $message['uid']);
  346. $_SESSION['group'] = $message['group'];
  347. $_SESSION['iskefu'] = 1;
  348. $_SESSION['uid'] = $message['uid'];
  349. $_SESSION['name'] = $message['name'];
  350. Gateway::joinGroup($client_id, 'group_' . $message['group']);
  351. $chat_message = [
  352. 'message_type' => 'loginSuccess',
  353. ];
  354. self::MySendMsg($client_id, json_encode($chat_message, 256));
  355. unset($chat_message);
  356. self::writeLogKfStatus($message['uid'], 2);
  357. return;
  358. }
  359. /**
  360. * 管理员
  361. * @param $client_id 服务ID
  362. * @param $message 数据
  363. */
  364. public static function adminInit($client_id, $token)
  365. {
  366. // 查询token是否存在.
  367. $systemConfigData = self::$db->query("SELECT `id` FROM `ws_admins` where `token`= '$token'");
  368. if ($systemConfigData) {
  369. $adminList = self::$redis->lpush('adminList', $client_id);
  370. self::systemMonitoring([$client_id]);
  371. } else {
  372. $chat_message = [
  373. 'message_type' => 'tips',
  374. 'data' => '管理员不存在'
  375. ];
  376. Gateway::sendToClient($client_id, json_encode($chat_message, 256));
  377. Gateway::closeClient($client_id);
  378. }
  379. }
  380. //客服登陆验证
  381. public static function KfloginCheck($client, $messageArray)
  382. {
  383. $uid = isset($messageArray['uid']) ? $messageArray['uid'] : '';
  384. $token = isset($messageArray['token']) ? $messageArray['token'] : '';
  385. if (empty($uid) || empty($token)) {
  386. return false;
  387. }
  388. $expire_time_vali = time() - 60 * 60 * 24;
  389. $kfid = intval(substr($uid, 2));
  390. $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();
  391. if ($ret) {
  392. self::$db->update('ws_users')->cols(array('online_status' => 1, 'online_connectid' => $client))->where('id=' . $kfid)->query();
  393. return $ret;
  394. }
  395. return false;
  396. }
  397. //用户发送邦定用户事件
  398. public static function userInitEnt($client_id, $message)
  399. {
  400. $uid = intval($message['uid']);
  401. $group = intval($message['group']);
  402. if (!isset(self::$global->groupmap[$group])) {
  403. self::MySendMsg($client_id, (json_encode(['message_type' => 'reLoginErr', 'msg' => '不存在客服组....'], 256)));
  404. Gateway::closeCurrentClient();
  405. }
  406. $loginstate = self::$logic->userIsLogin($client_id, $uid, $group);
  407. if ($loginstate == 1) {
  408. self::MySendMsg($oldcontid, (json_encode(['message_type' => 'reLoginErr', 'msg' => '正在登陆中,请稍后...'], 256)));
  409. Gateway::closeCurrentClient();
  410. return;
  411. }
  412. $hisdata = self::$redis->hget(self::USERINFOKEY, $uid);
  413. if ($hisdata) {
  414. $hisdata = json_decode($hisdata, true);
  415. $oldclientid = $hisdata['client_id'];
  416. self::MySendMsg($oldclientid, json_encode(['type' => 'reLoginErr', 'msg' => '相同账号登陆,本次退出'], 256));
  417. Gateway::closeClient($oldclientid);
  418. sleep(1);
  419. }
  420. $onlinekf = self::getOnlineKfData($group, 1);
  421. if (empty($onlinekf)) {
  422. Gateway::sendToClient($client_id, json_encode(['message_type' => 'notice', 'content' => '暂时没有客服上班,请稍后再咨询。'], 256));
  423. Gateway::closeClient($client_id);
  424. return;
  425. }
  426. self::$redis->hset('loginTmp:' . $uid, 'uid', time());
  427. self::$redis->expire('loginTmp:' . $uid, 5);
  428. $data = [
  429. 'id' => $uid,
  430. 'name' => $message['name'],
  431. 'avatar' => $message['avatar'],
  432. 'website' => $_SESSION['origin'],//$_SERVER['HTTP_ORIGIN'],
  433. 'browse' => Gateway::browse_info(),
  434. 'system' => Gateway::get_os(),
  435. 'ip' => isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '',
  436. 'group' => $message['group'],
  437. 'intime' => time(),
  438. 'kfuid' => '',
  439. 'ip' => $_SESSION['remotip'],
  440. 'serverid' => 0,
  441. 'client_id' => $client_id
  442. ];
  443. self::$redis->hset(self::USERLIST, $uid, json_encode($data, 256));
  444. self::$redis->hset(self::USERINFOKEY, $uid, json_encode($data, 256));
  445. // 写入接入值
  446. $key = date('Ymd') . 'total_in';
  447. $oldKey = date('Ymd', strtotime('-1 day')); // 删除前一天的统计值
  448. unset(self::$global->$oldKey);
  449. self::$global->increment($key);
  450. // 绑定 client_id 和 uid
  451. Gateway::bindUid($client_id, $uid);
  452. $_SESSION['iskefu'] = 0;
  453. $_SESSION['uid'] = $message['uid'];
  454. // 尝试分配新会员进入服务
  455. self::userOnlineTask($group, $uid);
  456. }
  457. /**
  458. * 当用户断开连接时触发
  459. * @param int $client_id 连接id
  460. *
  461. * tips: 当服务端主动退出的时候,会出现 exit status 9.原因是:服务端主动断开之后,连接的客户端会走这个方法,而短时间内进程
  462. * 需要处理这多的逻辑,又有cas操作,导致进程退出会超时,然后会被内核杀死,从而报出错误 9.实际对真正的业务没有任何的影响。
  463. */
  464. public static function onClose($client_id)
  465. {
  466. $isKefuoff = isset($_SESSION['iskefu']) ? $_SESSION['iskefu'] : 0;
  467. $uid = isset($_SESSION['uid']) ? $_SESSION['uid'] : false;
  468. echo "下线:uid: $uid - cid: $client_id - iskf: $isKefuoff \n";
  469. $adminList = self::$global->adminList ?? [];
  470. $key = array_search($client_id, $adminList);
  471. if (strlen($key)) {
  472. array_splice($adminList, $key, 1);
  473. self::$global->adminList = $adminList;
  474. }
  475. if (empty($uid)) {
  476. return;
  477. }
  478. if ($isKefuoff) {
  479. self::serviceOffline($client_id, $uid);
  480. } else {
  481. self::guestOffline($client_id, $uid);
  482. }
  483. return;
  484. }
  485. //客服下线了 系统调用,不能手动调用
  486. public static function serviceOffline($client_id, $uid)
  487. {
  488. $group = $_SESSION['group'];
  489. $uinfo = self::$redis->hget(self::KFINFOKEY, $uid);
  490. $uinfo = json_decode($uinfo, true);
  491. $user_info = $uinfo['user_info'];
  492. $kfid = self::getkfid($uid);
  493. $now = time();
  494. $starttime = $now - 86400 * 7;
  495. $serlogs = self::$db->select('servicelog_id')->from('ws_service_log')->where(" start_time>=$starttime and kf_id=$kfid AND status !=2 ")->query();
  496. if (!empty($user_info)) {
  497. foreach ($user_info as $val => $serverid) {
  498. self::MySendMsg($val, json_encode(['message_type' => 'serviceoffline', 'msg' => '客户人员下线!'], 256));
  499. Gateway::closeClient($val);
  500. }
  501. }
  502. $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 ";
  503. echo "客服退出: " . $sql . "\n";
  504. self::$db->query($sql);
  505. self::$db->update('ws_users')->cols(array('online_status' => 0, 'online_connectid' => ''))->where('id=' . $kfid)->query();
  506. self::writeLogKfStatus($uid, 0);
  507. return;
  508. }
  509. //用户下线了 系统调用,不能手动调用
  510. public static function guestOffline($client_id, $uid)
  511. {
  512. $uid = intval($uid);
  513. $krclient_id = 0;
  514. $data = self::$redis->hget(self::USERINFOKEY, $uid);
  515. if (empty($data)) {
  516. return;
  517. }
  518. $info = json_decode($data, true);
  519. self::$redis->hdel(self::USERLIST, $uid);
  520. self::$redis->hdel(self::USERINFOKEY, $uid);
  521. if (!empty($info['kfuid'])) {
  522. $kfinfo = self::$redis->hget(self::KFINFOKEY, $info['kfuid']);
  523. if (!empty($kfinfo)) {
  524. $kfinfoArr = json_decode($kfinfo, true);
  525. $krclient_id = $kfinfoArr['client_id'];
  526. $kfinfoArr['user_info'] = self::ArrayDataopt($kfinfoArr['user_info'], $client_id, 0);
  527. $kfinfoArr['task'] = count($kfinfoArr['user_info']);
  528. self::$redis->hset(self::KFINFOKEY, $info['kfuid'], json_encode($kfinfoArr, 256));
  529. }
  530. }
  531. $chat_message = [
  532. 'message_type' => 'userClose',
  533. 'data' => [
  534. 'content' => '用户连接已断开',
  535. 'id' => $uid,
  536. 'time' => date('H:i'),
  537. ]
  538. ];
  539. $now = time();
  540. $serverid = intval($info['serverid']);
  541. if ($serverid) {
  542. $sql = "update `ws_service_log` set `status` = '3' where servicelog_id=$serverid ";
  543. self::$db->query($sql);
  544. }
  545. if ($krclient_id) {
  546. Gateway::sendToClient($krclient_id, json_encode($chat_message, 256));
  547. }
  548. return;
  549. }
  550. /**
  551. * 客服结束会话
  552. *
  553. * tips: 未有$client_id的关闭
  554. */
  555. public static function closeUser($servicelog_id, $userId, $kf_id, $groupId)
  556. {
  557. }
  558. /**
  559. * 工单结束
  560. * @param int $client_id 连接id
  561. *
  562. * tips: 当服务端主动退出的时候,会出现 exit status 9.原因是:服务端主动断开之后,连接的客户端会走这个方法,而短时间内进程
  563. * 需要处理这多的逻辑,又有cas操作,导致进程退出会超时,然后会被内核杀死,从而报出错误 9.实际对真正的业务没有任何的影响。
  564. */
  565. public static function serverClose($servicelogId)
  566. {
  567. // 获取当前工单数据.
  568. $data = json_decode(self::$redis->HGET('SERVICELOG', $servicelogId), true);
  569. // 获取当前工单数据.
  570. $kfInfo = json_decode(self::$redis->HGET('KFINFO', 'KF'.$data['kf_id']), true);
  571. // 删除当前工单.
  572. //self::$redis->hdel('SERVICELOG', $servicelogId);
  573. // 当前服务客服删除当前人员.
  574. $kfUserList = self::ArrayDataopt($kfInfo['user_info'], $kfInfo['client_id'], 0);
  575. if (isset($kfInfo)) {
  576. print_r([$kfInfo,$servicelogId]);die;
  577. }
  578. // 当前客服所接待人员.
  579. $kfInfo['user_info'] = $kfUserList;
  580. $kfInfo['task'] = count($kfUserList);
  581. // 存入客服信息.
  582. $redis->HSET('KFINFO', 'KF'.$data['kf_id'], $kfInfo);
  583. // 将数据存入数据库.
  584. }
  585. /**
  586. * 有人退出
  587. * @param $group
  588. */
  589. private static function userOfflineTask($group)
  590. {
  591. }
  592. /**
  593. * 有人进入执行分配
  594. * @param $client_id
  595. * @param $group
  596. * @param $uid
  597. */
  598. private static function userOnlineTask($group = 0, $uid = 0)
  599. {
  600. $allusergkarr = self::getUserListData();
  601. if (empty($allusergkarr)) {
  602. return;
  603. }
  604. $allkfgkarr = self::getWorkKfData();
  605. if (empty($allkfgkarr)) {
  606. return;
  607. }
  608. $maxset = (self::$global->systemconfig)['KFMaxServices'] ?? 5;
  609. $maxset = intval($maxset);
  610. if ($group && $uid) {
  611. // 指定用指定组 [可能存在断线重连的情况] 如果存在旧的会话,直接连线客服和用户
  612. //否则按先到后到以及客服最大服务数限制
  613. $last = self::UserHasOldTalk($uid);
  614. if ($last) {
  615. self::BeginTalk(self::getkfuid($last['kf_id']), $uid, $last['group_id'], $last['servicelog_id']);
  616. return;
  617. }
  618. }
  619. //系统定时调用时,无组,无用户
  620. foreach ($allusergkarr as $group => $gusersArr) {
  621. if (!isset($allkfgkarr[$group]) || count($allkfgkarr[$group]) <= 0) {
  622. //所属客服组无人在线
  623. continue;
  624. }
  625. $nowkfs = $allkfgkarr[$group];
  626. $count = count($nowkfs);
  627. $i = 0;
  628. foreach ($gusersArr as $user) {
  629. if ($nowkfs[$i]['task'] > $maxset) {
  630. break;
  631. }
  632. $nowkfs[$i]['task']++;
  633. self::BeginTalk($nowkfs[$i]['id'], $user['id'], $group, 0, $user);
  634. self::$redis->hdel(self::USERLIST, $user['id']);
  635. $i++;
  636. if ($i >= $count) {
  637. $i = 0;
  638. }
  639. }
  640. }
  641. return;
  642. }
  643. //开启一个会话
  644. private static function BeginTalk($kfuid, $uid, $group, $serviceid = 0, $userInfo = false)
  645. {
  646. $serviceid = intval($serviceid);
  647. if (!$userInfo) {
  648. $userInfo = json_decode(self::$redis->hget(self::USERINFOKEY, $uid), true);
  649. }
  650. $kfinfo = json_decode(self::$redis->hget(self::KFINFOKEY, $kfuid), true);
  651. if (empty($userInfo) || empty($kfinfo)) {
  652. return false;
  653. }
  654. $server = [];
  655. $armarr = [];
  656. if ($serviceid) {
  657. $server = self::$db->select('*')->from('ws_service_log')->where("servicelog_id=$serviceid ")->row();
  658. if ($server) {
  659. $armarr = self::$db->select('*')->from('ws_alarm')->where("servicelog_id=$serviceid ")->row();
  660. }
  661. }
  662. if (empty($server)) {
  663. $array = [
  664. 'user_id' => $uid,
  665. 'client_id' => $userInfo['client_id'],
  666. 'user_name' => $userInfo['name'],
  667. 'user_avatar' => $userInfo['avatar'],
  668. 'user_ip' => $userInfo['ip'],
  669. 'kf_id' => self::getkfid($kfuid),
  670. 'start_time' => time(),
  671. 'group_id' => $userInfo['group'],
  672. 'website' => $userInfo['website'],
  673. 'system' => $userInfo['system'],
  674. 'browse' => $userInfo['browse'],
  675. 'intime' => $userInfo['intime'],
  676. ];
  677. $serviceid = self::$db->insert('ws_service_log')->cols($array)->query();
  678. $server = array_merge(['servicelog_id' => $serviceid], $array);
  679. $armid = self::$db->insert('ws_alarm')->cols(['servicelog_id' => $serviceid])->query();
  680. $armarr = self::$db->select('*')->from('ws_alarm')->where("alarm_id=$armid")->row();
  681. }
  682. $redisData = array_merge($server, $armarr, ['kf_client_id' => $kfinfo['client_id']]);
  683. self::$redis->hset(self::SERVICELOG, $serviceid, json_encode($redisData, 256));
  684. $kfinfo['user_info'] = array_merge($kfinfo['user_info'], [$userInfo['client_id'] => $serviceid]);
  685. $kfinfo['task'] = count($kfinfo['user_info']);
  686. self::$redis->hset(self::KFINFOKEY, $kfuid, json_encode($kfinfo, 256));
  687. $userInfo['serverid'] = $serviceid;
  688. $userInfo['kfuid'] = $kfuid;
  689. self::$redis->hset(self::USERINFOKEY, $uid, json_encode($userInfo, 256));
  690. // 通知会员发送信息绑定客服的id
  691. $noticeUser = [
  692. 'message_type' => 'connect',
  693. 'data' => [
  694. 'kf_id' => $kfuid,
  695. 'conversationId' => $serviceid,
  696. 'serverInfo' => $kfinfo,
  697. 'kf_name' => $kfinfo['job_name']
  698. ]
  699. ];
  700. self::MySendMsg($userInfo['client_id'], json_encode($noticeUser, 256));
  701. $sayHello = self::$db->query('select `word`,`status` from `ws_reply` where `id` = 2');
  702. if (!empty($sayHello) && 1 == $sayHello['0']['status']) {
  703. $chat_message = [
  704. 'message_type' => 'chatMessage',
  705. 'data' => [
  706. 'id' => self::getkfuid($kfinfo['id']),
  707. 'name' => $kfinfo['name'],
  708. 'time' => date('H:i'),
  709. 'content' => $sayHello['0']['word']
  710. ]
  711. ];
  712. self::MySendMsg($userInfo['client_id'], json_encode($chat_message, 256));
  713. unset($chat_message);
  714. }
  715. $noticeKf = [
  716. 'message_type' => 'connect',
  717. 'data' => [
  718. 'user_info' => $userInfo,
  719. 'conversationId' => $serviceid,
  720. ]
  721. ];
  722. self::MySendMsg($kfinfo['client_id'], json_encode($noticeKf, 256));
  723. unset($noticeKf);
  724. $key = date('Ymd') . 'success_in';
  725. $oldKey = date('Ymd', strtotime('-1 day')); // 删除前一天的统计值
  726. unset(self::$global->$oldKey);
  727. self::$global->increment($key);
  728. return;
  729. }
  730. //用户排队数据 按组
  731. private static function getUserListData()
  732. {
  733. $alluser = self::$redis->hgetall(self::USERLIST);
  734. if (empty($alluser)) {
  735. return false;
  736. }
  737. $allusergkarr = [];
  738. foreach ($alluser as $val) {
  739. $now = json_decode($val, true);
  740. if ($now) {
  741. //用户分组后的数组
  742. $allusergkarr[$now['group']][] = $now;
  743. }
  744. }
  745. foreach ($allusergkarr as $group => $nowgroups) {
  746. usort($allusergkarr[$group], function ($a, $b) {
  747. if ($a['intime'] == $b['intime']) {
  748. return 0;
  749. }
  750. return ($a['intime'] > $b['intime']) ? 1 : -1;
  751. });
  752. }
  753. if (!$allusergkarr) {
  754. return false;
  755. }
  756. unset($alluser);
  757. return $allusergkarr;
  758. }
  759. //找到可以接工单的客服 按组
  760. private static function getWorkKfData()
  761. {
  762. $allkfs = self::$redis->hgetall(self::KFINFOKEY);
  763. if (empty($allkfs)) {
  764. return false;
  765. }
  766. $allkfgkarr = [];
  767. foreach ($allkfs as $val) {
  768. $now = json_decode($val, true);
  769. if ($now && $now['status'] == 1) {
  770. //客分组后的数组
  771. $allkfgkarr[$now['group']][] = $now;
  772. }
  773. }
  774. if (!$allkfgkarr) {
  775. return false;
  776. }
  777. //客服每组按任务数由小到大排序 任务相同时按时间先后顺序
  778. foreach ($allkfgkarr as $group => $nowgroups) {
  779. usort($allkfgkarr[$group], function ($a, $b) {
  780. if ($a['task'] == $b['task']) {
  781. if ($a['intime'] == $b['intime']) {
  782. return 0;
  783. }
  784. return ($a['intime'] > $b['intime']) ? 1 : -1;
  785. }
  786. return ($a['task'] > $b['task']) ? 1 : -1;
  787. });
  788. }
  789. unset($allkfs);
  790. return $allkfgkarr;
  791. }
  792. //找到用户是否有一条未关闭的会话
  793. private static function UserHasOldTalk($uid)
  794. {
  795. $uid = intval($uid);
  796. $start_time = time() - 86400;
  797. $ret = self::$db->select('*')->from('ws_service_log')->where("start_time>=$start_time and user_id=$uid and status!=2 ")->orderByDESC(['servicelog_id'])->row();
  798. return $ret;
  799. }
  800. //今天排序累加
  801. private static function todayqueuelength()
  802. {
  803. $dtype = 'user.queue.day.length';
  804. $today = date("Y-m-d");
  805. $sret = self::$db->select('*')->from('ws_countmidtable')->where('dtype=:dtype and mdate=:mdate')->bindValues(array('dtype' => $dtype, 'mdate' => $today))->row();
  806. if ($sret) {
  807. self::$db->update('ws_countmidtable')->cols(array('dcontent' => intval($sret['dcontent']) + 1))->where('id=' . $sret['id'])->query();
  808. } else {
  809. self::$db->insert('ws_countmidtable')->cols(array(
  810. 'dtype' => $dtype,
  811. 'mdate' => $today,
  812. 'datatype' => 1,
  813. 'dcontent' => 1))->query();
  814. }
  815. }
  816. //客服工单转单
  817. private static function servicetrutoother($type, $owen, $otherkfid, $serverid, $clientuid)
  818. {
  819. $owen = intval(substr($owen, 2));
  820. $otherkfid = intval(substr($otherkfid, 2));
  821. self::$db->insert('ws_serviceturn_log')->cols(array(
  822. 'stype' => $type,
  823. 'uid' => $owen,
  824. 'tuid' => $otherkfid,
  825. 'serverid' => $serverid,
  826. 'guestuid' => $clientuid
  827. ))->query();
  828. }
  829. /**
  830. * 给客服分配会员【均分策略】
  831. * @param $kfList
  832. * @param $userList
  833. * @param $group
  834. * @param $total
  835. */
  836. private static function assignmentTask($kfList, $userList, $group, $total, $uid = 0)
  837. {
  838. }
  839. /**
  840. * 获取最大的服务人数
  841. * @return int
  842. */
  843. private static function getMaxServiceNum()
  844. {
  845. $maxNumber = self::$db->query('select `max_service` from `ws_kf_config` where `id` = 1');
  846. if (!empty($maxNumber)) {
  847. $maxNumber = 5;
  848. } else {
  849. $maxNumber = $maxNumber['0']['max_service'];
  850. }
  851. return $maxNumber;
  852. }
  853. /**
  854. * 将内存中的数据写入统计表
  855. * @param int $flag
  856. */
  857. private static function writeLog($flag = 1)
  858. {
  859. }
  860. /**
  861. * 机器人问答
  862. * @param $client_id 服务ID
  863. * @param $message 数据
  864. */
  865. private static function toRobot($client_id, $message)
  866. {
  867. $groups_id = $message['data']['groups_id'];
  868. $robot_name = $message['data']['robot_name'];
  869. $robotgroups_id = $message['data']['robotgroups_id'];
  870. // 查询问题.
  871. $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 . "'");
  872. $chat_message = [
  873. 'message_type' => 'robotMessage',
  874. //'message_type' => 'chatMessage',
  875. 'data' => [
  876. 'name' => '智能助手',
  877. 'time' => date('H:i'),
  878. 'content' => $getRobot ? $getRobot[0]['robot_content'] : 'error',
  879. ]
  880. ];
  881. Gateway::sendToClient($client_id, json_encode($chat_message, 256));
  882. }
  883. /**
  884. * 评价
  885. * @param $client_id 服务ID
  886. * @param $message 数据
  887. */
  888. private static function evaluate($client_id, $message)
  889. {
  890. // 修改数据库.
  891. $evaluate_id = $message['data']['evaluate_id'];
  892. $result = self::$db->query("UPDATE `ws_service_log` SET `evaluate_id` = '" . $evaluate_id . "' WHERE `client_id`='" . $client_id . "'");
  893. if ($result) {
  894. $chat_message = [
  895. 'message_type' => 'evaluate',
  896. 'data' => [
  897. 'status' => 1,
  898. 'time' => date('H:i'),
  899. ]
  900. ];
  901. } else {
  902. $chat_message = [
  903. 'message_type' => 'evaluate',
  904. 'data' => [
  905. 'status' => 2,
  906. 'time' => date('H:i'),
  907. ]
  908. ];
  909. }
  910. Gateway::sendToClient($client_id, json_encode($chat_message, 256));
  911. }
  912. //获取系统配置
  913. private static function upsystemconfig()
  914. {
  915. $systemConfigData = self::$db->query("SELECT * FROM `ws_systemconfig`");
  916. $arr = [];
  917. if ($systemConfigData) {
  918. foreach ($systemConfigData as $item) {
  919. $arr[$item['systemconfig_enName']] = $item;
  920. }
  921. self::$global->systemconfig = $arr;
  922. }
  923. $group = self::$db->query("SELECT * FROM `ws_groups`");
  924. $arr = [];
  925. if ($group) {
  926. foreach ($group as $val) {
  927. $arr[$val['id']] = $val['name'];
  928. }
  929. self::$global->groupmap = $arr;
  930. }
  931. //$sayHello = self::$db->query('select `word`,`status` from `ws_reply` where `id` = 2');
  932. }
  933. /**
  934. * 超时
  935. * @param $client_id 服务ID
  936. * @param $message 数据
  937. */
  938. private static function overTime()
  939. {
  940. // 查询对话时效设置.
  941. $systemConfigData = self::$db->query("SELECT `systemconfig_data`,`systemconfig_enName`,`systemconfig_content` FROM `ws_systemconfig`");
  942. foreach ($systemConfigData as $k => $v) {
  943. if ($v['systemconfig_enName'] == 'overtime') {
  944. $configOvertime = $v;
  945. } elseif ($v['systemconfig_enName'] == 'unoperated') {
  946. $configUnoperated = $v;
  947. }
  948. }
  949. // 查询未断开的工单.
  950. $serviceLog = self::$redis->hGetall('SERVICELOG');
  951. $setOvertime = strtotime('-' . ($configOvertime['systemconfig_data'] - 60) . ' second');
  952. $overtime = strtotime('-' . ($configOvertime['systemconfig_data']) . ' second');
  953. $setUnoperated = strtotime('-' . ($configUnoperated['systemconfig_data'] - 60) . ' second');
  954. $unoperated = strtotime('-' . ($configUnoperated['systemconfig_data']) . ' second');
  955. foreach ($serviceLog as $k => $v) {
  956. // 无效会话关闭.如果没有说一句话.
  957. $data = json_decode($v, true);
  958. if (!isset($data['userLastTime'])) {
  959. if ($data['start_time'] <= $unoperated) {
  960. self::serverClose($k);
  961. // 如果小于设定时间前一分钟则给出提示.
  962. } elseif ($data['start_time'] <= $setUnoperated) {
  963. $chat_message = [
  964. 'message_type' => 'overtime',
  965. 'data' => [
  966. 'content' => self::$global->unoperated['systemconfig_content'],
  967. ]
  968. ];
  969. Gateway::sendToClient($data['client_id'], json_encode($chat_message, 256));
  970. }
  971. // 双方静默超时.
  972. } elseif ($data['userLastTime'] <= $overtime && $data['serverLastTime'] <= $overtime) {
  973. self::serverClose($k);
  974. // 如果小于设定时间前一分钟则给出提示.
  975. } elseif ($data['userLastTime'] <= $setOvertime && $data['serverLastTime'] <= $setOvertime) {
  976. $chat_message = [
  977. 'message_type' => 'overtime',
  978. 'data' => [
  979. 'content' => self::$global->overtime['systemconfig_content'],
  980. ]
  981. ];
  982. Gateway::sendToClient($data['client_id'], json_encode($chat_message, 256));
  983. }
  984. }
  985. }
  986. /**
  987. * 系统监控
  988. * @param $message 数据
  989. */
  990. private static function systemMonitoring($adminList)
  991. {
  992. // 查询正进行的工单.
  993. $serviceLog = self::$redis->hGetall('SERVICELOG');
  994. // 查询系统设置表.
  995. $systemconfig = self::$db->query("SELECT `systemconfig_data`,`systemconfig_enName` FROM `ws_systemconfig` WHERE `systemconfig_enName`='verifyReturnTime' or `systemconfig_enName`='verifyAllTime'");
  996. // 质检会话响应时长.
  997. $returnTimeKey = array_search('verifyReturnTime', array_column($systemconfig, 'systemconfig_enName'));
  998. $verifyReturnTime = $systemconfig[$returnTimeKey]['systemconfig_data'];
  999. // 质检会话时长.
  1000. $allTimeKey = array_search('verifyAllTime', array_column($systemconfig, 'systemconfig_enName'));
  1001. $verifyAllTime = $systemconfig[$allTimeKey]['systemconfig_data'];
  1002. $evaluateCount = 0; // 差评总次数.
  1003. $overtimeNumber = 0; // 会话超时总次数.
  1004. $overtimeTime = []; // 每次会话超时时间.
  1005. $userSensitive = 0; // 用户敏感词报警总次数.
  1006. $serverSensitive = 0; // 客服敏感词报警总次数.
  1007. $csdNumber = 0; // 响应超时总次数.
  1008. $csdTime = []; // 每次响应超时时间.
  1009. foreach ($serviceLog as $k => $v) {
  1010. $data = json_decode($v, true);
  1011. // 工单报警次数.
  1012. $allCount = 0;
  1013. if ($data['evaluate_id'] == 3) {
  1014. $evaluateCount++; // 差评次数.
  1015. $allCount++; // 工单报警次数.
  1016. }
  1017. // 会话超时.
  1018. $duration = time() - $data['start_time'];
  1019. if ($duration > $verifyAllTime) {
  1020. $overtimeNumber++; // 会话超时总次数.
  1021. $allCount++; // 工单报警次数.
  1022. $overtimeTime[] = $duration; // 响应超时时间.
  1023. }
  1024. // 敏感词报警.
  1025. $userSensitive += $data['alarm_userSensitive'];
  1026. $allCount += $data['alarm_userSensitive'];
  1027. $serverSensitive += $data['alarm_serverSensitive'];
  1028. $allCount += $data['alarm_serverSensitive'];
  1029. // 响应超时.
  1030. if ($data['alarm_corresponding'] > $verifyReturnTime) {
  1031. $csdTime[] = $data['alarm_corresponding']; // 响应超时时间.
  1032. $csdNumber++; // 响应超时总次数.
  1033. $allCount++; // 工单报警次数.
  1034. }
  1035. $serviceLog[$k] = $data;
  1036. $serviceLog[$k]['allCount'] = $allCount; // 工单报警次数.
  1037. }
  1038. self::DebugOut([$serviceLog, $csdTime, $verifyReturnTime], 'systemMonitoring');
  1039. // 查询对话时效设置.
  1040. foreach ($adminList as $v) {
  1041. $chat_message = [
  1042. 'message_type' => 'monitor',
  1043. 'data' => [
  1044. 'cvtList' => $serviceLog,
  1045. 'userSensitive' => $userSensitive,
  1046. 'serverSensitive' => $serverSensitive,
  1047. 'csdNumber' => $csdNumber,
  1048. 'csdTime' => $csdTime,
  1049. 'overtimeNumber' => $overtimeNumber,
  1050. 'overtimeTime' => $overtimeTime,
  1051. 'evaluateCount' => $evaluateCount,
  1052. ]
  1053. ];
  1054. Gateway::sendToClient($v, json_encode($chat_message, 256));
  1055. }
  1056. }
  1057. //客服在线状态写组
  1058. private static function writeLogKfStatus($kf, $status, $flag = 1)
  1059. {
  1060. if ($flag == 1) {
  1061. $status = intval($status);
  1062. if ($status == 0) {
  1063. self::$db->delete('ws_kfonline')->where("uid='$kf'")->query();
  1064. } else {
  1065. $now = date('Y-m-d H:i;s');
  1066. $ip = isset($_SESSION['remotip']) ? $_SESSION['remotip'] : '';
  1067. $sql = "insert into ws_kfonline(uid,status,uptime,ip) values('$kf',$status,'$now','$ip') ON DUPLICATE KEY UPDATE status=$status,uptime='$now' ";
  1068. self::$db->query($sql);
  1069. }
  1070. } else {
  1071. self::$db->query("delete from ws_kfonline ");
  1072. }
  1073. }
  1074. public static function resetServiceLog($kfid = 0)
  1075. {
  1076. $t = time() - 24 * 3600 * 7;
  1077. if ($kfid) {
  1078. if ((substr($kfid, 0, 2) == 'KF')) {
  1079. $kfid = intval(substr($kfid, 2));
  1080. }
  1081. $kfid = intval($kfid);
  1082. self::$db->query("update ws_service_log set status=2 where kf_id=$kfid and start_time>=$t and status!=2");
  1083. self::$redis->hdel(self::KFINFOKEY, 'KF' . $kfid);
  1084. } else {
  1085. self::$redis->del(self::KFINFOKEY);
  1086. self::$redis->del(self::USERLIST);
  1087. self::$redis->del(self::USERINFOKEY);
  1088. self::$db->query("update ws_service_log set status=2 where start_time>=$t and status!=2");
  1089. }
  1090. }
  1091. public static function onWorkerStop($businessWorker)
  1092. {
  1093. if ($businessWorker->worker_id == 1) {
  1094. self::resetServiceLog();
  1095. }
  1096. }
  1097. //用户下线通知
  1098. private static function userCloseNotice($client_id, $cuid, $group)
  1099. {
  1100. }
  1101. //踢掉同一用户的旧用户
  1102. private static function tickOlduser($uid)
  1103. {
  1104. }
  1105. private static function DebugOut($msg, $title = '', $type = 'info')
  1106. {
  1107. $config = self::$global->systemconfig;
  1108. if (!isset($config['isdebug']) || empty($config['isdebug']['systemconfig_data'])) {
  1109. return;
  1110. }
  1111. if (!is_string($msg)) {
  1112. $msg = json_encode([$msg], 256);
  1113. }
  1114. $msg = date("Y-m-d H:i:s") . ' - ' . $type . ' - ' . $title . ' - ' . $msg . "\n";
  1115. echo $msg;
  1116. }
  1117. //定时器相关
  1118. private static function TimerThing($worker)
  1119. {
  1120. // 当天的累积接入值
  1121. $key = date('Ymd') . 'total_in';
  1122. if (is_null(self::$global->$key)) {
  1123. self::$global->$key = 0;
  1124. $oldKey = date('Ymd', strtotime('-1 day')); // 删除前一天的统计值
  1125. unset(self::$global->$oldKey);
  1126. unset($oldKey, $key);
  1127. }
  1128. // 成功接入值
  1129. $key = date('Ymd') . 'success_in';
  1130. if (is_null(self::$global->$key)) {
  1131. self::$global->$key = 0;
  1132. $oldKey = date('Ymd', strtotime('-1 day')); // 删除前一天的统计值
  1133. unset(self::$global->$oldKey);
  1134. unset($oldKey, $key);
  1135. }
  1136. // 定时统计数据
  1137. if (0 == $worker->id) {
  1138. self::writeLogKfStatus(0, 0, 0);
  1139. //初始化.....
  1140. self::upsystemconfig();
  1141. //每5分钟更新一次系统配置文件
  1142. Timer::add(60 * 3, function () {
  1143. self::upsystemconfig();
  1144. });
  1145. self::resetServiceLog();
  1146. }
  1147. }
  1148. //调试使用
  1149. public static function mydebug($client_id, $message)
  1150. {
  1151. $ret = self::$db->insert('ws_service_log')->cols(array(
  1152. 'user_id' => 1,
  1153. 'client_id' => 'acasdfasf',
  1154. 'user_name' => 'test',
  1155. 'user_avatar' => '',
  1156. 'user_ip' => '',
  1157. 'kf_id' => 1,
  1158. 'start_time' => 1212,
  1159. 'group_id' => 4,
  1160. 'website' => '',
  1161. 'system' => '',
  1162. 'browse' => ''
  1163. ))->query();
  1164. print_r($ret);
  1165. }
  1166. public static function MySendMsg($clientId, $msg)
  1167. {
  1168. Gateway::sendToClient($clientId, $msg);
  1169. }
  1170. //得到客服的UID字符值
  1171. public static function getkfuid($uid)
  1172. {
  1173. if (substr($uid, 0, 2) == 'KF') {
  1174. return $uid;
  1175. } else {
  1176. return 'KF' . intval($uid);
  1177. }
  1178. }
  1179. //得到客服的ID整数值
  1180. public static function getkfid($id)
  1181. {
  1182. if (strtolower(substr($id, 0, 2)) == 'kf') {
  1183. return intval(substr($id, 2));
  1184. }
  1185. return intval($id);
  1186. }
  1187. //从数组中获取参数
  1188. public static function getPars($array, $key, $default = '')
  1189. {
  1190. if (isset($array[$key])) {
  1191. return $array[$key];
  1192. }
  1193. return $default;
  1194. }
  1195. //获取在线客服信息
  1196. public static function getOnlineKfData($group = 0, $status = 0)
  1197. {
  1198. $all = self::$redis->hgetall(self::KFINFOKEY);
  1199. if (!$all) {
  1200. return false;
  1201. }
  1202. $return = [];
  1203. foreach ($all as $val) {
  1204. $now = json_decode($val, true);
  1205. if ($group) {
  1206. if ($now['group'] != $group) {
  1207. continue;
  1208. }
  1209. }
  1210. if ($status) {
  1211. if ($now['status'] != $status) {
  1212. continue;
  1213. }
  1214. }
  1215. $return[$now['id']] = $now;
  1216. }
  1217. return $return;
  1218. }
  1219. //找到在排队的用户按时间先后顺序
  1220. public static function getUselistData($group)
  1221. {
  1222. $all = self::$redis->hgetall(self::USERLIST);
  1223. if (!$all) {
  1224. return false;
  1225. }
  1226. $return = [];
  1227. foreach ($all as $val) {
  1228. $now = json_decode($val, true);
  1229. if ($group == $now['group']) {
  1230. $return[] = $now;
  1231. }
  1232. }
  1233. usort($return, function ($a, $b) {
  1234. if ($a['intime'] == $b['intime']) {
  1235. return 0;
  1236. }
  1237. return $a['intime'] > $b['intime'] ? 1 : -1;
  1238. });
  1239. return $return;
  1240. }
  1241. //对客服的用户user_info数组进行加减操作 $clientid用户连接号 opt=1添加 0删除 $serverid服务工单号
  1242. public static function ArrayDataopt($array, $clientid, $opt, $serverid = 0)
  1243. {
  1244. if (!is_array($array)) {
  1245. return [];
  1246. }
  1247. if ($opt == 0) {
  1248. if (isset($array[$clientid])) {
  1249. unset($array[$clientid]);
  1250. }
  1251. return $array;
  1252. } else {
  1253. $array[$clientid] = $serverid;
  1254. return $array;
  1255. }
  1256. }
  1257. }