Events.php 82 KB

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