Events.php 30 KB

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