Events.php 47 KB

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