Events.php 69 KB

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