Events.php 83 KB

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