Events.php 77 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148
  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. use Workerman\Worker;
  23. /**
  24. * 主逻辑
  25. * 主要是处理 onConnect onMessage onClose 三个方法
  26. * onConnect 和 onClose 如果不需要可以不用实现并删除
  27. */
  28. class Events
  29. {
  30. /**
  31. * 新建一个类的静态成员,用来保存数据库实例
  32. */
  33. public static $db = null;
  34. public static $global = null;
  35. public static $redis = null;
  36. public static $logic = null;
  37. const KFSERVICES = 'KFSERVICES'; //KFSERVICES:KF10 1213131=>22这样的 客服工单hash表 健为连接号,值为工单号
  38. const KFINFOKEY = 'KFINFO'; //客服信息hash表
  39. const USERINFOKEY = 'USERINFO'; //用户信息hash表
  40. const USERLIST = 'USERLIST'; //用户排队表
  41. const SERVICELOG = 'SERVICELOG'; //工单信息
  42. const WEBSOCKALLUSER = 'WEBSOCKALLUSER'; //所有连接
  43. const KFRELONINFLAG = 'KFRELOGIN'; //客服重登陆标示
  44. /**
  45. * 进程启动后初始化数据库连接
  46. */
  47. public static function onWorkerStart($worker)
  48. {
  49. include_once(__DIR__ . DIRECTORY_SEPARATOR . "Mlogic.php");
  50. self::$logic = Mlogic::GetInstance();
  51. self::$db = self::$logic->getDb();
  52. self::$redis = self::$logic->getRedis();
  53. self::$global = self::$logic->getGlbData();
  54. self::TimerThing($worker);
  55. }
  56. /**
  57. * 每分钟定时向客服发送一次排队情况
  58. */
  59. public static function lineup()
  60. {
  61. $group = self::$global->groupmap;
  62. foreach ($group as $groupid => $gname) {
  63. $users = self::getUselistData($groupid);
  64. if (!empty($users)) {
  65. Gateway::sendToGroup('group_' . $groupid, json_encode(['type' => 'lineupCount', 'data' => ['count' => count($users)]], 256));
  66. }
  67. }
  68. }
  69. /**
  70. * 当客户端连接时触发
  71. * 如果业务不需此回调可以删除onConnect
  72. *
  73. * @param int $client_id 连接id
  74. */
  75. public static function onConnect($client_id)
  76. {
  77. // 检测是否开启自动应答
  78. $sayHello = self::$global->systemReplay;
  79. if (!empty($sayHello)) {
  80. foreach ($sayHello as $v) {
  81. $hello = [
  82. 'message_type' => 'helloMessage',
  83. 'data' => [
  84. 'name' => '智能助手',
  85. 'time' => date('H:i'),
  86. 'content' => $v
  87. ]
  88. ];
  89. Gateway::sendToClient($client_id, json_encode($hello, 256));
  90. unset($hello);
  91. }
  92. }
  93. unset($sayHello);
  94. // 检测是否开启广告
  95. $advertisement = self::$db->query('select * from `ws_advertisement` where `advertisement_status` = 1');
  96. if (!empty($advertisement)) {
  97. $chat_message = [
  98. 'message_type' => 'advertisement',
  99. 'data' => $advertisement
  100. ];
  101. Gateway::sendToClient($client_id, json_encode($chat_message, 256));
  102. unset($chat_message);
  103. }
  104. unset($advertisement);
  105. self::$redis->hset(self::WEBSOCKALLUSER, $client_id, json_encode(['time' => date('H:i:s'), 'ip' => $_SERVER['REMOTE_ADDR'] . ':' . $_SERVER['REMOTE_PORT']]));
  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. //客服获取用户详细信息
  146. case 'kfgetuserinfo':
  147. $tmp_id = isset($message['data']['id']) ? $message['data']['id'] : 0;
  148. self::kfgetuserinfo($client_id, intval($tmp_id));
  149. break;
  150. // 客服聊天
  151. case 'chatMessage':
  152. self::chatMessage($message['data']);
  153. break;
  154. // 机器人问答.
  155. case 'toRobot':
  156. self::toRobot($client_id, $message);
  157. break;
  158. // 评价.
  159. case 'evaluate':
  160. self::evaluate($message['data']);
  161. break;
  162. // 客服关闭会话.
  163. case 'kfCloseUser':
  164. self::serverClose($message['data']['conversationId'], $message['data']['type']);
  165. break;
  166. // 客服更改状态.
  167. case 'kfOnline':
  168. self::KFStatusCg($client_id, $message);
  169. break;
  170. case 'changeOtherhKeFu';
  171. self::changeOtherhKeFu($client_id, $message);
  172. break;
  173. case 'userlabeall':
  174. self::getUserLabAll($client_id, $message);
  175. break;
  176. // 弹出评价.
  177. case 'getEvaluate';
  178. self::getEvaluate($message['data']);
  179. break;
  180. case 'debug':
  181. self::debug($message['data']);
  182. break;
  183. }
  184. }
  185. return true;
  186. }
  187. // 弹出评价.
  188. public static function getEvaluate($message)
  189. {
  190. // 获取当前会话工单.
  191. $data = json_decode(self::$redis->HGET('SERVICELOG', $message['conversationId']), true);
  192. if (empty($data)) {
  193. return;
  194. }
  195. $chat_message = [
  196. 'message_type' => 'getEvaluate',
  197. 'data' => [
  198. 'content' => '欢迎你的咨询,请对我们的服务做出评价',
  199. ]
  200. ];
  201. Gateway::sendToClient($data['client_id'], json_encode($chat_message, 256));
  202. }
  203. //客服聊天
  204. public static function chatMessage($message)
  205. {
  206. // 获取当前会话工单.
  207. $data = json_decode(self::$redis->HGET('SERVICELOG', $message['conversationId']), true);
  208. if (empty($data)) {
  209. return;
  210. }
  211. if (!Gateway::isOnline($data['kf_client_id'])) {
  212. $errorMessage = [
  213. 'message_type' => 'kfNotOnlin',
  214. 'data' => [
  215. 'error' => '客服不在线,可能无法及时应答',
  216. ]
  217. ];
  218. Gateway::sendToClient($data['client_id'], json_encode($errorMessage, 256));
  219. }
  220. $chat_message = [
  221. 'message_type' => 'chatMessage',
  222. 'data' => [
  223. 'name' => $message['from_name'],
  224. 'id' => $message['from_id'],
  225. 'time' => date('H:i'),
  226. 'content' => $message['content'],
  227. ]
  228. ];
  229. // 是否为第一次回复.
  230. if (isset($message['isFirst']) && $message['isFirst']) {
  231. $data['alarm_corresponding'] = time() - $data['start_time'];
  232. $data['alarm_respond'] = 2;
  233. }
  234. // 发送消息.
  235. if (substr($message['from_id'], 0, 2) === 'KF') {
  236. // 统计敏感词.
  237. $data['alarm_serverSensitive'] += $message['sensitiveNumber'];
  238. $data['serverLastTime'] = time();
  239. Gateway::sendToClient($data['client_id'], json_encode($chat_message, 256));
  240. } else {
  241. // 统计敏感词.
  242. $data['alarm_userSensitive'] += $message['sensitiveNumber'];
  243. $data['userLastTime'] = time();
  244. Gateway::sendToClient($data['kf_client_id'], json_encode($chat_message, 256));
  245. }
  246. // 返回当前时间
  247. $chat_message = [
  248. 'message_type' => 'webTime',
  249. 'data' => [
  250. 'webTime' => date('H:i'),
  251. ]
  252. ];
  253. Gateway::sendToCurrentClient(json_encode($chat_message, 256));
  254. // 保存修改后的工单信息.
  255. self::$redis->HSET('SERVICELOG', $message['conversationId'], json_encode($data, 256));
  256. // 聊天信息入库
  257. $insertChatData = [
  258. 'from_id' => $message['from_id'],
  259. 'from_name' => $message['from_name'],
  260. 'to_id' => $message['to_id'],
  261. 'to_name' => $message['to_name'],
  262. 'content' => $message['content'],
  263. 'servicelog_id' => $message['conversationId'],
  264. 'time_line' => time()
  265. ];
  266. self::$db->insert('ws_chat_log')->cols($insertChatData)->query();
  267. }
  268. //得到一个用户详细信息
  269. public static function kfgetuserinfo($clientid, $id)
  270. {
  271. $ret = self::$db->select('*')->from('ws_account')->where('id=:id')->bindValues(['id' => $id])->row();
  272. Gateway::sendToClient($clientid, json_encode(['message_type' => 'userdetailinfo', 'data' => $ret]));
  273. return;
  274. }
  275. //获取在线客服列表
  276. public static function getkfonlines()
  277. {
  278. $return = [
  279. 'message_type' => 'onlinekfs',
  280. 'data' => [],
  281. ];
  282. $nowkfid = isset($_SESSION['uid']) ? $_SESSION['uid'] : 0;
  283. $fromgrouupid = isset($_SESSION['group']) ? $_SESSION['group'] : 0;
  284. if (empty($fromgrouupid) || empty($nowkfid)) {
  285. return $return;
  286. }
  287. $online = self::getOnlineKfData(0, 1);
  288. if (empty($online)) {
  289. return $return;
  290. }
  291. $groupnamemap = self::$global->groupmap;
  292. $ret = [];
  293. foreach ($online as $uinfo) {
  294. if ($nowkfid == $uinfo['id']) {
  295. continue;
  296. }
  297. $ret[] = ['groupid' => $uinfo['group'], 'groupname' => $groupnamemap[$uinfo['group']], 'kfuid' => $uinfo['id'], 'kfname' => $uinfo['name'], 'kfjobname' => $uinfo['job_name']];
  298. }
  299. $return['data'] = $ret;
  300. return $return;
  301. }
  302. public static function KFStatusCg($client_id, $message)
  303. {
  304. if (!isset($_SESSION['iskefu']) || $_SESSION['iskefu'] != 1) {
  305. return;
  306. }
  307. $userId = $message['data']['uid'];
  308. $status = intval($message['data']['status']);
  309. if (!in_array($status, [1, 2, 3])) {
  310. return false;
  311. }
  312. $oldstatus = '';
  313. $kfinfo = self::$redis->hget(self::KFINFOKEY, $userId);
  314. if (empty($kfinfo)) {
  315. return false;
  316. }
  317. $kfinfo = json_decode($kfinfo, true);
  318. if (!$kfinfo) {
  319. return false;
  320. }
  321. if ($kfinfo['status'] != $status) {
  322. $oldstatus = $kfinfo['status'];
  323. $kfinfo['status'] = $status;
  324. self::$redis->hset(self::KFINFOKEY, $userId, json_encode($kfinfo, 256));
  325. }
  326. self::writeLogKfStatus($userId, $status);
  327. Gateway::sendToCurrentClient(json_encode(['message_type' => 'cgstatus', 'data' => ['new_status' => $status, 'old_status' => $oldstatus]]));
  328. return;
  329. }
  330. //获取某个用户全部信息
  331. public static function getClientIndo($id)
  332. {
  333. $ret = self::$db->from('ws_accounts')->select("*")->where(['id' => $id])->row();
  334. return $ret;
  335. }
  336. //客服接入sock,及初始化
  337. public static function Kfinit($client_id, $message)
  338. {
  339. $uid = self::getPars($message, 'uid');
  340. $group = intval(self::getPars($message, 'group', 0));
  341. if (empty($uid) || empty($group) || !isset(self::$global->groupmap[$group])) {
  342. self::MySendMsg($client_id, json_encode(["message_type" => 'checkfalse', 'data' => "客服登陆参数错误"], 256));
  343. Gateway::closeCurrentClient();
  344. return;
  345. }
  346. $loginstate = self::$logic->userIsLogin($client_id, $uid, $group);
  347. if ($loginstate == 1) {
  348. self::MySendMsg($client_id, (json_encode(['message_type' => 'reLoginErr', 'msg' => '正在登陆中,请稍后...'], 256)));
  349. Gateway::closeClient($client_id);
  350. return;
  351. }
  352. //客服登陆验证 不符合的直接断掉
  353. $kfinfo = self::KfloginCheck($client_id, $message);
  354. if (empty($kfinfo)) {
  355. self::MySendMsg($client_id, json_encode(["message_type" => 'checkfalse', 'data' => "验证失败"], 256));
  356. Gateway::closeCurrentClient();
  357. return true;
  358. } elseif ($kfinfo['status'] != 1) {
  359. self::MySendMsg($client_id, json_encode(["message_type" => 'checkfalse', 'data' => "禁用中..."], 256));
  360. Gateway::closeCurrentClient();
  361. return true;
  362. }
  363. if ($loginstate == 2) {
  364. $oldcontids = Gateway::getClientIdByUid($uid);
  365. Gateway::sendToClient($oldcontids['0'], (json_encode(['message_type' => 'reLoginErr', 'msg' => '你的账号在其它登陆,本次下线'], 256)));
  366. Gateway::closeClient($oldcontids['0']);
  367. sleep(1);
  368. }
  369. self::$redis->hset('loginTmp:' . $uid, 'uid', time());
  370. self::$redis->expire('loginTmp:' . $uid, 5);
  371. self::$redis->hset(self::KFRELONINFLAG, $uid, time());
  372. $newinfo =
  373. [
  374. 'id' => 'KF' . $kfinfo['id'],
  375. 'name' => $kfinfo['user_name'],
  376. 'job_name' => $kfinfo['user_job_number'],
  377. 'avatar' => $kfinfo['user_avatar'],
  378. 'group' => $group,
  379. 'client_id' => $client_id,
  380. 'task' => 0,
  381. 'intime' => time(),
  382. 'signature' => $kfinfo['signature'],
  383. 'status' => 2, // 1为在线(接收分配、接收消息)2为隐身(不接收分配、只接收消息)3、休息
  384. 'user_info' => [], //在会话的用户cid key为clientid ,值为工单号 ///////弃用 改为hash数据了
  385. ];
  386. self::$redis->hset(self::KFINFOKEY, $uid, json_encode($newinfo, 256));
  387. $_SESSION['info'] = $newinfo;
  388. // 绑定 client_id 和 uid
  389. Gateway::bindUid($client_id, $message['uid']);
  390. $_SESSION['group'] = $message['group'];
  391. $_SESSION['iskefu'] = 1;
  392. $_SESSION['uid'] = $message['uid'];
  393. $_SESSION['name'] = $message['name'];
  394. $_SESSION['client_id'] = $client_id;
  395. Gateway::joinGroup($client_id, 'group_' . $message['group']);
  396. $chat_message = [
  397. 'message_type' => 'loginSuccess',
  398. 'userlabels' => self::$global->accountslabel,
  399. ];
  400. self::MySendMsg($client_id, json_encode($chat_message, 256));
  401. unset($chat_message);
  402. self::KFStatusCg($client_id, ['data' => ['uid' => $uid, 'status' => 1]]);
  403. self::SendKFHistoryRecord($client_id, $uid);
  404. return;
  405. }
  406. //客服掉线后 历史聊天记录
  407. private static function SendKFHistoryRecord($client_id, $userId)
  408. {
  409. $flag = self::$redis->hget(self::KFRELONINFLAG, $userId);
  410. if (!empty($flag)) {
  411. self::kfonlilneRework($client_id, $userId);
  412. self::$redis->hdel(self::KFRELONINFLAG, $userId);
  413. }
  414. return;
  415. }
  416. //客服上线重新处理下旧的没完成的工单信息
  417. private static function kfonlilneRework($clientid, $kfuid)
  418. {
  419. $oldService = self::$redis->hgetall(self::getKfServiceKey($kfuid));
  420. if ($oldService) {
  421. foreach ($oldService as $tmpcie => $tmpsid) {
  422. $tmpserver = json_decode(self::$redis->hget(self::SERVICELOG, $tmpsid), true);
  423. if (!$tmpserver) {
  424. continue;
  425. }
  426. $tmpserver['kf_client_id'] = $clientid;
  427. self::$redis->hset(self::SERVICELOG, $tmpsid, json_encode($tmpserver, 256));
  428. self::userOnlineTask($tmpserver['group_id'], $tmpserver['user_id'], $tmpserver, 0);
  429. }
  430. }
  431. return;
  432. }
  433. /**
  434. * 管理员登陆验证
  435. * @param $client_id 服务ID
  436. * @param $message 数据
  437. */
  438. public static function adminInit($client_id, $token)
  439. {
  440. // 查询token是否存在.
  441. $systemConfigData = self::$db->query("SELECT `id` FROM `ws_admins` where `token`= '$token'");
  442. if ($systemConfigData) {
  443. self::$redis->sadd('adminList', $client_id);
  444. self::systemMonitoring([$client_id]);
  445. } else {
  446. $chat_message = [
  447. 'message_type' => 'tips',
  448. 'data' => '管理员不存在'
  449. ];
  450. Gateway::sendToClient($client_id, json_encode($chat_message, 256));
  451. Gateway::closeClient($client_id);
  452. }
  453. }
  454. //客服登陆验证
  455. public static function KfloginCheck($client, $messageArray)
  456. {
  457. $uid = isset($messageArray['uid']) ? $messageArray['uid'] : '';
  458. $token = isset($messageArray['token']) ? $messageArray['token'] : '';
  459. if (empty($uid) || empty($token)) {
  460. return false;
  461. }
  462. $expire_time_vali = time() - 60 * 60 * 24;
  463. $kfid = intval(substr($uid, 2));
  464. $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();
  465. if ($ret) {
  466. self::$db->update('ws_users')->cols(array('online_status' => 1, 'online_connectid' => $client))->where('id=' . $kfid)->query();
  467. return $ret;
  468. }
  469. return false;
  470. }
  471. //用户发送邦定用户事件
  472. public static function userInitEnt($client_id, $message)
  473. {
  474. $uid = intval($message['uid']);
  475. $group = intval($message['group']);
  476. $userTmpInfo = self::getUserInfoCache($uid);
  477. if (empty($userTmpInfo)) {
  478. self::MySendMsg($client_id, (json_encode(['message_type' => 'reLoginErr', 'msg' => '不存在的用户....'], 256)));
  479. Gateway::closeCurrentClient();
  480. return true;
  481. }
  482. $last = self::UserHasOldTalk($uid);
  483. if (!isset(self::$global->groupmap[$group]) && !$last) {
  484. self::MySendMsg($client_id, (json_encode(['message_type' => 'reLoginErr', 'msg' => '不存在客服组....'], 256)));
  485. return true;
  486. //Gateway::closeCurrentClient();
  487. }
  488. $loginstate = self::$logic->userIsLogin($client_id, $uid, $group);
  489. if ($loginstate == 1) {
  490. self::MySendMsg($client_id, (json_encode(['message_type' => 'reLoginErr', 'msg' => '正在登陆中,请稍后...'], 256)));
  491. Gateway::closeCurrentClient();
  492. return;
  493. }
  494. $hisdata = self::$redis->hget(self::USERINFOKEY, $uid);
  495. if ($hisdata) {
  496. $hisdata = json_decode($hisdata, true);
  497. $oldclientid = $hisdata['client_id'];
  498. self::MySendMsg($oldclientid, json_encode(['type' => 'reLoginErr', 'msg' => '相同账号登陆1,本次退出'], 256));
  499. self::MySendMsg($client_id, json_encode(['type' => 'reLoginErr', 'msg' => '相同账号登陆2,本次退出'], 256));
  500. Gateway::closeClient($oldclientid);
  501. Gateway::closeCurrentClient();
  502. return;
  503. }
  504. $onlinekf = self::getOnlineKfData($group, 1);
  505. if (empty($onlinekf) && empty($last)) {
  506. Gateway::sendToClient($client_id, json_encode(['message_type' => 'notice', 'content' => '暂时没有客服上班,请稍后再咨询。'], 256));
  507. //Gateway::closeClient($client_id);
  508. return;
  509. }
  510. $groupMax = self::$global->systemconfig['maxWait'];
  511. $noworders = self::getUselistData($group);
  512. if ($noworders && count($noworders) >= intval($groupMax['systemconfig_data'])) {
  513. Gateway::sendToClient($client_id, json_encode(['message_type' => 'notice', 'content' => '组排队人数超过上限,请稍后在连线。'], 256));
  514. return;
  515. }
  516. if (!$last && self::HasInqueue($group)) {
  517. Gateway::sendToClient($client_id, json_encode(['message_type' => 'inqueue', 'content' => '当前咨询人数繁多,正在排队中,请耐心等待。'], 256));
  518. }
  519. self::$redis->hset('loginTmp:' . $uid, 'uid', time());
  520. self::$redis->expire('loginTmp:' . $uid, 5);
  521. $data = [
  522. 'id' => $uid,
  523. 'name' => $message['name'],
  524. 'avatar' => $message['avatar'],
  525. 'website' => $_SESSION['origin'],//$message['website'],
  526. 'browse' => Gateway::browse_info(),
  527. 'system' => Gateway::get_os(),//$message['system'],
  528. 'ip' => isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '',//message['ip'],
  529. 'group' => $message['group'],
  530. 'intime' => time(),
  531. 'kfuid' => '',
  532. 'serverid' => 0,
  533. 'client_id' => $client_id
  534. ];
  535. if ($last) {
  536. $data['group'] = $last['group_id'];
  537. $data['intime'] = $last['intime'];
  538. $data['kfuid'] = $last['kf_id'];
  539. $data['serverid'] = $last['servicelog_id'];
  540. }
  541. if (!$last) {
  542. self::$redis->hset(self::USERLIST, $uid, json_encode($data, 256));
  543. }
  544. self::$redis->hset(self::USERINFOKEY, $uid, json_encode($data, 256));
  545. // 写入接入值
  546. $key = date('Ymd') . 'total_in';
  547. self::$global->increment($key);
  548. // 绑定 client_id 和 uid
  549. Gateway::bindUid($client_id, $uid);
  550. $_SESSION['iskefu'] = 0;
  551. $_SESSION['uid'] = $message['uid'];
  552. // 尝试分配新会员进入服务
  553. self::userOnlineTask($group, $uid, $last, $client_id);
  554. }
  555. /**
  556. * 当用户断开连接时触发
  557. * @param int $client_id 连接id
  558. *
  559. * tips: 当服务端主动退出的时候,会出现 exit status 9.原因是:服务端主动断开之后,连接的客户端会走这个方法,而短时间内进程
  560. * 需要处理这多的逻辑,又有cas操作,导致进程退出会超时,然后会被内核杀死,从而报出错误 9.实际对真正的业务没有任何的影响。
  561. */
  562. public static function onClose($client_id)
  563. {
  564. self::$redis->hdel(self::WEBSOCKALLUSER, $client_id);
  565. $isKefuoff = isset($_SESSION['iskefu']) ? $_SESSION['iskefu'] : 0;
  566. $uid = isset($_SESSION['uid']) ? $_SESSION['uid'] : false;
  567. echo "下线:uid: $uid - cid: $client_id - iskf: $isKefuoff \n";
  568. $isAdmin = self::$redis->sismember('adminList', $client_id);
  569. if ($isAdmin) {
  570. self::$redis->srem('adminList', $client_id);
  571. }
  572. if (empty($uid)) {
  573. return true;
  574. }
  575. if ($isKefuoff) {
  576. self::serviceOfflineV2($client_id, $uid);
  577. } else {
  578. self::guestOffline($client_id, $uid);
  579. }
  580. return true;
  581. }
  582. //客服掉线处理 第二版 系统调用,不能手动调用
  583. public static function serviceOfflineV2($client_id, $uid)
  584. {
  585. $group = $_SESSION['group'];
  586. $uinfo = self::$redis->hget(self::KFINFOKEY, $uid);
  587. self::$redis->hdel(self::KFINFOKEY, $uid);
  588. $uinfo = json_decode($uinfo, true);
  589. if (empty($uinfo) || empty($group)) {
  590. echo "客服发生异常退出\n";
  591. return;
  592. }
  593. $user_info = self::$redis->hgetall(self::getKfServiceKey($uid));
  594. if (!empty($user_info)) {
  595. foreach ($user_info as $val => $serverid) {
  596. self::MySendMsg($val, json_encode(['message_type' => 'serviceoffline', 'msg' => '客服人员下线!'], 256));
  597. }
  598. }
  599. echo "客服退出: " . $uid . "\n";
  600. self::writeLogKfStatus($uid, 0);
  601. return;
  602. }
  603. //客服下线了 系统调用,不能手动调用
  604. public static function serviceOffline($client_id, $uid)
  605. {
  606. $group = $_SESSION['group'];
  607. $uinfo = self::$redis->hget(self::KFINFOKEY, $uid);
  608. self::$redis->hdel(self::KFINFOKEY, $uid);
  609. $uinfo = json_decode($uinfo, true);
  610. if (empty($uinfo)) {
  611. echo "客服发生异常退出\n";
  612. return;
  613. }
  614. //$user_info = $uinfo['user_info'];
  615. $user_info = self::$redis->hgetall(self::getKfServiceKey($uid));
  616. $kfid = self::getkfid($uid);
  617. $now = time();
  618. $starttime = $now - 86400 * 7;
  619. self::$redis->hset('loginTmp:' . $uid, 'uid', time());
  620. self::$redis->expire('loginTmp:' . $uid, 5);
  621. if (!empty($user_info)) {
  622. foreach ($user_info as $val => $serverid) {
  623. self::insertServerLog($serverid, 4);
  624. self::$redis->hdel(self::SERVICELOG, intval($serverid));
  625. self::MySendMsg($val, json_encode(['message_type' => 'serviceoffline', 'msg' => '客服人员下线!'], 256));
  626. Gateway::closeClient($val);
  627. }
  628. }
  629. $sql = "update `ws_service_log` set `status` = '2',end_time=$now,`servicelog_close_type` = 4 where start_time>=$starttime and kf_id=$kfid and group_id=$group and `status`!=2 ";
  630. echo "客服退出: " . $uid . "\n";
  631. self::$db->query($sql);
  632. self::$db->update('ws_users')->cols(array('online_status' => 0, 'online_connectid' => ''))->where('id=' . $kfid)->query();
  633. self::$redis->del(self::getKfServiceKey($uid));
  634. self::writeLogKfStatus($uid, 0);
  635. return true;
  636. }
  637. //用户下线了 系统调用,不能手动调用
  638. public static function guestOffline($client_id, $uid)
  639. {
  640. self::$redis->hset('loginTmp:' . $uid, 'uid', time());
  641. self::$redis->expire('loginTmp:' . $uid, 3);
  642. $uid = intval($uid);
  643. $krclient_id = 0;
  644. $data = self::$redis->hget(self::USERINFOKEY, $uid);
  645. if (empty($data)) {
  646. return;
  647. }
  648. $info = json_decode($data, true);
  649. self::$redis->hdel(self::USERLIST, $uid);
  650. self::$redis->hdel(self::USERINFOKEY, $uid);
  651. if (!empty($info['kfuid'])) {
  652. $kfinfo = self::$redis->hget(self::KFINFOKEY, $info['kfuid']);
  653. if (!empty($kfinfo)) {
  654. $kfinfoArr = json_decode($kfinfo, true);
  655. $krclient_id = $kfinfoArr['client_id'];
  656. /*$kfinfoArr['user_info'] = self::ArrayDataopt($kfinfoArr['user_info'], $client_id, 0);
  657. $kfinfoArr['task'] = count($kfinfoArr['user_info']);
  658. self::$redis->hset(self::KFINFOKEY, $info['kfuid'], json_encode($kfinfoArr, 256));*/
  659. }
  660. }
  661. $chat_message = [
  662. 'message_type' => 'userClose',
  663. 'data' => [
  664. 'content' => '用户连接已断开',
  665. 'id' => $uid,
  666. 'time' => date('H:i'),
  667. ]
  668. ];
  669. $now = time();
  670. $serverid = intval($info['serverid']);
  671. if ($serverid) {
  672. $sql = "update `ws_service_log` set `status` = '3' where servicelog_id=$serverid and `status` !=2 ";
  673. self::$db->query($sql);
  674. }
  675. if ($krclient_id) {
  676. Gateway::sendToClient($krclient_id, json_encode($chat_message, 256));
  677. }
  678. return;
  679. }
  680. /**
  681. * 客服结束会话
  682. *
  683. * tips: 未有$client_id的关闭
  684. */
  685. public static function closeUser($servicelog_id, $userId, $kf_id, $groupId)
  686. {
  687. }
  688. /**
  689. * 工单结束
  690. * @param int $client_id 连接id
  691. *
  692. * tips: 当服务端主动退出的时候,会出现 exit status 9.原因是:服务端主动断开之后,连接的客户端会走这个方法,而短时间内进程
  693. * 需要处理这多的逻辑,又有cas操作,导致进程退出会超时,然后会被内核杀死,从而报出错误 9.实际对真正的业务没有任何的影响。
  694. */
  695. public static function serverClose($servicelogId, $closeBy = 0)
  696. {
  697. // 获取当前工单数据.
  698. $data = json_decode(self::$redis->HGET('SERVICELOG', $servicelogId), true);
  699. if (empty($data)) {
  700. return;
  701. }
  702. // 获取当前客服.
  703. $kfInfo = json_decode(self::$redis->HGET('KFINFO', 'KF' . $data['kf_id']), true);
  704. // 删除当前工单.
  705. self::$redis->hdel('SERVICELOG', $servicelogId);
  706. // 当前服务客服删除当前人员.
  707. //$kfUserList = self::ArrayDataopt($kfInfo['user_info'], $data['client_id'], 0);
  708. self::$redis->hdel(self::getKfServiceKey(self::getkfuid($data['kf_id'])), $data['client_id']);
  709. // 删除当前人员信息.
  710. self::$redis->hdel('USERINFO', $data['user_id']);
  711. // 当前客服所接待人员.
  712. //$kfInfo['user_info'] = $kfUserList;
  713. //$kfInfo['task'] = count($kfUserList);
  714. // 存入客服信息.
  715. //self::$redis->HSET('KFINFO', 'KF' . $data['kf_id'], json_encode($kfInfo, 256));
  716. // 发送消息给用户.
  717. $chat_message = [
  718. 'message_type' => 'closeBysever',
  719. 'data' => [
  720. 'content' => '会话关闭',
  721. 'time' => date('H:i'),
  722. ]
  723. ];
  724. Gateway::sendToClient($data['client_id'], json_encode($chat_message, 256));
  725. // 关闭用户连接.
  726. //Gateway::closeClient($data['client_id']);
  727. // 发送消息给客服.
  728. $del_message = [
  729. 'message_type' => 'delUser',
  730. 'data' => [
  731. 'id' => $data['user_id']
  732. ]
  733. ];
  734. Gateway::sendToClient($data['kf_client_id'], json_encode($del_message, 256));
  735. // 查询工单会话总数.
  736. $chatCount = self::$db->select('count(*) as count')->from('ws_chat_log')->where("servicelog_id=$servicelogId")->row();
  737. // 将数据存入数据库.
  738. $updateServiceLogData = [
  739. 'status' => 2,
  740. 'evaluate_id' => isset($data['evaluate_id']) ? $data['evaluate_id'] : 0,
  741. 'evaluate_content' => isset($data['evaluate_content']) ? $data['evaluate_content'] : '',
  742. 'servicelog_close_type' => $closeBy,
  743. 'end_time' => time(),
  744. ];
  745. $updataAlarmData = [
  746. 'alarm_userSensitive' => $data['alarm_userSensitive'],
  747. 'alarm_serverSensitive' => $data['alarm_serverSensitive'],
  748. 'alarm_corresponding' => $data['alarm_corresponding'],
  749. 'alarm_cvtOvertime' => time() - $data['start_time'],
  750. 'alarm_respond' => $data['alarm_respond'],
  751. 'alarm_lineTime' => $data['start_time'] - $data['intime'],
  752. 'alarm_count' => $chatCount['count'],
  753. ];
  754. self::$db->update('ws_service_log')->cols($updateServiceLogData)->where("servicelog_id=$servicelogId")->query();
  755. self::$db->update('ws_alarm')->cols($updataAlarmData)->where("servicelog_id=$servicelogId")->query();
  756. }
  757. /**
  758. * 修改工单数据库数据
  759. * @param int $client_id 连接id
  760. *
  761. * tips: 当服务端主动退出的时候,会出现 exit status 9.原因是:服务端主动断开之后,连接的客户端会走这个方法,而短时间内进程
  762. * 需要处理这多的逻辑,又有cas操作,导致进程退出会超时,然后会被内核杀死,从而报出错误 9.实际对真正的业务没有任何的影响。
  763. */
  764. public static function insertServerLog($servicelogId, $closeBy = 0)
  765. {
  766. // 获取当前工单数据.
  767. $data = json_decode(self::$redis->HGET('SERVICELOG', $servicelogId), true);
  768. if (empty($data)) {
  769. return;
  770. }
  771. // 查询工单会话总数.
  772. $chatCount = self::$db->select('count(*) as count')->from('ws_chat_log')->where("servicelog_id=$servicelogId")->row();
  773. // 将数据存入数据库.
  774. $updateServiceLogData = [
  775. 'status' => 2,
  776. 'evaluate_id' => isset($data['evaluate_id']) ? $data['evaluate_id'] : 0,
  777. 'evaluate_content' => isset($data['evaluate_content']) ? $data['evaluate_content'] : '',
  778. 'servicelog_close_type' => $closeBy,
  779. 'end_time' => time(),
  780. ];
  781. $updataAlarmData = [
  782. 'alarm_userSensitive' => $data['alarm_userSensitive'],
  783. 'alarm_serverSensitive' => $data['alarm_serverSensitive'],
  784. 'alarm_corresponding' => $data['alarm_corresponding'],
  785. 'alarm_cvtOvertime' => time() - $data['start_time'],
  786. 'alarm_respond' => $data['alarm_respond'],
  787. 'alarm_lineTime' => $data['start_time'] - $data['intime'],
  788. 'alarm_count' => $chatCount['count'],
  789. ];
  790. self::$db->update('ws_service_log')->cols($updateServiceLogData)->where("servicelog_id=$servicelogId")->query();
  791. self::$db->update('ws_alarm')->cols($updataAlarmData)->where("servicelog_id=$servicelogId")->query();
  792. }
  793. /**
  794. * 有人退出
  795. * @param $group
  796. */
  797. private static function userOfflineTask($group)
  798. {
  799. }
  800. /**
  801. * 有人进入执行分配
  802. * @param $client_id
  803. * @param $group
  804. * @param $uid
  805. */
  806. private static function userOnlineTask($group = 0, $uid = 0, $last = [], $client_id = '')
  807. {
  808. if ($group && $uid) {
  809. // 指定用指定组 [可能存在断线重连的情况] 如果存在旧的会话,直接连线客服和用户
  810. //否则按先到后到以及客服最大服务数限制
  811. if ($last) {
  812. $userInfo = json_decode(self::$redis->hget(self::USERINFOKEY, $uid), true);
  813. self::BeginOldTalk(self::getkfuid($last['kf_id']), $uid, $last['group_id'], $last['servicelog_id']);
  814. if ($client_id == $userInfo['client_id']) {
  815. // 查询工单历史会话.
  816. $serviceid = $last['servicelog_id'];
  817. $chatLog = self::$db->query("SELECT * FROM `ws_chat_log` where `servicelog_id`= '$serviceid' order by `time_line`");
  818. $toOld_message = [
  819. 'message_type' => 'toOld',
  820. 'data' => [
  821. 'chatLog' => $chatLog ?? [],
  822. 'content' => '接入至未结束的会话',
  823. 'serviceid' => $serviceid,
  824. 'uid' => $uid
  825. ]
  826. ];
  827. Gateway::sendToCurrentClient(json_encode($toOld_message, 256));
  828. }
  829. return;
  830. }
  831. }
  832. $allusergkarr = self::getUserListData();
  833. if (empty($allusergkarr)) {
  834. return;
  835. }
  836. $allkfgkarr = self::getWorkKfData();
  837. ///做某个组的客户是否还有人服务检测,如果此组没有客服在线了,要把对应排队的人踢掉
  838. self::Kf_user_click($allkfgkarr, $allusergkarr);
  839. if (empty($allkfgkarr) && !$last) {
  840. return;
  841. }
  842. $maxset = intval((self::$global->systemconfig)['KFMaxServices']['systemconfig_data']);
  843. //系统定时调用时,无组,无用户
  844. foreach ($allusergkarr as $group => $gusersArr) {
  845. if (!isset($allkfgkarr[$group]) || count($allkfgkarr[$group]) <= 0) {
  846. //所属客服组无人在线
  847. continue;
  848. }
  849. $nowkfs = $allkfgkarr[$group];
  850. $count = count($nowkfs);
  851. $i = 0;
  852. foreach ($gusersArr as $user) {
  853. if ($nowkfs[$i]['task'] >= $maxset) {
  854. break;
  855. }
  856. $nowkfs[$i]['task']++;
  857. self::BeginTalk($nowkfs[$i]['id'], $user['id'], $group, 0, $user);
  858. self::$redis->hdel(self::USERLIST, $user['id']);
  859. $i++;
  860. if ($i >= $count) {
  861. $i = 0;
  862. }
  863. }
  864. }
  865. return;
  866. }
  867. //踢掉某个组没有客服的用户
  868. private static function Kf_user_click($kfArrays, $userLIsts)
  869. {
  870. foreach ($userLIsts as $group => $groupusers) {
  871. $haskf = isset($kfArrays[$group]) ? 1 : 0;
  872. if (!$haskf) {
  873. foreach ($groupusers as $user) {
  874. Gateway::sendToClient($user['client_id'], json_encode(['message_type' => 'notice', 'data' => ['msg' => "没有客服人员在线,请稍后再试。"]], 256));
  875. Gateway::closeClient($user['client_id']);
  876. }
  877. }
  878. }
  879. return true;
  880. }
  881. //开启一个会话
  882. private static function BeginTalk($kfuid, $uid, $group, $serviceid = 0, $userInfo = false, $isChangeKF = 0)
  883. {
  884. $serviceid = intval($serviceid);
  885. if (!$userInfo) {
  886. $userInfo = json_decode(self::$redis->hget(self::USERINFOKEY, $uid), true);
  887. }
  888. $kfinfo = json_decode(self::$redis->hget(self::KFINFOKEY, $kfuid), true);
  889. if (empty($userInfo) || empty($kfinfo)) {
  890. return false;
  891. }
  892. $server = [];
  893. $armarr = [];
  894. if ($serviceid) {
  895. $server = self::$db->select('*')->from('ws_service_log')->where("servicelog_id=$serviceid ")->row();
  896. if ($server) {
  897. $armarr = self::$db->select('*')->from('ws_alarm')->where("servicelog_id=$serviceid ")->row();
  898. }
  899. }
  900. if (empty($server)) {
  901. $array = [
  902. 'user_id' => intval($uid),
  903. 'client_id' => $userInfo['client_id'],
  904. 'user_name' => $userInfo['name'],
  905. 'user_avatar' => $userInfo['avatar'],
  906. 'user_ip' => $userInfo['ip'],
  907. 'kf_id' => self::getkfid($kfuid),
  908. 'start_time' => time(),
  909. 'group_id' => $group ? $group : $userInfo['group'],
  910. 'website' => $userInfo['website'],
  911. 'system' => $userInfo['system'],
  912. 'browse' => $userInfo['browse'],
  913. 'intime' => $userInfo['intime'],
  914. 'status' => 1,
  915. 'evaluate_id' => 0,
  916. 'servicelog_close_type' => 0
  917. ];
  918. $serviceid = self::$db->insert('ws_service_log')->cols($array)->query();
  919. $server = array_merge(['servicelog_id' => $serviceid], $array);
  920. $armid = self::$db->insert('ws_alarm')->cols(['servicelog_id' => $serviceid])->query();
  921. $armarr = self::$db->select('*')->from('ws_alarm')->where("alarm_id=$armid")->row();
  922. }
  923. $redisData = array_merge($server, $armarr, ['kf_client_id' => $kfinfo['client_id'], 'server_name' => $kfinfo['name']]);
  924. self::$redis->hset(self::SERVICELOG, $serviceid, json_encode($redisData, 256));
  925. self::setKfTasks($kfuid, $userInfo['client_id'], 1, $serviceid);
  926. $userInfo['serverid'] = $serviceid;
  927. $userInfo['kfuid'] = $kfuid;
  928. self::$redis->hset(self::USERINFOKEY, $uid, json_encode($userInfo, 256));
  929. // 通知会员发送信息绑定客服的id
  930. $noticeUser = [
  931. 'message_type' => 'connect',
  932. 'data' => [
  933. 'kf_id' => $kfuid,
  934. 'conversationId' => $serviceid,
  935. 'serverInfo' => $kfinfo,
  936. 'kf_name' => $kfinfo['job_name']
  937. ]
  938. ];
  939. self::MySendMsg($userInfo['client_id'], json_encode($noticeUser, 256));
  940. $sayHello = (self::$global->kfReplay)[0];
  941. if (!empty($sayHello) && 1 == $sayHello['status'] && !$isChangeKF) {
  942. $chat_message = [
  943. 'message_type' => 'chatMessage',
  944. 'data' => [
  945. 'id' => self::getkfuid($kfinfo['id']),
  946. 'name' => $kfinfo['name'],
  947. 'time' => date('H:i'),
  948. 'content' => $sayHello['word']
  949. ]
  950. ];
  951. self::MySendMsg($userInfo['client_id'], json_encode($chat_message, 256));
  952. unset($chat_message);
  953. }
  954. $userInfo['intime'] = date("H:i", $userInfo['intime']); ///后改为只显示小时分
  955. $ut_tmp = self::getUserInfoCache($uid);
  956. $userInfo = array_merge($userInfo,
  957. [
  958. 'account_name' => $ut_tmp['account_name'],
  959. 'nick_name' => $ut_tmp['nick_name'],
  960. 'account_email' => $ut_tmp['account_email'],
  961. 'account_phone' => $ut_tmp['account_phone'],
  962. 'address' => $ut_tmp['address'],
  963. 'remark' => $ut_tmp['remark'],
  964. 'label' => self::$global->accountslabel[$ut_tmp['label_id']]['name']
  965. ]
  966. );
  967. $noticeKf = [
  968. 'message_type' => 'connect',
  969. 'data' => [
  970. 'user_info' => $userInfo,
  971. 'conversationId' => $serviceid,
  972. 'history' => [],
  973. ]
  974. ];
  975. self::MySendMsg($kfinfo['client_id'], json_encode($noticeKf, 256));
  976. unset($noticeKf);
  977. $key = date('Ymd') . 'success_in';
  978. self::$global->increment($key);
  979. return;
  980. }
  981. //连接至上一个会话
  982. private static function BeginOldTalk($kfuid, $uid, $group, $serviceid = 0, $userInfo = false)
  983. {
  984. $serviceid = intval($serviceid);
  985. $userInfo = json_decode(self::$redis->hget(self::USERINFOKEY, $uid), true);
  986. $kfinfo = json_decode(self::$redis->hget(self::KFINFOKEY, $kfuid), true);
  987. if (empty($userInfo)) {
  988. return false;
  989. }
  990. // 获取旧工单信息.
  991. $data = json_decode(self::$redis->HGET('SERVICELOG', $serviceid), true);
  992. if (empty($data)) {
  993. return;
  994. }
  995. // 修改工单数据.
  996. $data['user_avatar'] = $userInfo['avatar'];
  997. $data['client_id'] = $userInfo['client_id'];
  998. $data['user_ip'] = $userInfo['ip'];
  999. $data['website'] = $userInfo['website'];
  1000. $data['system'] = $userInfo['system'];
  1001. $data['browse'] = $userInfo['browse'];
  1002. $data['status'] = 1;
  1003. $data['kf_client_id'] = $kfinfo['client_id'];
  1004. $data['kf_id'] = self::getkfid($kfuid);
  1005. self::$redis->hset(self::SERVICELOG, $serviceid, json_encode($data, 256));
  1006. // 更改用户连接客服信息
  1007. $userInfo['serverid'] = $serviceid;
  1008. $userInfo['kfuid'] = $kfuid;
  1009. self::$redis->hset(self::USERINFOKEY, $uid, json_encode($userInfo, 256));
  1010. // 更改客服连接信息.
  1011. $kfinfo = json_decode(self::$redis->hget(self::KFINFOKEY, $kfuid), true);
  1012. $kfUsers = self::$redis->hgetall(self::getKfServiceKey($kfuid));
  1013. foreach ($kfUsers as $key => $value) {
  1014. if ($value == $serviceid) {
  1015. // 删除之前的当前用户连接
  1016. self::$redis->hdel(self::getKfServiceKey($kfuid), $key);
  1017. break;
  1018. }
  1019. }
  1020. self::$redis->hset(self::getKfServiceKey($kfuid), $userInfo['client_id'], $serviceid);
  1021. // 通知会员发送信息绑定客服的id
  1022. $noticeUser = [
  1023. 'message_type' => 'connect',
  1024. 'data' => [
  1025. 'kf_id' => $kfuid,
  1026. 'conversationId' => $serviceid,
  1027. 'serverInfo' => $kfinfo,
  1028. 'kf_name' => $kfinfo['job_name']
  1029. ]
  1030. ];
  1031. self::MySendMsg($userInfo['client_id'], json_encode($noticeUser, 256));
  1032. // 发送给客服用户信息.
  1033. $userInfo['intime'] = date("H:i", $userInfo['intime']);
  1034. $noticeKf = [
  1035. 'message_type' => 'connect',
  1036. 'data' => [
  1037. 'user_info' => $userInfo,
  1038. 'conversationId' => $serviceid,
  1039. 'history' => self::getServerChagLog($serviceid)
  1040. ]
  1041. ];
  1042. self::MySendMsg($kfinfo['client_id'], json_encode($noticeKf, 256));
  1043. unset($noticeKf);
  1044. $key = date('Ymd') . 'success_in';
  1045. self::$global->increment($key);
  1046. return;
  1047. }
  1048. //获取工单最后20条聊天记录
  1049. private static function getServerChagLog($sericeId, $limit = 20)
  1050. {
  1051. $ret = self::$db->select('from_id,from_name,to_id,to_name,content,time_line')->from('ws_chat_log')->where('servicelog_id=:sid')->bindValues(array('sid' => $sericeId))->orderByASC(['id'])->limit($limit)->query();
  1052. if ($ret) {
  1053. rsort($ret);
  1054. }
  1055. return $ret;
  1056. }
  1057. //用户排队数据 按组
  1058. private static function getUserListData()
  1059. {
  1060. $alluser = self::$redis->hgetall(self::USERLIST);
  1061. if (empty($alluser)) {
  1062. return false;
  1063. }
  1064. $allusergkarr = [];
  1065. foreach ($alluser as $val) {
  1066. $now = json_decode($val, true);
  1067. if ($now) {
  1068. //用户分组后的数组
  1069. $allusergkarr[$now['group']][] = $now;
  1070. }
  1071. }
  1072. foreach ($allusergkarr as $group => $nowgroups) {
  1073. usort($allusergkarr[$group], function ($a, $b) {
  1074. if ($a['intime'] == $b['intime']) {
  1075. return 0;
  1076. }
  1077. return ($a['intime'] > $b['intime']) ? 1 : -1;
  1078. });
  1079. }
  1080. if (!$allusergkarr) {
  1081. return false;
  1082. }
  1083. unset($alluser);
  1084. return $allusergkarr;
  1085. }
  1086. //找到可以接工单的客服 按组
  1087. private static function getWorkKfData()
  1088. {
  1089. $allkfs = self::$redis->hgetall(self::KFINFOKEY);
  1090. if (empty($allkfs)) {
  1091. return false;
  1092. }
  1093. $allkfgkarr = [];
  1094. foreach ($allkfs as $val) {
  1095. $now = json_decode($val, true);
  1096. if ($now && $now['status'] == 1) {
  1097. //客分组后的数组
  1098. $tmp = self::getKfTasks($now['id']);
  1099. $now['task'] = $tmp ? count($tmp) : 0;
  1100. $allkfgkarr[$now['group']][] = $now;
  1101. }
  1102. }
  1103. if (!$allkfgkarr) {
  1104. return false;
  1105. }
  1106. //客服每组按任务数由小到大排序 任务相同时按时间先后顺序
  1107. foreach ($allkfgkarr as $group => $nowgroups) {
  1108. usort($allkfgkarr[$group], function ($a, $b) {
  1109. if ($a['task'] == $b['task']) {
  1110. if ($a['intime'] == $b['intime']) {
  1111. return 0;
  1112. }
  1113. return ($a['intime'] > $b['intime']) ? 1 : -1;
  1114. }
  1115. return ($a['task'] > $b['task']) ? 1 : -1;
  1116. });
  1117. }
  1118. unset($allkfs);
  1119. return $allkfgkarr;
  1120. }
  1121. //找到用户是否有一条未关闭的会话
  1122. private static function UserHasOldTalk($uid, $database = 0)
  1123. {
  1124. if ($database) {
  1125. $uid = intval($uid);
  1126. $start_time = time() - 86400;
  1127. $ret = self::$db->select('*')->from('ws_service_log')->where("start_time>=$start_time and user_id=$uid and status!=2 ")->orderByDESC(['servicelog_id'])->row();
  1128. return $ret;
  1129. }
  1130. $all = self::$redis->hgetall(self::SERVICELOG);
  1131. if (empty($all)) {
  1132. return false;
  1133. }
  1134. foreach ($all as $val) {
  1135. $tmp = json_decode($val, true);
  1136. if ($tmp && $tmp['user_id'] == $uid) {
  1137. return $tmp;
  1138. }
  1139. }
  1140. return false;
  1141. }
  1142. //今天排序累加
  1143. private static function todayqueuelength()
  1144. {
  1145. $dtype = 'user.queue.day.length';
  1146. $today = date("Y-m-d");
  1147. $sret = self::$db->select('*')->from('ws_countmidtable')->where('dtype=:dtype and mdate=:mdate')->bindValues(array('dtype' => $dtype, 'mdate' => $today))->row();
  1148. if ($sret) {
  1149. self::$db->update('ws_countmidtable')->cols(array('dcontent' => intval($sret['dcontent']) + 1))->where('id=' . $sret['id'])->query();
  1150. } else {
  1151. self::$db->insert('ws_countmidtable')->cols(array(
  1152. 'dtype' => $dtype,
  1153. 'mdate' => $today,
  1154. 'datatype' => 1,
  1155. 'dcontent' => 1))->query();
  1156. }
  1157. }
  1158. //客服工单转单
  1159. private static function servicetrutoother($type, $owen, $otherkfid, $serverid, $clientuid)
  1160. {
  1161. $owen = intval(substr($owen, 2));
  1162. $otherkfid = intval(substr($otherkfid, 2));
  1163. self::$db->insert('ws_serviceturn_log')->cols(array(
  1164. 'stype' => $type,
  1165. 'uid' => $owen,
  1166. 'tuid' => $otherkfid,
  1167. 'serverid' => $serverid,
  1168. 'guestuid' => $clientuid
  1169. ))->query();
  1170. }
  1171. /**
  1172. * 给客服分配会员【均分策略】
  1173. * @param $kfList
  1174. * @param $userList
  1175. * @param $group
  1176. * @param $total
  1177. */
  1178. private static function assignmentTask($kfList, $userList, $group, $total, $uid = 0)
  1179. {
  1180. }
  1181. /**
  1182. * 获取最大的服务人数
  1183. * @return int
  1184. */
  1185. private static function getMaxServiceNum()
  1186. {
  1187. $maxNumber = self::$db->query('select `max_service` from `ws_kf_config` where `id` = 1');
  1188. if (!empty($maxNumber)) {
  1189. $maxNumber = 5;
  1190. } else {
  1191. $maxNumber = $maxNumber['0']['max_service'];
  1192. }
  1193. return $maxNumber;
  1194. }
  1195. /**
  1196. * 将内存中的数据写入统计表
  1197. * @param int $flag
  1198. */
  1199. private static function writeLog($flag = 1)
  1200. {
  1201. // 上午 8点 到 22 点开始统计
  1202. if (date('H') < 8 || date('H') > 22) {
  1203. return;
  1204. }
  1205. $inQueue_1 = self::$redis->hgetall(self::USERLIST);
  1206. $inQueue = empty($inQueue_1) ? 0 : count($inQueue_1);
  1207. $allkf = self::$redis->hgetall(self::KFINFOKEY);
  1208. $nowTalking = $onlineKf = 0;
  1209. if (!empty($allkf)) {
  1210. foreach ($allkf as $kfuid => $val) {
  1211. $onlineKf++;
  1212. $nowTalking = 0;
  1213. }
  1214. }
  1215. $key = date('Ymd') . 'total_in';
  1216. $key2 = date('Ymd') . 'success_in';
  1217. $param = [
  1218. 'is_talking' => $nowTalking,
  1219. 'in_queue' => $inQueue,
  1220. 'online_kf' => $onlineKf,
  1221. 'success_in' => self::$global->$key2,
  1222. 'total_in' => self::$global->$key,
  1223. 'now_date' => date('Y-m-d')
  1224. ];
  1225. self::$db->update('ws_now_data')->cols($param)->where('id=1')->query();
  1226. if (2 == $flag) {
  1227. $param = [
  1228. 'is_talking' => $nowTalking,
  1229. 'in_queue' => $inQueue,
  1230. 'online_kf' => $onlineKf,
  1231. 'success_in' => self::$global->$key2,
  1232. 'total_in' => self::$global->$key,
  1233. 'add_date' => date('Y-m-d'),
  1234. 'add_hour' => date('H'),
  1235. 'add_minute' => date('i'),
  1236. ];
  1237. self::$db->insert('ws_service_data')->cols($param)->query();
  1238. }
  1239. unset($allkf, $nowTalking, $inQueue, $onlineKf, $key, $key2, $param);
  1240. }
  1241. /**
  1242. * 机器人问答
  1243. * @param $client_id 服务ID
  1244. * @param $message 数据
  1245. */
  1246. private static function toRobot($client_id, $message)
  1247. {
  1248. $groups_id = $message['data']['groups_id'];
  1249. $robot_name = $message['data']['robot_name'];
  1250. $robotgroups_id = $message['data']['robotgroups_id'];
  1251. // 查询问题.
  1252. $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 . "'");
  1253. $chat_message = [
  1254. 'message_type' => 'robotMessage',
  1255. //'message_type' => 'chatMessage',
  1256. 'data' => [
  1257. 'name' => '智能助手',
  1258. 'time' => date('H:i'),
  1259. 'content' => $getRobot ? $getRobot[0]['robot_content'] : 'error',
  1260. ]
  1261. ];
  1262. Gateway::sendToClient($client_id, json_encode($chat_message, 256));
  1263. }
  1264. /**
  1265. * 评价
  1266. * @param $client_id 服务ID
  1267. * @param $message 数据
  1268. */
  1269. private static function evaluate($message)
  1270. {
  1271. // 获取当前会话工单.
  1272. $data = json_decode(self::$redis->HGET('SERVICELOG', $message['conversationId']), true);
  1273. if (empty($data)) {
  1274. return;
  1275. }
  1276. $data['evaluate_id'] = $message['evaluate_id'];
  1277. $data['evaluate_content'] = $message['evaluate_content'];
  1278. self::$redis->HSET('SERVICELOG', $message['conversationId'], json_encode($data, 256));
  1279. $chat_message = [
  1280. 'message_type' => 'evaluate',
  1281. 'data' => [
  1282. 'status' => 1,
  1283. 'time' => date('H:i'),
  1284. ]
  1285. ];
  1286. Gateway::sendToClient($message['client_id'], json_encode($chat_message, 256));
  1287. }
  1288. //获取系统配置
  1289. private static function upsystemconfig()
  1290. {
  1291. $systemConfigData = self::$db->query("SELECT * FROM `ws_systemconfig`");
  1292. $arr = [];
  1293. if ($systemConfigData) {
  1294. foreach ($systemConfigData as $item) {
  1295. $arr[$item['systemconfig_enName']] = $item;
  1296. }
  1297. self::$global->systemconfig = $arr;
  1298. }
  1299. $group = self::$db->query("SELECT * FROM `ws_groups`");
  1300. $arr = [];
  1301. if ($group) {
  1302. foreach ($group as $val) {
  1303. $arr[$val['id']] = $val['name'];
  1304. }
  1305. self::$global->groupmap = $arr;
  1306. }
  1307. $arr = [];
  1308. $systemReplay = self::$db->query('select * from `ws_reply` where `type`=1 order by `sort`');
  1309. $kfReplay = self::$db->query('select * from `ws_reply` where `type`=2');
  1310. $systemWelcome = [];
  1311. foreach ($systemReplay as $v) {
  1312. $systemWelcome[] = htmlspecialchars_decode($v['word']);
  1313. }
  1314. self::$global->systemReplay = $systemWelcome;
  1315. self::$global->kfReplay = $kfReplay;
  1316. $arr = [];
  1317. $bq = self::$db->query("select * from ws_accountslabel");
  1318. if ($bq) {
  1319. foreach ($bq as $val) {
  1320. $arr[$val['id']] = $val;
  1321. }
  1322. self::$global->accountslabel = $arr;
  1323. }
  1324. }
  1325. /**
  1326. * 超时
  1327. * @param $client_id 服务ID
  1328. * @param $message 数据
  1329. */
  1330. private static function overTime()
  1331. {
  1332. // 查询对话时效设置.
  1333. $systemConfigData = self::$db->query("SELECT `systemconfig_data`,`systemconfig_enName`,`systemconfig_content` FROM `ws_systemconfig`");
  1334. foreach ($systemConfigData as $k => $v) {
  1335. if ($v['systemconfig_enName'] == 'overtime') {
  1336. $configOvertime = $v;
  1337. } elseif ($v['systemconfig_enName'] == 'unoperated') {
  1338. $configUnoperated = $v;
  1339. }
  1340. }
  1341. // 查询未断开的工单.
  1342. $serviceLog = self::$redis->hGetall('SERVICELOG');
  1343. $setOvertime = strtotime('-' . ($configOvertime['systemconfig_data'] - 60) . ' second');
  1344. $overtime = strtotime('-' . ($configOvertime['systemconfig_data']) . ' second');
  1345. $setUnoperated = strtotime('-' . ($configUnoperated['systemconfig_data'] - 60) . ' second');
  1346. $unoperated = strtotime('-' . ($configUnoperated['systemconfig_data']) . ' second');
  1347. foreach ($serviceLog as $k => $v) {
  1348. // 无效会话关闭.如果没有说一句话.
  1349. $data = json_decode($v, true);
  1350. if (!isset($data['userLastTime'])) {
  1351. if ($data['start_time'] <= $unoperated) {
  1352. self::serverClose($k, 1);
  1353. // 如果小于设定时间前一分钟则给出提示.
  1354. } elseif ($data['start_time'] <= $setUnoperated) {
  1355. $chat_message = [
  1356. 'message_type' => 'overtime',
  1357. 'data' => [
  1358. 'content' => $configUnoperated['systemconfig_content'],
  1359. ]
  1360. ];
  1361. Gateway::sendToClient($data['client_id'], json_encode($chat_message, 256));
  1362. }
  1363. // 双方静默超时.
  1364. } elseif (isset($data['serverLastTime'])) {
  1365. if ($data['userLastTime'] <= $overtime && $data['serverLastTime'] <= $overtime) {
  1366. self::serverClose($k, 2);
  1367. } elseif ($data['userLastTime'] <= $setOvertime && $data['serverLastTime'] <= $setOvertime) {
  1368. $chat_message = [
  1369. 'message_type' => 'overtime',
  1370. 'data' => [
  1371. 'content' => $configOvertime['systemconfig_content'],
  1372. ]
  1373. ];
  1374. Gateway::sendToClient($data['client_id'], json_encode($chat_message, 256));
  1375. }
  1376. } else {
  1377. if ($data['userLastTime'] <= $overtime) {
  1378. self::serverClose($k, 2);
  1379. } elseif ($data['userLastTime'] <= $setOvertime) {
  1380. $chat_message = [
  1381. 'message_type' => 'overtime',
  1382. 'data' => [
  1383. 'content' => $configOvertime['systemconfig_content'],
  1384. ]
  1385. ];
  1386. Gateway::sendToClient($data['client_id'], json_encode($chat_message, 256));
  1387. }
  1388. }
  1389. }
  1390. }
  1391. /**
  1392. * 系统监控
  1393. * @param $message 数据
  1394. */
  1395. private static function systemMonitoring($adminList)
  1396. {
  1397. // 查询正进行的工单.
  1398. $serviceLog = self::$redis->hGetall('SERVICELOG');
  1399. // 查询系统设置表.
  1400. $systemconfig = self::$db->query("SELECT `systemconfig_data`,`systemconfig_enName` FROM `ws_systemconfig` WHERE `systemconfig_enName`='verifyReturnTime' or `systemconfig_enName`='verifyAllTime'");
  1401. // 质检会话响应时长.
  1402. $returnTimeKey = array_search('verifyReturnTime', array_column($systemconfig, 'systemconfig_enName'));
  1403. $verifyReturnTime = $systemconfig[$returnTimeKey]['systemconfig_data'];
  1404. // 质检会话时长.
  1405. $allTimeKey = array_search('verifyAllTime', array_column($systemconfig, 'systemconfig_enName'));
  1406. $verifyAllTime = $systemconfig[$allTimeKey]['systemconfig_data'];
  1407. $evaluateCount = 0; // 差评总次数.
  1408. $overtimeNumber = 0; // 会话超时总次数.
  1409. $overtimeTime = []; // 每次会话超时时间.
  1410. $userSensitive = 0; // 用户敏感词报警总次数.
  1411. $serverSensitive = 0; // 客服敏感词报警总次数.
  1412. $csdNumber = 0; // 响应超时总次数.
  1413. $csdTime = []; // 每次响应超时时间.
  1414. foreach ($serviceLog as $k => $v) {
  1415. $data = json_decode($v, true);
  1416. // 工单报警次数.
  1417. $allCount = 0;
  1418. if ($data['evaluate_id'] == 3) {
  1419. $evaluateCount++; // 差评次数.
  1420. $allCount++; // 工单报警次数.
  1421. }
  1422. // 会话超时.
  1423. $duration = time() - $data['start_time'];
  1424. if ($duration > $verifyAllTime) {
  1425. $overtimeNumber++; // 会话超时总次数.
  1426. $allCount++; // 工单报警次数.
  1427. $overtimeTime[] = $duration; // 响应超时时间.
  1428. }
  1429. // 敏感词报警.
  1430. $userSensitive += $data['alarm_userSensitive'];
  1431. $allCount += $data['alarm_userSensitive'];
  1432. $serverSensitive += $data['alarm_serverSensitive'];
  1433. $allCount += $data['alarm_serverSensitive'];
  1434. // 响应超时.
  1435. if ($data['alarm_corresponding'] > $verifyReturnTime) {
  1436. $csdTime[] = $data['alarm_corresponding']; // 响应超时时间.
  1437. $csdNumber++; // 响应超时总次数.
  1438. $allCount++; // 工单报警次数.
  1439. }
  1440. $serviceLog[$k] = $data;
  1441. $serviceLog[$k]['allCount'] = $allCount; // 工单报警次数.
  1442. }
  1443. self::DebugOut([$serviceLog, $csdTime, $verifyReturnTime], 'systemMonitoring');
  1444. $chat_message = [
  1445. 'message_type' => 'monitor',
  1446. 'data' => [
  1447. 'cvtList' => $serviceLog,
  1448. 'userSensitive' => $userSensitive,
  1449. 'serverSensitive' => $serverSensitive,
  1450. 'csdNumber' => $csdNumber,
  1451. 'csdTime' => $csdTime,
  1452. 'overtimeNumber' => $overtimeNumber,
  1453. 'overtimeTime' => $overtimeTime,
  1454. 'evaluateCount' => $evaluateCount,
  1455. ]
  1456. ];
  1457. // 查询对话时效设置.
  1458. foreach ($adminList as $v) {
  1459. Gateway::sendToClient($v, json_encode($chat_message, 256));
  1460. }
  1461. }
  1462. //客户工单内部组转接
  1463. public static function changeOtherhKeFu($client_id, $smessage)
  1464. {
  1465. $message = $smessage['data'];
  1466. $groupid = isset($message['fromgroup']) ? intval($message['fromgroup']) : 0;
  1467. $groupidto = isset($message['togroup']) ? intval($message['togroup']) : 0;
  1468. $toukfid = isset($message['toukfuid']) ? $message['toukfuid'] : 0;
  1469. $fromkfuid = isset($message['fromkfuid']) ? $message['fromkfuid'] : 0;
  1470. $uid = isset($message['uid']) ? intval($message['uid']) : 0;
  1471. $word = isset($message['word']) ? $message['word'] : '';
  1472. if (empty($groupid) || empty($groupidto) || empty($toukfid) || empty($fromkfuid) || empty($uid) || ($toukfid == $fromkfuid)) {
  1473. self::DebugOut('changeOtherhKeFu exit1...');
  1474. return false;
  1475. }
  1476. if (!Gateway::isUidOnline($toukfid) || !Gateway::isUidOnline($uid)) {
  1477. self::DebugOut('changeOtherhKeFu exit2...');
  1478. return false;
  1479. }
  1480. $kf_info_from = json_decode(self::$redis->hget(self::KFINFOKEY, $fromkfuid), true);
  1481. $kf_info_to = json_decode(self::$redis->hget(self::KFINFOKEY, $toukfid), true);
  1482. $user_info = json_decode(self::$redis->hget(self::USERINFOKEY, $uid), true);
  1483. $serviceid = intval($user_info['serverid']);
  1484. if (empty($kf_info_from) || empty($kf_info_to) || empty($user_info) || empty($serviceid)) {
  1485. self::DebugOut('changeOtherhKeFu exit23...');
  1486. return false;
  1487. }
  1488. if ($kf_info_to['status'] != 1) {
  1489. self::DebugOut('changeOtherhKeFu exit4...');
  1490. return false;
  1491. }
  1492. /////////取消原有会话,开启新会话
  1493. $oldlog = self::$db->select('*')->from('ws_service_log')->where('servicelog_id=:servicelog_id ')->bindValues(['servicelog_id' => $serviceid])->orderByDESC(['servicelog_id'])->row();
  1494. if (!$oldlog) {
  1495. self::DebugOut('changeOtherhKeFu exit5...');
  1496. return false;
  1497. }
  1498. self::insertServerLog($serviceid, 5);
  1499. self::$redis->hdel(self::SERVICELOG, $serviceid);
  1500. unset($oldlog['servicelog_id']);
  1501. ///更新redis数据
  1502. self::updteKfTasksByservicd($fromkfuid, $serviceid, $user_info['client_id'], 0);
  1503. self:: BeginTalk($toukfid, $uid, $groupidto, 0, $user_info, 1);
  1504. self::servicetrutoother('OUT', $fromkfuid, $toukfid, $serviceid, $uid);
  1505. $newUserInfo = json_decode(self::$redis->hget(self::USERINFOKEY, $uid), true);
  1506. self::servicetrutoother('IN', $toukfid, $fromkfuid, $newUserInfo['serverid'], $uid);
  1507. //回转接人,转接成功
  1508. Gateway::sendToCurrentClient(json_encode(['message_type' => 'trunconnect', 'data' => ['status' => 1]], 256));
  1509. // 发送给用户转接消息
  1510. Gateway::sendToClient($user_info['client_id'], json_encode(['message_type' => 'changeKeFuSuccess', 'data' => ['content' => "会话转接成功"]], 256));
  1511. self::DebugOut('changekf 转换成功!');
  1512. return;
  1513. }
  1514. //客服在线状态写组
  1515. private static function writeLogKfStatus($kf, $status, $flag = 1)
  1516. {
  1517. if ($flag == 1) {
  1518. $status = intval($status);
  1519. if ($status == 0) {
  1520. self::$db->delete('ws_kfonline')->where("uid='$kf'")->query();
  1521. } else {
  1522. $now = date('Y-m-d H:i;s');
  1523. $ip = isset($_SESSION['remotip']) ? $_SESSION['remotip'] : '';
  1524. $sql = "insert into ws_kfonline(uid,status,uptime,ip) values('$kf',$status,'$now','$ip') ON DUPLICATE KEY UPDATE status=$status,uptime='$now' ";
  1525. self::$db->query($sql);
  1526. }
  1527. } else {
  1528. self::$db->query("delete from ws_kfonline ");
  1529. }
  1530. }
  1531. public static function resetServiceLog($kfid = 0)
  1532. {
  1533. $t = time() - 24 * 3600 * 7;
  1534. $now = time();
  1535. if ($kfid) {
  1536. if ((substr($kfid, 0, 2) == 'KF')) {
  1537. $kfid = intval(substr($kfid, 2));
  1538. }
  1539. $kfid = intval($kfid);
  1540. self::$db->query("update ws_service_log set status=2,end_time=$now where start_time>=$t and kf_id=$kfid and status!=2");
  1541. self::$redis->hdel(self::KFINFOKEY, 'KF' . $kfid);
  1542. } else {
  1543. //self::$redis->del(self::KFINFOKEY);
  1544. //self::$redis->del(self::USERLIST);
  1545. //self::$redis->del(self::USERINFOKEY);
  1546. //self::$redis->del('adminList');
  1547. //self::$redis->del(self::WEBSOCKALLUSER);
  1548. //self::$redis->del('SERVICELOG');
  1549. self::$redis->flushdb();
  1550. self::$db->query("update ws_service_log set status=2,end_time=$now where start_time>=$t and status!=2");
  1551. }
  1552. }
  1553. public static function onWorkerStop($businessWorker)
  1554. {
  1555. if ($businessWorker->id == 1) {
  1556. self::resetServiceLog();
  1557. }
  1558. }
  1559. //用户下线通知
  1560. private static function userCloseNotice($client_id, $cuid, $group)
  1561. {
  1562. }
  1563. //踢掉同一用户的旧用户
  1564. private static function tickOlduser($uid)
  1565. {
  1566. }
  1567. private static function DebugOut($msg, $title = '', $type = 'info')
  1568. {
  1569. $config = self::$global->systemconfig;
  1570. if (!isset($config['isdebug']) || empty($config['isdebug']['systemconfig_data'])) {
  1571. return;
  1572. }
  1573. if (!is_string($msg)) {
  1574. $msg = json_encode([$msg], 256);
  1575. }
  1576. $msg = date("Y-m-d H:i:s") . ' - ' . $type . ' - ' . $title . ' - ' . $msg . "\n";
  1577. echo $msg;
  1578. }
  1579. //定时器相关
  1580. private static function TimerThing($worker)
  1581. {
  1582. // 当天的累积接入值
  1583. $key = date('Ymd') . 'total_in';
  1584. if (is_null(self::$global->$key)) {
  1585. self::$global->$key = 0;
  1586. $oldKey = date('Ymd', strtotime('-1 day')); // 删除前一天的统计值
  1587. unset(self::$global->$oldKey);
  1588. unset($oldKey, $key);
  1589. }
  1590. // 成功接入值
  1591. $key = date('Ymd') . 'success_in';
  1592. if (is_null(self::$global->$key)) {
  1593. self::$global->$key = 0;
  1594. $oldKey = date('Ymd', strtotime('-1 day')); // 删除前一天的统计值
  1595. unset(self::$global->$oldKey);
  1596. unset($oldKey, $key);
  1597. }
  1598. // 每1分钟做一次redis ping检测避免redis掉线
  1599. Timer::add(60, function () {
  1600. if (!self::$logic->RedisPing()) {
  1601. self::$redis = self::$logic->getRedis(0);
  1602. }
  1603. });
  1604. if (strtolower(substr(PHP_OS, 0, 3)) == 'win') {
  1605. // 定时统计数据
  1606. if (0 == $worker->id) {
  1607. self::writeLogKfStatus(0, 0, 0);
  1608. //每5秒更新进行一次人员分配
  1609. Timer::add(5, function () {
  1610. self::userOnlineTask();
  1611. });
  1612. //每1分钟报告一次本组排列人员(如果有人排队)
  1613. Timer::add(60, function () {
  1614. self::lineup();
  1615. });
  1616. // 1分钟统计一次实时数据
  1617. Timer::add(60 * 1, function () {
  1618. self::writeLog(1);
  1619. });
  1620. // 40分钟写一次当前日期点数的log数据
  1621. Timer::add(60 * 40, function () {
  1622. self::writeLog(2);
  1623. });
  1624. //初始化.....
  1625. self::upsystemconfig();
  1626. //每3分钟更新一次系统配置文件
  1627. Timer::add(60 * 3, function () {
  1628. self::upsystemconfig();
  1629. });
  1630. // 删除前一天的统计值
  1631. Timer::add(60 * 60 * 12, function () {
  1632. $oldKey = date('Ymd', strtotime('-1 day'));
  1633. unset(self::$global->$oldKey);
  1634. });
  1635. // 管理员实时监控.
  1636. Timer::add(20, function () {
  1637. // 获取在线管理员
  1638. $adminList = self::$redis->smembers('adminList');
  1639. if ($adminList) {
  1640. self::systemMonitoring($adminList);
  1641. }
  1642. });
  1643. // 检查对话时效给出.
  1644. Timer::add(40, function () {
  1645. self::overTime();
  1646. });
  1647. self::resetServiceLog();
  1648. }
  1649. } else {
  1650. ///linux 下支持多进程....
  1651. if (0 == $worker->id) {
  1652. self::writeLogKfStatus(0, 0, 0);
  1653. //每5秒更新进行一次人员分配
  1654. Timer::add(5, function () {
  1655. self::userOnlineTask();
  1656. });
  1657. //每1分钟报告一次本组排列人员(如果有人排队)
  1658. Timer::add(60, function () {
  1659. self::lineup();
  1660. });
  1661. self::resetServiceLog();
  1662. } elseif (1 == $worker->id) {
  1663. // 1分钟统计一次实时数据
  1664. Timer::add(60 * 1, function () {
  1665. self::writeLog(1);
  1666. });
  1667. // 40分钟写一次当前日期点数的log数据
  1668. Timer::add(60 * 40, function () {
  1669. self::writeLog(2);
  1670. });
  1671. } elseif (2 == $worker->id) {
  1672. //初始化.....
  1673. self::upsystemconfig();
  1674. //每3分钟更新一次系统配置文件
  1675. Timer::add(60 * 3, function () {
  1676. self::upsystemconfig();
  1677. });
  1678. // 删除前一天的统计值
  1679. Timer::add(60 * 60 * 12, function () {
  1680. $oldKey = date('Ymd', strtotime('-1 day'));
  1681. unset(self::$global->$oldKey);
  1682. });
  1683. } elseif (3 == $worker->id) {
  1684. // 管理员实时监控.
  1685. Timer::add(20, function () {
  1686. // 获取在线管理员
  1687. $adminList = self::$redis->smembers('adminList');
  1688. if ($adminList) {
  1689. self::systemMonitoring($adminList);
  1690. }
  1691. });
  1692. // 检查对话时效给出.
  1693. Timer::add(40, function () {
  1694. self::overTime();
  1695. });
  1696. }
  1697. }
  1698. }
  1699. //调试使用
  1700. public static function mydebug($client_id, $message)
  1701. {
  1702. }
  1703. public static function MySendMsg($clientId, $msg)
  1704. {
  1705. Gateway::sendToClient($clientId, $msg);
  1706. }
  1707. //得到客服的UID字符值
  1708. public static function getkfuid($uid)
  1709. {
  1710. if (substr($uid, 0, 2) == 'KF') {
  1711. return $uid;
  1712. } else {
  1713. return 'KF' . intval($uid);
  1714. }
  1715. }
  1716. //得到客服的ID整数值
  1717. public static function getkfid($id)
  1718. {
  1719. if (strtolower(substr($id, 0, 2)) == 'kf') {
  1720. return intval(substr($id, 2));
  1721. }
  1722. return intval($id);
  1723. }
  1724. //从数组中获取参数
  1725. public static function getPars($array, $key, $default = '')
  1726. {
  1727. if (isset($array[$key])) {
  1728. return $array[$key];
  1729. }
  1730. return $default;
  1731. }
  1732. //获取在线客服信息
  1733. public static function getOnlineKfData($group = 0, $status = 0)
  1734. {
  1735. $all = self::$redis->hgetall(self::KFINFOKEY);
  1736. if (!$all) {
  1737. return false;
  1738. }
  1739. $return = [];
  1740. foreach ($all as $val) {
  1741. $now = json_decode($val, true);
  1742. if ($group) {
  1743. if ($now['group'] != $group) {
  1744. continue;
  1745. }
  1746. }
  1747. if ($status) {
  1748. if ($now['status'] != $status) {
  1749. continue;
  1750. }
  1751. }
  1752. $return[$now['id']] = $now;
  1753. }
  1754. return $return;
  1755. }
  1756. //找到在排队的用户按时间先后顺序
  1757. public static function getUselistData($group)
  1758. {
  1759. $all = self::$redis->hgetall(self::USERLIST);
  1760. if (!$all) {
  1761. return false;
  1762. }
  1763. $return = [];
  1764. foreach ($all as $val) {
  1765. $now = json_decode($val, true);
  1766. if ($group == $now['group']) {
  1767. $return[] = $now;
  1768. }
  1769. }
  1770. usort($return, function ($a, $b) {
  1771. if ($a['intime'] == $b['intime']) {
  1772. return 0;
  1773. }
  1774. return $a['intime'] > $b['intime'] ? 1 : -1;
  1775. });
  1776. return $return;
  1777. }
  1778. //对客服的用户user_info数组进行加减操作 $clientid用户连接号 opt=1添加 0删除 $serverid服务工单号
  1779. public static function ArrayDataopt($array, $clientid, $opt, $serverid = 0)
  1780. {
  1781. if (!is_array($array)) {
  1782. return [];
  1783. }
  1784. if ($opt == 0) {
  1785. if (isset($array[$clientid])) {
  1786. unset($array[$clientid]);
  1787. }
  1788. return $array;
  1789. } else {
  1790. $array[$clientid] = $serverid;
  1791. return $array;
  1792. }
  1793. }
  1794. //用户重要性标签
  1795. private static function getUserLabAll($client_id, $message)
  1796. {
  1797. $data = self::$global->accountslabel;
  1798. Gateway::sendToCurrentClient(json_encode(['message_type' => 'userlabeall', 'data' => $data], 256));
  1799. }
  1800. //调试使用
  1801. public static function debug($dataArray)
  1802. {
  1803. }
  1804. //客服的工单hash健名
  1805. public static function getKfServiceKey($kfuid)
  1806. {
  1807. return self::KFSERVICES . ':' . $kfuid;
  1808. }
  1809. //获取客服所有连接信息及工单信息
  1810. public static function getKfTasks($kfuid)
  1811. {
  1812. $all = self::$redis->hgetall(self::getKfServiceKey($kfuid));
  1813. if (empty($all)) {
  1814. return false;
  1815. }
  1816. return $all;
  1817. }
  1818. //设置或删除客服的连接 opt==0删除 1添加
  1819. public static function setKfTasks($kfuid, $clientid, $opt = 0, $serviceid = 0)
  1820. {
  1821. $k = self::getKfServiceKey($kfuid);
  1822. if ($opt == 0) {
  1823. self::$redis->hdel($k, $clientid);
  1824. return;
  1825. }
  1826. self::$redis->hset($k, $clientid, $serviceid);
  1827. }
  1828. //有旧单时,更新连接ID
  1829. public static function updteKfTasksByservicd($kfuid, $serciceid, $newclientid, $opt = 1)
  1830. {
  1831. $tkey = self::getKfServiceKey($kfuid);
  1832. $all = self::getKfTasks($kfuid);
  1833. $serciceid = intval($serciceid);
  1834. if ($opt == 1) {
  1835. if (empty($all)) {
  1836. self::$redis->hset($tkey, $newclientid, $serciceid);
  1837. return;
  1838. }
  1839. foreach ($all as $cid => $nowserverid) {
  1840. if (intval($nowserverid) == $serciceid) {
  1841. self::$redis->hdel(self::getKfServiceKey($kfuid), $cid);
  1842. }
  1843. }
  1844. self::$redis->hset($tkey, $newclientid, $serciceid);
  1845. return true;
  1846. } else {
  1847. if (empty($all)) {
  1848. return;
  1849. }
  1850. foreach ($all as $cid => $nowserverid) {
  1851. if (intval($nowserverid) == $serciceid) {
  1852. self::$redis->hdel(self::getKfServiceKey($kfuid), $cid);
  1853. }
  1854. }
  1855. return true;
  1856. }
  1857. }
  1858. //缓存获取用户信息
  1859. public static function getUserInfoCache($uid, $cacheTime = 180)
  1860. {
  1861. $uid = intval($uid);
  1862. $key = 'TmpUserInfo:' . $uid;
  1863. $cache = self::$redis->hget($key, $uid);
  1864. if ($cache && $cacheTime) {
  1865. return json_decode($cache, true);
  1866. }
  1867. $date = self::$db->select('*')->from('ws_accounts')->where("id= $uid ")->row();
  1868. self::$redis->hset($key, $uid, json_encode($date, 256));
  1869. self::$redis->EXPIRE($key, $cacheTime);
  1870. return $date;
  1871. }
  1872. //检查一个新人是否需要排队
  1873. public static function HasInqueue($group)
  1874. {
  1875. $group = intval($group);
  1876. $allserveric = self::$redis->hgetall(self::SERVICELOG);
  1877. if (empty($allserveric)) {
  1878. return false;
  1879. }
  1880. $count = 0;
  1881. foreach ($allserveric as $serv) {
  1882. $tmp = json_decode($serv, true);
  1883. if (isset($tmp['group_id']) && $tmp['group_id'] == $group) {
  1884. $count++;
  1885. }
  1886. }
  1887. $gkf = self::getOnlineKfData($group, 1);
  1888. $max = intval(self::$global->systemconfig['KFMaxServices']['systemconfig_data']);
  1889. if ($gkf) {
  1890. $cc = count($gkf) * $max;
  1891. if ($count >= $cc) {
  1892. return true;
  1893. }
  1894. }
  1895. return false;
  1896. }
  1897. }