Events.php 26 KB

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