Events.php 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788
  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. /**
  37. * 进程启动后初始化数据库连接
  38. */
  39. public static function onWorkerStart($worker)
  40. {
  41. include_once(__DIR__ . DIRECTORY_SEPARATOR . "Mlogic.php");
  42. self::$logic = Mlogic::GetInstance();
  43. self::$db = self::$logic->getDb();
  44. self::$redis = self::$logic->getRedis();
  45. self::$global = self::$logic->getGlbData();
  46. self::TimerThing($worker);
  47. }
  48. /**
  49. * 每分钟定时向客服发送一次排队情况
  50. */
  51. public static function lineup()
  52. {
  53. }
  54. /**
  55. * 当客户端连接时触发
  56. * 如果业务不需此回调可以删除onConnect
  57. *
  58. * @param int $client_id 连接id
  59. */
  60. public static function onConnect($client_id)
  61. {
  62. // 检测是否开启自动应答
  63. $sayHello = self::$db->query('select `word`,`status` from `ws_reply` where `id` = 1');
  64. if (!empty($sayHello) && 1 == $sayHello['0']['status']) {
  65. $hello = [
  66. 'message_type' => 'helloMessage',
  67. 'data' => [
  68. 'name' => '智能助手',
  69. 'time' => date('H:i'),
  70. 'content' => $sayHello['0']['word']
  71. ]
  72. ];
  73. Gateway::sendToClient($client_id, json_encode($hello, 256));
  74. unset($hello);
  75. }
  76. unset($sayHello);
  77. // 检测是否开启广告
  78. $advertisement = self::$db->query('select * from `ws_advertisement` where `advertisement_status` = 1');
  79. if (!empty($advertisement)) {
  80. $chat_message = [
  81. 'message_type' => 'advertisement',
  82. 'data' => $advertisement
  83. ];
  84. Gateway::sendToClient($client_id, json_encode($chat_message, 256));
  85. unset($chat_message);
  86. }
  87. unset($advertisement);
  88. }
  89. /**
  90. * 当客户端发来消息时触发
  91. * @param int $client_id 连接id
  92. * @param mixed $message 具体消息
  93. */
  94. public static function onMessage($client_id, $message)
  95. {
  96. if ($message == '{"type":"ping"}') {
  97. Gateway::sendToCurrentClient('{"type":"pong"}');
  98. return;
  99. } else {
  100. self::DebugOut($message, "OnMessage");
  101. self::DebugOut([self::$global->kfList, self::$global->userList, self::$global->uidSimpleList, self::$global->userToKf, $_SESSION['remotip'] . ':' . $_SESSION['remotport']], 'Msg mem: ');
  102. }
  103. $message = json_decode($message, true);
  104. if (isset($message['type'])) {
  105. switch ($message['type']) {
  106. case 'mydebug':
  107. self::mydebug($client_id, $message['data']);
  108. break;
  109. // 管理员初始化
  110. case 'adminInit':
  111. $token = $message['token'];
  112. self::adminInit($client_id, $token);
  113. break;
  114. // 客服初始化
  115. case 'init':
  116. $data = $message['data'];
  117. self::Kfinit($client_id, $data);
  118. break;
  119. // 顾客初始化
  120. case 'userInit';
  121. $data = $message['data'];
  122. self::userInitEnt($client_id, $data);
  123. break;
  124. //在线客服信息
  125. case 'getkfonlines':
  126. Gateway::sendToCurrentClient(json_encode(self::getkfonlines(), 256));
  127. break;
  128. case 'kfgetuserinfo':
  129. $tmp_id = isset($message['data']['id']) ? $message['data']['id'] : 0;
  130. self::kfgetuserinfo($client_id, intval($tmp_id));
  131. break;
  132. case 'chatMessage':
  133. break;
  134. // 转接
  135. case 'changeGroup':
  136. break;
  137. case 'closeUser':
  138. break;
  139. // 机器人问答.
  140. case 'toRobot':
  141. self::toRobot($client_id, $message);
  142. break;
  143. // 评价.
  144. case 'evaluate':
  145. self::evaluate($client_id, $message);
  146. break;
  147. // 客服关闭会话.
  148. case 'kfCloseUser':
  149. break;
  150. // 客服更改状态.
  151. case 'kfOnline':
  152. break;
  153. case 'changeOtherhKeFu';
  154. break;
  155. // 弹出评价.
  156. case 'getEvaluate';
  157. break;
  158. }
  159. }
  160. }
  161. //得到一个用户详细信息
  162. public static function kfgetuserinfo($clientid, $id)
  163. {
  164. $ret = self::$db->select('*')->from('ws_account')->where('id=:id')->bindValues(['id' => $id])->row();
  165. Gateway::sendToClient($clientid, json_encode(['message_type' => 'userdetailinfo', 'data' => $ret]));
  166. return;
  167. }
  168. //获取在线客服列表
  169. public static function getkfonlines()
  170. {
  171. }
  172. //客户工单内部组转接
  173. public static function changeOtherhKeFu($client_id, $smessage)
  174. {
  175. return;
  176. }
  177. //获取某个用户全部信息
  178. public static function getClientIndo($id)
  179. {
  180. $ret = self::$db->from('ws_accounts')->select("*")->where(['id' => $id])->row();
  181. return $ret;
  182. }
  183. //客服接入sock,及初始化
  184. public static function Kfinit($client_id, $message)
  185. {
  186. // TODO 尝试拉取用户来服务 [二期规划]
  187. }
  188. /**
  189. * 管理员
  190. * @param $client_id 服务ID
  191. * @param $message 数据
  192. */
  193. public static function adminInit($client_id, $token)
  194. {
  195. // 查询token是否存在.
  196. $systemConfigData = self::$db->query("SELECT `id` FROM `ws_admins` where `token`= '$token'");
  197. //print_r(self::$global->adminList);
  198. if ($systemConfigData) {
  199. $adminList = self::$global->adminList;
  200. $adminList[] = $client_id;
  201. self::$global->adminList = $adminList;
  202. self::systemMonitoring([$client_id]);
  203. } else {
  204. Gateway::closeClient($client_id);
  205. }
  206. }
  207. //客服登陆验证
  208. public static function KfloginCheck($client, $messageArray)
  209. {
  210. $uid = isset($messageArray['uid']) ? $messageArray['uid'] : '';
  211. $token = isset($messageArray['token']) ? $messageArray['token'] : '';
  212. if (empty($uid) || empty($token)) {
  213. return false;
  214. }
  215. $expire_time_vali = time() - 60 * 60 * 24;
  216. $kfid = intval(substr($uid, 2));
  217. $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();
  218. if ($ret) {
  219. self::$db->update('ws_users')->cols(array('online_status' => 1, 'online_connectid' => $client))->where('id=' . $kfid)->query();
  220. return $ret;
  221. }
  222. return false;
  223. }
  224. //用户发送邦定用户事件
  225. public static function userInitEnt($client_id, $message)
  226. {
  227. // 尝试分配新会员进入服务
  228. self::userOnlineTask($client_id, $message['group'], $message['uid']);
  229. }
  230. /**
  231. * 当用户断开连接时触发
  232. * @param int $client_id 连接id
  233. *
  234. * tips: 当服务端主动退出的时候,会出现 exit status 9.原因是:服务端主动断开之后,连接的客户端会走这个方法,而短时间内进程
  235. * 需要处理这多的逻辑,又有cas操作,导致进程退出会超时,然后会被内核杀死,从而报出错误 9.实际对真正的业务没有任何的影响。
  236. */
  237. public static function onClose($client_id)
  238. {
  239. $isKefuoff = isset($_SESSION['iskefu']) ? $_SESSION['iskefu'] : 0;
  240. $uid = isset($_SESSION['uid']) ? $_SESSION['uid'] : false;
  241. echo "下线:uid: $uid - cid: $client_id - iskf: $isKefuoff \n";
  242. $adminList = self::$global->adminList ?? [];
  243. $key = array_search($client_id, $adminList);
  244. if (strlen($key)) {
  245. array_splice($adminList, $key, 1);
  246. self::$global->adminList = $adminList;
  247. }
  248. if (empty($uid)) {
  249. return;
  250. }
  251. if ($isKefuoff) {
  252. self::serviceOffline($client_id, $uid);
  253. } else {
  254. self::guestOffline($client_id, $uid);
  255. }
  256. return;
  257. }
  258. //客服下线了
  259. public static function serviceOffline($client_id, $uid)
  260. {
  261. self::writeLogKfStatus($uid, 0);
  262. return;
  263. }
  264. //用户下线了
  265. public static function guestOffline($client_id, $uid)
  266. {
  267. }
  268. /**
  269. * 客服结束会话
  270. *
  271. * tips: 未有$client_id的关闭
  272. */
  273. public static function closeUser($servicelog_id, $userId, $kf_id, $groupId)
  274. {
  275. }
  276. /**
  277. * 客服结束会话
  278. * @param int $client_id 连接id
  279. *
  280. * tips: 当服务端主动退出的时候,会出现 exit status 9.原因是:服务端主动断开之后,连接的客户端会走这个方法,而短时间内进程
  281. * 需要处理这多的逻辑,又有cas操作,导致进程退出会超时,然后会被内核杀死,从而报出错误 9.实际对真正的业务没有任何的影响。
  282. */
  283. public static function serverClose($client_id, $servicelog_id, $userId, $kf_id, $groupId)
  284. {
  285. }
  286. /**
  287. * 有人退出
  288. * @param $group
  289. */
  290. private static function userOfflineTask($group)
  291. {
  292. }
  293. /**
  294. * 有人进入执行分配
  295. * @param $client_id
  296. * @param $group
  297. * @param $uid
  298. */
  299. private static function userOnlineTask($client_id, $group, $uid = 0)
  300. {
  301. }
  302. //今天排序累加
  303. private static function todayqueuelength()
  304. {
  305. $dtype = 'user.queue.day.length';
  306. $today = date("Y-m-d");
  307. $sret = self::$db->select('*')->from('ws_countmidtable')->where('dtype=:dtype and mdate=:mdate')->bindValues(array('dtype' => $dtype, 'mdate' => $today))->row();
  308. if ($sret) {
  309. self::$db->update('ws_countmidtable')->cols(array('dcontent' => intval($sret['dcontent']) + 1))->where('id=' . $sret['id'])->query();
  310. } else {
  311. self::$db->insert('ws_countmidtable')->cols(array(
  312. 'dtype' => $dtype,
  313. 'mdate' => $today,
  314. 'datatype' => 1,
  315. 'dcontent' => 1))->query();
  316. }
  317. }
  318. //客服工单转单
  319. private static function servicetrutoother($type, $owen, $otherkfid, $serverid, $clientuid)
  320. {
  321. $owen = intval(substr($owen, 2));
  322. $otherkfid = intval(substr($otherkfid, 2));
  323. self::$db->insert('ws_serviceturn_log')->cols(array(
  324. 'stype' => $type,
  325. 'uid' => $owen,
  326. 'tuid' => $otherkfid,
  327. 'serverid' => $serverid,
  328. 'guestuid' => $clientuid
  329. ))->query();
  330. }
  331. /**
  332. * 给客服分配会员【均分策略】
  333. * @param $kfList
  334. * @param $userList
  335. * @param $group
  336. * @param $total
  337. */
  338. private static function assignmentTask($kfList, $userList, $group, $total, $uid = 0)
  339. {
  340. }
  341. /**
  342. * 获取最大的服务人数
  343. * @return int
  344. */
  345. private static function getMaxServiceNum()
  346. {
  347. $maxNumber = self::$db->query('select `max_service` from `ws_kf_config` where `id` = 1');
  348. if (!empty($maxNumber)) {
  349. $maxNumber = 5;
  350. } else {
  351. $maxNumber = $maxNumber['0']['max_service'];
  352. }
  353. return $maxNumber;
  354. }
  355. /**
  356. * 将内存中的数据写入统计表
  357. * @param int $flag
  358. */
  359. private static function writeLog($flag = 1)
  360. {
  361. }
  362. /**
  363. * 机器人问答
  364. * @param $client_id 服务ID
  365. * @param $message 数据
  366. */
  367. private static function toRobot($client_id, $message)
  368. {
  369. $groups_id = $message['data']['groups_id'];
  370. $robot_name = $message['data']['robot_name'];
  371. $robotgroups_id = $message['data']['robotgroups_id'];
  372. // 查询问题.
  373. $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 . "'");
  374. $chat_message = [
  375. 'message_type' => 'robotMessage',
  376. //'message_type' => 'chatMessage',
  377. 'data' => [
  378. 'name' => '智能助手',
  379. 'time' => date('H:i'),
  380. 'content' => $getRobot ? $getRobot[0]['robot_content'] : 'error',
  381. ]
  382. ];
  383. Gateway::sendToClient($client_id, json_encode($chat_message, 256));
  384. }
  385. /**
  386. * 评价
  387. * @param $client_id 服务ID
  388. * @param $message 数据
  389. */
  390. private static function evaluate($client_id, $message)
  391. {
  392. // 修改数据库.
  393. $evaluate_id = $message['data']['evaluate_id'];
  394. $result = self::$db->query("UPDATE `ws_service_log` SET `evaluate_id` = '" . $evaluate_id . "' WHERE `client_id`='" . $client_id . "'");
  395. if ($result) {
  396. $chat_message = [
  397. 'message_type' => 'evaluate',
  398. 'data' => [
  399. 'status' => 1,
  400. 'time' => date('H:i'),
  401. ]
  402. ];
  403. } else {
  404. $chat_message = [
  405. 'message_type' => 'evaluate',
  406. 'data' => [
  407. 'status' => 2,
  408. 'time' => date('H:i'),
  409. ]
  410. ];
  411. }
  412. Gateway::sendToClient($client_id, json_encode($chat_message, 256));
  413. }
  414. //获取系统配置
  415. private static function upsystemconfig()
  416. {
  417. $systemConfigData = self::$db->query("SELECT * FROM `ws_systemconfig`");
  418. $arr = [];
  419. if ($systemConfigData) {
  420. foreach ($systemConfigData as $item) {
  421. $arr[$item['systemconfig_enName']] = $item;
  422. }
  423. self::$global->systemconfig = $arr;
  424. }
  425. $group = self::$db->query("SELECT * FROM `ws_groups`");
  426. $arr = [];
  427. if ($group) {
  428. foreach ($group as $val) {
  429. $arr[$val['id']] = $val['name'];
  430. }
  431. self::$global->groupmap = $arr;
  432. }
  433. }
  434. /**
  435. * 超时
  436. * @param $client_id 服务ID
  437. * @param $message 数据
  438. */
  439. private static function overTime()
  440. {
  441. // 查询对话时效设置.
  442. $systemConfigData = self::$db->query("SELECT `systemconfig_data`,`systemconfig_enName`,`systemconfig_content` FROM `ws_systemconfig`");
  443. foreach ($systemConfigData as $k => $v) {
  444. if ($v['systemconfig_enName'] == 'overtime') {
  445. self::$global->overtime = $v;
  446. } elseif ($v['systemconfig_enName'] == 'unoperated') {
  447. self::$global->unoperated = $v;
  448. } elseif ($v['systemconfig_enName'] == 'noResponse') {
  449. self::$global->noResponse = $v;
  450. }
  451. }
  452. // 查询未断开的工单.
  453. $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'");
  454. $whereOr = '1=0';
  455. foreach ($serviceLog as $k => $v) {
  456. if ($k == 0) {
  457. $whereOr = "`servicelog_id`=" . $v['servicelog_id'];
  458. } else {
  459. $whereOr .= " OR `servicelog_id`=" . $v['servicelog_id'];
  460. }
  461. }
  462. // 查询最后一次会话.
  463. //$chatLog = self::$db->query("SELECT `servicelog_id`,MAX(`time_line`) FROM `ws_chat_log` WHERE ".$whereOr." group by `servicelog_id`");
  464. $chatLog = self::$db->query("
  465. select * from ws_chat_log as a where time_line=(
  466. 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
  467. )
  468. ");
  469. $setOvertime = strtotime('-' . (self::$global->overtime['systemconfig_data'] - 60) . ' second');
  470. $overtime = strtotime('-' . (self::$global->overtime['systemconfig_data']) . ' second');
  471. $setUnoperated = strtotime('-' . (self::$global->unoperated['systemconfig_data'] - 60) . ' second');
  472. $unoperated = strtotime('-' . (self::$global->unoperated['systemconfig_data']) . ' second');
  473. $noResponse = strtotime('-' . (self::$global->noResponse['systemconfig_data']) . ' second');
  474. foreach ($serviceLog as $k => $v) {
  475. if (!strlen(array_search($v['servicelog_id'], array_column($chatLog, 'servicelog_id')))) {
  476. if ($v['start_time'] <= $unoperated) {
  477. $servicelog_id = $v['servicelog_id'];
  478. self::$db->query("update `ws_service_log` set `servicelog_close_type` = 1 where `servicelog_id`= '$servicelog_id'");
  479. self::serverClose($v['client_id'], $servicelog_id, $v['user_id'], 'KF' . $v['kf_id'], $v['group_id']);
  480. // 如果小于设定时间前一分钟则给出提示.
  481. } elseif ($v['start_time'] <= $setUnoperated) {
  482. $chat_message = [
  483. 'message_type' => 'overtime',
  484. 'data' => [
  485. 'content' => self::$global->unoperated['systemconfig_content'],
  486. ]
  487. ];
  488. Gateway::sendToClient($v['client_id'], json_encode($chat_message, 256));
  489. }
  490. }
  491. }
  492. // 双方静默超时.
  493. foreach ($chatLog as $k => $v) {
  494. // 如果对话为客服的最后一次对话且时间小于设定时间则结束工单.
  495. if ($v['time_line'] <= $overtime) {
  496. $found_key = array_search($v['servicelog_id'], array_column($serviceLog, 'servicelog_id'));
  497. $servicelog_id = $v['servicelog_id'];
  498. self::$db->query("update `ws_service_log` set `servicelog_close_type` = 2 where `servicelog_id`= '$servicelog_id'");
  499. 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']);
  500. // 如果对话为客服的最后一次对话且时间小于设定时间前一分钟则给出提示.
  501. } elseif ($v['time_line'] <= $setOvertime) {
  502. $chat_message = [
  503. 'message_type' => 'overtime',
  504. 'data' => [
  505. 'content' => self::$global->overtime['systemconfig_content'],
  506. ]
  507. ];
  508. $found_key = array_search($v['servicelog_id'], array_column($serviceLog, 'servicelog_id'));
  509. Gateway::sendToClient($serviceLog[$found_key]['client_id'], json_encode($chat_message, 256));
  510. }
  511. }
  512. }
  513. /**
  514. * 系统监控
  515. * @param $message 数据
  516. */
  517. private static function systemMonitoring($adminList)
  518. {
  519. // 查询未结束工单.
  520. $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
  521. from `ws_service_log`
  522. join `ws_alarm` on ws_service_log.servicelog_id=ws_alarm.servicelog_id
  523. join `ws_users` on ws_service_log.kf_id=ws_users.id
  524. WHERE ws_service_log.status='1' OR ws_service_log.status='3'");
  525. // 查询系统设置表.
  526. $systemconfig = self::$db->query("SELECT `systemconfig_data`,`systemconfig_enName` FROM `ws_systemconfig` WHERE `systemconfig_enName`='verifyReturnTime' or `systemconfig_enName`='verifyAllTime'");
  527. $returnTimeKey = array_search('verifyReturnTime', array_column($systemconfig, 'systemconfig_enName'));
  528. // 质检会话响应时长.
  529. $verifyReturnTime = $systemconfig[$returnTimeKey]['systemconfig_data'];
  530. $allTimeKey = array_search('verifyAllTime', array_column($systemconfig, 'systemconfig_enName'));
  531. // 质检会话时长.
  532. $verifyAllTime = $systemconfig[$allTimeKey]['systemconfig_data'];
  533. // 差评次数.
  534. $evaluateCount = 0;
  535. // 未结束工单id.
  536. $servicelog_ids = '';
  537. $overtimeNumber = 0; // 会话超时次数.
  538. $overtimeTime = []; // 会话超时时间.
  539. $userSensitive = 0; // 用户敏感词报警次数.
  540. $serverSensitive = 0; // 客服敏感词报警次数.
  541. $csdNumber = 0; // 响应超时次数.
  542. $csdTime = []; // 响应超时时间.
  543. foreach ($serviceLog as $k => $v) {
  544. // 工单报警总次数.
  545. $allCount = 0;
  546. // 差评次数.
  547. if ($v['evaluate_id'] == 3) {
  548. $evaluateCount++;
  549. $allCount++;
  550. }
  551. $duration = time() - $v['start_time'];
  552. // 会话超时.
  553. if ($duration > $verifyAllTime) {
  554. $overtimeNumber++;
  555. $allCount++;
  556. $overtimeTime[] = $duration;
  557. }
  558. // 敏感词报警.
  559. $userSensitive += $v['alarm_userSensitive'];
  560. $allCount += $v['alarm_userSensitive'];
  561. $serverSensitive += $v['alarm_serverSensitive'];
  562. $allCount += $v['alarm_serverSensitive'];
  563. // 响应超时.
  564. if ($v['alarm_corresponding'] > $verifyReturnTime) {
  565. $csdTime[] = $v['alarm_corresponding'];
  566. $csdNumber++;
  567. $allCount++;
  568. }
  569. $serviceLog[$k]['allCount'] = $allCount;
  570. }
  571. self::DebugOut([$serviceLog, $csdTime, $verifyReturnTime], 'systemMonitoring');
  572. // 查询对话时效设置.
  573. foreach ($adminList as $v) {
  574. $chat_message = [
  575. 'message_type' => 'monitor',
  576. 'data' => [
  577. 'cvtList' => $serviceLog,
  578. 'userSensitive' => $userSensitive,
  579. 'serverSensitive' => $serverSensitive,
  580. 'csdNumber' => $csdNumber,
  581. 'csdTime' => $csdTime,
  582. 'overtimeNumber' => $overtimeNumber,
  583. 'overtimeTime' => $overtimeTime,
  584. 'evaluateCount' => $evaluateCount,
  585. ]
  586. ];
  587. Gateway::sendToClient($v, json_encode($chat_message, 256));
  588. }
  589. }
  590. //客服在线状态写组
  591. private static function writeLogKfStatus($kf, $status, $flag = 1)
  592. {
  593. if ($flag == 1) {
  594. $status = intval($status);
  595. if ($status == 0) {
  596. self::$db->delete('ws_kfonline')->where("uid='$kf'")->query();
  597. } else {
  598. $now = date('Y-m-d H:i;s');
  599. $ip = isset($_SESSION['remotip']) ? $_SESSION['remotip'] : '';
  600. $sql = "insert into ws_kfonline(uid,status,uptime,ip) values('$kf',$status,'$now','$ip') ON DUPLICATE KEY UPDATE status=$status,uptime='$now' ";
  601. self::$db->query($sql);
  602. }
  603. } else {
  604. self::$db->query("delete from ws_kfonline ");
  605. }
  606. }
  607. public static function resetServiceLog($kfid = 0)
  608. {
  609. $t = time() - 24 * 3600;
  610. if ($kfid) {
  611. if ((substr($kfid, 0, 2) == 'KF')) {
  612. $kfid = intval(substr($kfid, 2));
  613. }
  614. $kfid = intval($kfid);
  615. self::$db->query("update ws_service_log set status=2 where kf_id=$kfid and start_time>=$t and status!=2");
  616. } else {
  617. self::$db->query("update ws_service_log set status=2 where start_time>=$t and status!=2");
  618. }
  619. }
  620. public static function onWorkerStop($businessWorker)
  621. {
  622. if ($businessWorker->worker_id == 1) {
  623. self::resetServiceLog();
  624. }
  625. }
  626. //用户下线通知
  627. private static function userCloseNotice($client_id, $cuid, $group)
  628. {
  629. }
  630. //踢掉同一用户的旧用户
  631. private static function tickOlduser($uid)
  632. {
  633. }
  634. private static function DebugOut($msg, $title = '', $type = 'info')
  635. {
  636. $config = self::$global->systemconfig;
  637. if (!isset($config['isdebug']) || empty($config['isdebug']['systemconfig_data'])) {
  638. return;
  639. }
  640. if (!is_string($msg)) {
  641. $msg = json_encode([$msg], 256);
  642. }
  643. $msg = date("Y-m-d H:i:s") . ' - ' . $type . ' - ' . $title . ' - ' . $msg . "\n";
  644. echo $msg;
  645. }
  646. //定时器相关
  647. private static function TimerThing($worker)
  648. {
  649. // 当天的累积接入值
  650. $key = date('Ymd') . 'total_in';
  651. if (is_null(self::$global->$key)) {
  652. self::$global->$key = 0;
  653. $oldKey = date('Ymd', strtotime('-1 day')); // 删除前一天的统计值
  654. unset(self::$global->$oldKey);
  655. unset($oldKey, $key);
  656. }
  657. // 成功接入值
  658. $key = date('Ymd') . 'success_in';
  659. if (is_null(self::$global->$key)) {
  660. self::$global->$key = 0;
  661. $oldKey = date('Ymd', strtotime('-1 day')); // 删除前一天的统计值
  662. unset(self::$global->$oldKey);
  663. unset($oldKey, $key);
  664. }
  665. // 定时统计数据
  666. if (0 == $worker->id) {
  667. self::writeLogKfStatus(0, 0, 0);
  668. //初始化.....
  669. self::upsystemconfig();
  670. //每5分钟更新一次系统配置文件
  671. Timer::add(60 * 3, function () {
  672. self::upsystemconfig();
  673. });
  674. self::resetServiceLog();
  675. }
  676. }
  677. //调试使用
  678. public static function mydebug($client_id, $message)
  679. {
  680. print_r(self::$redis);
  681. $v = self::$redis->hget('test', 't01');
  682. echo 'mydebug ' . $v . "\n";
  683. }
  684. }