Events.php 40 KB

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