Events.php 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230
  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. // 1分钟统计一次实时数据
  76. Timer::add(60 * 1, function () {
  77. self::writeLog(1);
  78. });
  79. // 40分钟写一次当前日期点数的log数据
  80. Timer::add(60 * 40, function () {
  81. self::writeLog(2);
  82. });
  83. }
  84. // 检查对话时效给出.
  85. Timer::add(3, function () {
  86. // 查询对话时效设置.
  87. $systemConfigData = self::$db->query("SELECT `systemconfig_data`,`systemconfig_enName`,`systemconfig_content` FROM `ws_systemconfig`");
  88. foreach ($systemConfigData as $k => $v) {
  89. if ($v['systemconfig_enName'] == 'overtime') {
  90. self::$global->overtime = $v;
  91. } elseif ($v['systemconfig_enName'] == 'unoperated') {
  92. self::$global->unoperated = $v;
  93. } elseif ($v['systemconfig_enName'] == 'noResponse') {
  94. self::$global->noResponse = $v;
  95. }
  96. }
  97. // 查询未断开的工单.
  98. $serviceLog = self::$db->query("SELECT `servicelog_id`,`client_id`,`start_time` FROM `ws_service_log` WHERE `status`='1' OR `status`='3'");
  99. $whereOr = '1=0';
  100. foreach ($serviceLog as $k => $v) {
  101. if ($k == 0) {
  102. $whereOr = "`servicelog_id`=".$v['servicelog_id'];
  103. } else {
  104. $whereOr .= " OR `servicelog_id`=".$v['servicelog_id'];
  105. }
  106. }
  107. // 查询最后一次会话.
  108. //$chatLog = self::$db->query("SELECT `servicelog_id`,MAX(`time_line`) FROM `ws_chat_log` WHERE ".$whereOr." group by `servicelog_id`");
  109. $chatLog = self::$db->query("
  110. select * from ws_chat_log as a where time_line=(
  111. select max(b.time_line) from ws_chat_log as b where a.servicelog_id = b.servicelog_id and (".$whereOr.") group by servicelog_id
  112. )
  113. ");
  114. $setOvertime = strtotime('-'.(self::$global->overtime['systemconfig_data']-60).' second');
  115. $overtime = strtotime('-'.(self::$global->overtime['systemconfig_data']).' second');
  116. $setUnoperated = strtotime('-'.(self::$global->unoperated['systemconfig_data']-60).' second');
  117. $unoperated = strtotime('-'.(self::$global->unoperated['systemconfig_data']).' second');
  118. $noResponse = strtotime('-'.(self::$global->noResponse['systemconfig_data']).' second');
  119. foreach ($serviceLog as $k => $v) {//注意该循环时间
  120. if (!strlen(array_search($v['servicelog_id'], array_column($chatLog, 'servicelog_id')))) {
  121. // 如果小于设定时间则关闭会话.
  122. if ($v['start_time'] <= $unoperated) {
  123. self::serverClose($v['client_id']);
  124. // 如果小于设定时间前一分钟则给出提示.
  125. } elseif ($v['start_time'] <= $setUnoperated) {
  126. $chat_message = [
  127. 'message_type' => 'overtime',
  128. 'data' => [
  129. 'content' => htmlspecialchars(self::$global->unoperated['systemconfig_content']),
  130. ]
  131. ];
  132. Gateway::sendToClient($v['client_id'], json_encode($chat_message));
  133. }
  134. }
  135. }
  136. // 循环检测会话时效.
  137. foreach ($chatLog as $k => $v) {
  138. $toWho = substr($v['to_id'],0,2);
  139. // 如果对话为客服的最后一次对话且时间小于设定时间则结束工单.
  140. if ($toWho != 'KF' && $v['time_line'] <= $overtime) {
  141. $found_key = array_search($v['servicelog_id'], array_column($serviceLog, 'servicelog_id'));
  142. self::serverClose($serviceLog[$found_key]['client_id']);
  143. // 如果对话为客服的最后一次对话且时间小于设定时间前一分钟则给出提示.
  144. } elseif ($toWho != 'KF' && $v['time_line'] <= $setOvertime) {
  145. $chat_message = [
  146. 'message_type' => 'overtime',
  147. 'data' => [
  148. 'content' => htmlspecialchars(self::$global->overtime['systemconfig_content']),
  149. ]
  150. ];
  151. $found_key = array_search($v['servicelog_id'], array_column($serviceLog, 'servicelog_id'));
  152. Gateway::sendToClient($serviceLog[$found_key]['client_id'], json_encode($chat_message));
  153. }
  154. }
  155. });
  156. }
  157. /**
  158. * 当客户端连接时触发
  159. * 如果业务不需此回调可以删除onConnect
  160. *
  161. * @param int $client_id 连接id
  162. */
  163. public static function onConnect($client_id)
  164. {
  165. // 检测是否开启自动应答
  166. $sayHello = self::$db->query('select `word`,`status` from `ws_reply` where `id` = 1');
  167. if (!empty($sayHello) && 1 == $sayHello['0']['status']) {
  168. $hello = [
  169. 'message_type' => 'helloMessage',
  170. 'data' => [
  171. 'name' => '智能助手',
  172. 'time' => date('H:i'),
  173. 'content' => htmlspecialchars($sayHello['0']['word'])
  174. ]
  175. ];
  176. Gateway::sendToClient($client_id, json_encode($hello, 256));
  177. unset($hello);
  178. }
  179. unset($sayHello);
  180. }
  181. /**
  182. * 当客户端发来消息时触发
  183. * @param int $client_id 连接id
  184. * @param mixed $message 具体消息
  185. */
  186. public static function onMessage($client_id, $message)
  187. {
  188. if ($message == '{"type":"ping"}') {
  189. Gateway::sendToCurrentClient('{"type":"pong"}');
  190. return;
  191. } else {
  192. /*echo "onMessage: " . $message . "\r\n";
  193. print_r([self::$global->kfList, self::$global->userList, self::$global->uidSimpleList, self::$global->userToKf]);*/
  194. }
  195. $message = json_decode($message, true);
  196. switch ($message['type']) {
  197. // 客服初始化
  198. case 'init':
  199. self::Kfinit($client_id, $message);
  200. break;
  201. // 顾客初始化
  202. case 'userInit';
  203. self::userInitEnt($client_id, $message);
  204. break;
  205. // 聊天
  206. case 'chatMessage':
  207. $client = Gateway::getClientIdByUid($message['data']['to_id']);
  208. if (!empty($client)) {
  209. $chat_message = [
  210. 'message_type' => 'chatMessage',
  211. 'data' => [
  212. 'name' => $message['data']['from_name'],
  213. 'avatar' => $message['data']['from_avatar'],
  214. 'id' => $message['data']['from_id'],
  215. 'time' => date('H:i'),
  216. 'content' => htmlspecialchars($message['data']['content']),
  217. ]
  218. ];
  219. Gateway::sendToClient($client['0'], json_encode($chat_message));
  220. unset($chat_message);
  221. // 聊天信息入库
  222. $serviceLog = [
  223. 'from_id' => $message['data']['from_id'],
  224. 'from_name' => $message['data']['from_name'],
  225. 'from_avatar' => $message['data']['from_avatar'],
  226. 'to_id' => $message['data']['to_id'],
  227. 'to_name' => $message['data']['to_name'],
  228. 'content' => $message['data']['content'],
  229. 'servicelog_id' => $message['data']['conversationId'],
  230. 'time_line' => time()
  231. ];
  232. self::$db->insert('ws_chat_log')->cols($serviceLog)->query();
  233. unset($serviceLog);
  234. }
  235. break;
  236. // 转接
  237. case 'changeGroup':
  238. // 通知客户端转接中
  239. $simpleList = self::$global->uidSimpleList;
  240. if (!isset($simpleList[$message['uid']])) { // 客户已经退出
  241. return;
  242. }
  243. $userClient = $simpleList[$message['uid']]['0'];
  244. $userGroup = $simpleList[$message['uid']]['1']; // 会员原来的分组也是客服的分组
  245. $reLink = [
  246. 'message_type' => 'relinkMessage'
  247. ];
  248. Gateway::sendToClient($userClient, json_encode($reLink));
  249. unset($reLink);
  250. // 记录该客服与该会员的服务结束
  251. self::$db->query("update `ws_service_log` set `end_time` = " . time() . " , `status` = '2' where `client_id`= '" . $userClient . "'");
  252. // 从当前客服的服务表中删除这个会员
  253. $old = $kfList = self::$global->kfList;
  254. if (!isset($kfList[$userGroup])) {
  255. $waitMsg = '暂时没有相关客服上班,请稍后再咨询。';
  256. // 逐一通知
  257. foreach (self::$global->userList as $vo) {
  258. $waitMessage = [
  259. 'message_type' => 'wait',
  260. 'data' => [
  261. 'content' => $waitMsg,
  262. ]
  263. ];
  264. Gateway::sendToClient($userClient, json_encode($waitMessage, 256));
  265. unset($waitMessage);
  266. }
  267. return;
  268. }
  269. $myList = $kfList[$userGroup]; // 该客服分组数组
  270. foreach ($myList as $key => $vo) {
  271. if (in_array($userClient, $vo['user_info'])) {
  272. // 维护现在的该客服的服务信息
  273. $kfList[$userGroup][$key]['task'] -= 1; // 当前服务的人数 -1
  274. foreach ($vo['user_info'] as $k => $v) {
  275. if ($userClient == $v) {
  276. unset($kfList[$userGroup][$key]['user_info'][$k]);
  277. break;
  278. }
  279. }
  280. break;
  281. }
  282. }
  283. while (!self::$global->cas('kfList', $old, $kfList)) {
  284. }; // 刷新内存中客服的服务列表
  285. unset($old, $kfList, $myList);
  286. // 将会员加入队列中
  287. $userList = self::$global->userList;
  288. do {
  289. $NewUserList = $userList;
  290. $NewUserList[$message['uid']] = [
  291. 'id' => $message['uid'],
  292. 'name' => $message['name'],
  293. 'avatar' => $message['avatar'],
  294. 'ip' => $message['ip'],
  295. 'group' => $message['group'], // 指定要链接的分组
  296. 'client_id' => $userClient
  297. ];
  298. } while (!self::$global->cas('userList', $userList, $NewUserList));
  299. unset($NewUserList, $userList);
  300. // 执行会员分配通知双方
  301. self::userOnlineTask($userClient, $message['group']);
  302. unset($userClient, $userGroup);
  303. break;
  304. case 'closeUser':
  305. $userInfo = self::$global->uidSimpleList;
  306. if (isset($userInfo[$message['uid']])) {
  307. $waitMessage = [
  308. 'message_type' => 'wait',
  309. 'data' => [
  310. 'content' => '暂时没有客服上班,请稍后再咨询。',
  311. ]
  312. ];
  313. Gateway::sendToClient($userInfo[$message['uid']]['0'], json_encode($waitMessage, 256));
  314. unset($waitMessage);
  315. }
  316. unset($userInfo);
  317. break;
  318. // 机器人问答.
  319. case 'toRobot':
  320. self::toRobot($client_id, $message);
  321. break;
  322. // 评价.
  323. case 'evaluate':
  324. self::evaluate($client_id, $message);
  325. break;
  326. // 客服关闭会话.
  327. case 'kfCloseUser':
  328. $client = Gateway::getClientIdByUid($message['data']['to_id']);
  329. if (!empty($client)) {
  330. self::serverClose($client['0']);
  331. }
  332. break;
  333. // default:
  334. // Gateway::closeClient($client_id);
  335. }
  336. }
  337. //客服接入sock,及初始化
  338. public static function Kfinit($client_id, $message){
  339. $kfList = self::$global->kfList;
  340. //客服登陆验证 不符合的直接断掉
  341. $logcheck = true ; //开发时使用
  342. //$logcheck = self::KfloginChedk($client_id, $message);
  343. if (!$logcheck) {
  344. Gateway::closeCurrentClient();
  345. return true;
  346. }
  347. // 如果该客服未在内存中记录则记录
  348. if (!isset($kfList[$message['group']]) || !array_key_exists($message['uid'], $kfList[$message['group']])) {
  349. do {
  350. $newKfList = $kfList;
  351. $newKfList[$message['group']][$message['uid']] = [
  352. 'id' => $message['uid'],
  353. 'name' => $message['name'],
  354. 'avatar' => $message['avatar'],
  355. 'client_id' => $client_id,
  356. 'task' => 0,
  357. 'user_info' => []
  358. ];
  359. } while (!self::$global->cas('kfList', $kfList, $newKfList));
  360. unset($newKfList, $kfList);
  361. } else if (isset($kfList[$message['group']][$message['uid']])) {
  362. do {
  363. $newKfList = $kfList;
  364. $newKfList[$message['group']][$message['uid']]['client_id'] = $client_id;
  365. } while (!self::$global->cas('kfList', $kfList, $newKfList));
  366. unset($newKfList, $kfList);
  367. }
  368. // 绑定 client_id 和 uid
  369. Gateway::bindUid($client_id, $message['uid']);
  370. $_SESSION['group'] = $message['group'];
  371. $_SESSION['iskefu'] = 1;
  372. $_SESSION['uid'] = $message['uid'];
  373. // TODO 尝试拉取用户来服务 [二期规划]
  374. }
  375. //客服登陆验证
  376. public static function KfloginChedk($client, $messageArray)
  377. {
  378. $uid = isset($messageArray['uid']) ? ($messageArray['uid']) : '';
  379. $token = isset($messageArray['token']) ?   ($messageArray['token']) : '';
  380. if (empty($uid) || empty($token)) {
  381. return false;
  382. }
  383. $expire_time_vali = time() - 60 * 60 * 24 * 3;
  384. $kfid = intval(substr($uid, 2));
  385. $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();
  386. if ($ret) {
  387. self::$db->update('ws_users')->cols(array('online_status'=>1,'online_connectid'=>$client))->where('id='.$kfid)->query();
  388. return $ret;
  389. }
  390. return false;
  391. }
  392. //用户发送邦定用户事件
  393. public static function userInitEnt($client_id, $message)
  394. {
  395. $userList = self::$global->userList;
  396. // 如果该顾客未在内存中记录则记录
  397. $uidSimpleList = self::$global->uidSimpleList;
  398. if (isset($uidSimpleList[$message['uid']])) {
  399. $uidSimpleList = self::$global->uidSimpleList;
  400. $oldclientid = $uidSimpleList[$message['uid']]['0'];
  401. Gateway::sendToClient($oldclientid, json_encode(['type' => 'reLoginErr', 'msg' => '相同账号登陆,本次退出'], 256));
  402. Gateway::closeClient($oldclientid);
  403. sleep(2);
  404. }
  405. if (!array_key_exists($message['uid'], $userList)) {
  406. do {
  407. $NewUserList = $userList;
  408. $NewUserList[$message['uid']] = [
  409. 'id' => $message['uid'],
  410. 'name' => $message['name'],
  411. 'avatar' => $message['avatar'],
  412. 'website' => $_SESSION['origin'],//$_SERVER['HTTP_ORIGIN'],
  413. 'browse' => Gateway::browse_info(),
  414. 'system' => Gateway::get_os(),
  415. 'ip' => isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '',
  416. 'group' => $message['group'],
  417. 'client_id' => $client_id
  418. ];
  419. } while (!self::$global->cas('userList', $userList, $NewUserList));
  420. unset($NewUserList, $userList);
  421. // 维护 UID对应的client_id 数组
  422. do {
  423. $old = $newList = self::$global->uidSimpleList;
  424. $newList[$message['uid']] = [
  425. $client_id,
  426. $message['group']
  427. ];
  428. } while (!self::$global->cas('uidSimpleList', $old, $newList));
  429. unset($old, $newList);
  430. // 写入接入值
  431. $key = date('Ymd') . 'total_in';
  432. self::$global->$key = 0;
  433. do {
  434. $oldKey = date('Ymd', strtotime('-1 day')); // 删除前一天的统计值
  435. unset(self::$global->$oldKey);
  436. } while (!self::$global->increment($key));
  437. unset($key);
  438. }
  439. // 绑定 client_id 和 uid
  440. Gateway::bindUid($client_id, $message['uid']);
  441. $_SESSION['iskefu'] = 0;
  442. $_SESSION['uid'] = $message['uid'];
  443. // 尝试分配新会员进入服务
  444. self::userOnlineTask($client_id, $message['group'], $message['uid']);
  445. }
  446. /**
  447. * 当用户断开连接时触发
  448. * @param int $client_id 连接id
  449. *
  450. * tips: 当服务端主动退出的时候,会出现 exit status 9.原因是:服务端主动断开之后,连接的客户端会走这个方法,而短时间内进程
  451. * 需要处理这多的逻辑,又有cas操作,导致进程退出会超时,然后会被内核杀死,从而报出错误 9.实际对真正的业务没有任何的影响。
  452. */
  453. public static function onClose($client_id)
  454. {
  455. $isKefuoff = isset($_SESSION['iskefu']) ? $_SESSION['iskefu'] : 0;
  456. $uid = isset($_SESSION['uid']) ? $_SESSION['uid'] : false;
  457. if (empty($uid)) {
  458. return;
  459. }
  460. if ($isKefuoff) {
  461. self::serviceOffline($client_id, $uid);
  462. } else {
  463. self::guestOffline($client_id, $uid);
  464. }
  465. return;
  466. }
  467. //客服下线了
  468. public static function serviceOffline($client_id, $uid)
  469. {
  470. $group = $_SESSION['group'];
  471. $kefuinfo_old = $kefuinfo_old_new = self::$global->kfList;
  472. $user_info = $kefuinfo_old_new[$group][$uid]['user_info'];
  473. $simpliUsers = self::$global->uidSimpleList;
  474. $simpliUsersID_UID_Arr = [];
  475. if (!empty($simpliUsers)) {
  476. foreach ($simpliUsers as $key => $val) {
  477. $simpliUsersID_UID_Arr[$val['0']] = $key;
  478. }
  479. }
  480. $now = time();
  481. if (!empty($user_info)) {
  482. foreach ($user_info as $val) {
  483. Gateway::sendToClient($val, json_encode(['type' => 'serviceoffline', 'msg' => '客户人员下线!'], 256));
  484. if (isset($simpliUsersID_UID_Arr[$val])) {
  485. 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 ");
  486. }
  487. Gateway::closeClient($val);
  488. }
  489. }
  490. unset($kefuinfo_old_new[$group][$uid]);
  491. $kfid = intval(substr($uid,2));
  492. self::$db->update('ws_users')->cols(array('online_status'=>0,'online_connectid'=>''))->where('id='.$kfid)->query();
  493. do {
  494. } while (!self::$global->cas('kfList', $kefuinfo_old, $kefuinfo_old_new));
  495. return;
  496. }
  497. //用户下线了
  498. public static function guestOffline($client_id, $uid)
  499. {
  500. $kfuid = -1;
  501. $krclient_id = 0;
  502. $kfgroup = -1;
  503. $userToKf = $userToKfNew = self::$global->userToKf;
  504. if (isset($userToKfNew[$uid])) {
  505. $kfuid = isset($userToKfNew[$uid]['1']) ? $userToKfNew[$uid]['1'] : -1;
  506. $krclient_id = isset(Gateway::getClientIdByUid($kfuid)['0']) ? Gateway::getClientIdByUid($kfuid)['0'] : 0;
  507. unset($userToKfNew[$uid]);
  508. do {
  509. } while (!self::$global->cas('userToKf', $userToKf, $userToKfNew));
  510. }
  511. $uidSimpleList = $uidSimpleListNew = self::$global->uidSimpleList;
  512. if (isset($uidSimpleListNew[$uid])) {
  513. $kfgroup = $uidSimpleListNew[$uid]['1'];
  514. unset($uidSimpleListNew[$uid]);
  515. do {
  516. } while (!self::$global->cas('uidSimpleList', $uidSimpleList, $uidSimpleListNew));
  517. }
  518. $userList = $userListNew = self::$global->userList;
  519. if (!empty($userList)) {
  520. $ischange = 0;
  521. foreach ($userList as $key => $val) {
  522. if ($val['id'] == $uid) {
  523. unset($userListNew[$key]);
  524. $ischange = 1;
  525. break;
  526. }
  527. }
  528. if ($ischange) {
  529. do {
  530. } while (!self::$global->cas('userList', $userList, $userListNew));
  531. }
  532. }
  533. if ($kfuid != -1 && $kfgroup != -1) {
  534. $kefuinfo_old = $kefuinfo_old_new = self::$global->kfList;
  535. $ischange_kf_list = 0;
  536. if (isset($kefuinfo_old[$kfgroup][$kfuid])) {
  537. $infos = $kefuinfo_old[$kfgroup][$kfuid]['user_info'];
  538. if ($infos) {
  539. if (is_array($infos)) {
  540. foreach ($infos as $key => $val) {
  541. if ($val == $client_id) {
  542. $ischange_kf_list = 1;
  543. unset($kefuinfo_old_new[$kfgroup][$kfuid]['user_info'][$key]);
  544. $kefuinfo_old_new[$kfgroup][$kfuid]['task'] = $kefuinfo_old_new[$kfgroup][$kfuid]['task'] - 1;
  545. }
  546. }
  547. }
  548. if ($ischange_kf_list) {
  549. do {
  550. } while (!self::$global->cas('kfList', $kefuinfo_old, $kefuinfo_old_new));
  551. $chat_message = [
  552. 'message_type' => 'userClose',
  553. 'data' => [
  554. 'content' => '用户连接已断开',
  555. 'time' => date('H:i'),
  556. ]
  557. ];
  558. $now = time();
  559. $kf__uid = substr($kfuid, 2);
  560. $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 ";
  561. //echo "客户退出:". $sql ."\n";
  562. self::$db->query($sql);
  563. Gateway::sendToClient($krclient_id, json_encode($chat_message, 256));
  564. }
  565. }
  566. }
  567. }
  568. }
  569. /**
  570. * 客服结束会话
  571. * @param int $client_id 连接id
  572. *
  573. * tips: 当服务端主动退出的时候,会出现 exit status 9.原因是:服务端主动断开之后,连接的客户端会走这个方法,而短时间内进程
  574. * 需要处理这多的逻辑,又有cas操作,导致进程退出会超时,然后会被内核杀死,从而报出错误 9.实际对真正的业务没有任何的影响。
  575. */
  576. public static function serverClose($client_id)
  577. {
  578. // 返回.
  579. $chat_message = [
  580. 'message_type' => 'closeBysever',
  581. 'data' => [
  582. 'content' => '客服停止了该会话',
  583. 'time' => date('H:i'),
  584. ]
  585. ];
  586. Gateway::sendToClient($client_id, json_encode($chat_message, 256));
  587. Gateway::closeClient($client_id);
  588. $isServiceUserOut = false;
  589. // 将会员服务信息,从客服的服务列表中移除
  590. $old = $kfList = self::$global->kfList;
  591. foreach ($kfList as $k => $v) {
  592. foreach ($v as $key => $vo) {
  593. if (in_array($client_id, $vo['user_info'])) {
  594. $isServiceUserOut = true;
  595. // 根据client id 去更新会话工单一些信息
  596. self::$db->query("update `ws_service_log` set `end_time` = " . time() . " , `status` = '2' where `client_id`= '" . $client_id . "'");
  597. // 从会员的内存表中检索出该会员的信息,并更新内存
  598. $oldSimple = $simpleList = self::$global->uidSimpleList;
  599. $outUser = [];
  600. foreach ($simpleList as $u => $c) {
  601. if ($c['0'] == $client_id) {
  602. $outUser[] = [
  603. 'user_id' => $u,
  604. 'group_id' => $c['1']
  605. ];
  606. unset($simpleList[$u]);
  607. break;
  608. }
  609. }
  610. while (!self::$global->cas('uidSimpleList', $oldSimple, $simpleList)) {
  611. };
  612. unset($oldSimple, $simpleList);
  613. $outUser = self::$db->query("select `user_id`,`group_id` from `ws_service_log` where `client_id`= '" . $client_id . "'");
  614. // 通知 客服删除退出的用户
  615. if (!empty($outUser)) {
  616. $del_message = [
  617. 'message_type' => 'delUser',
  618. 'data' => [
  619. 'id' => $outUser['0']['user_id']
  620. ]
  621. ];
  622. Gateway::sendToClient($vo['client_id'], json_encode($del_message, 256));
  623. unset($del_message);
  624. // 尝试分配新会员进入服务
  625. self::userOfflineTask($outUser['0']['group_id']);
  626. }
  627. unset($outUser);
  628. // 维护现在的该客服的服务信息
  629. $kfList[$k][$key]['task'] -= 1; // 当前服务的人数 -1
  630. foreach ($vo['user_info'] as $m => $l) {
  631. if ($client_id == $l) {
  632. unset($kfList[$k][$key]['user_info'][$m]);
  633. break;
  634. }
  635. }
  636. // 刷新内存中客服的服务列表
  637. while (!self::$global->cas('kfList', $old, $kfList)) {
  638. };
  639. unset($old, $kfList);
  640. break;
  641. }
  642. }
  643. if ($isServiceUserOut) break;
  644. }
  645. // 尝试从排队的用户中删除退出的客户端
  646. if (false == $isServiceUserOut) {
  647. $old = $userList = self::$global->userList;
  648. foreach (self::$global->userList as $key => $vo) {
  649. if ($client_id == $vo['client_id']) {
  650. $isServiceUserOut = true;
  651. unset($userList[$key]);
  652. break;
  653. }
  654. }
  655. while (!self::$global->cas('userList', $old, $userList)) {
  656. };
  657. // 从会员的内存表中检索出该会员的信息,并更新内存
  658. $oldSimple = $simpleList = self::$global->uidSimpleList;
  659. foreach ($simpleList as $u => $c) {
  660. if ($c['0'] == $client_id) {
  661. unset($simpleList[$u]);
  662. break;
  663. }
  664. }
  665. while (!self::$global->cas('uidSimpleList', $oldSimple, $simpleList)) {
  666. };
  667. unset($oldSimple, $simpleList);
  668. }
  669. // 尝试是否是客服退出
  670. if (false == $isServiceUserOut) {
  671. $old = $kfList = self::$global->kfList;
  672. foreach (self::$global->kfList as $k => $v) {
  673. foreach ($v as $key => $vo) {
  674. // 客服服务列表中无数据,才去删除客服内存信息
  675. if ($client_id == $vo['client_id'] && (0 == count($vo['user_info']))) {
  676. unset($kfList[$k][$key]);
  677. break;
  678. }
  679. }
  680. }
  681. while (!self::$global->cas('kfList', $old, $kfList)) {
  682. };
  683. }
  684. }
  685. /**
  686. * 有人退出
  687. * @param $group
  688. */
  689. private static function userOfflineTask($group)
  690. {
  691. // TODO 此处查询最大的可服务人数,后面可以用其他的方式,存储这个数值,让其更高效的访问
  692. $maxNumber = self::getMaxServiceNum();
  693. $res = self::assignmentTask(self::$global->kfList, self::$global->userList, $group, $maxNumber);
  694. unset($maxNumber);
  695. if (1 == $res['code']) {
  696. while (!self::$global->cas('kfList', self::$global->kfList, $res['data']['4'])) {
  697. }; // 更新客服数据
  698. while (!self::$global->cas('userList', self::$global->userList, $res['data']['5'])) {
  699. }; // 更新会员数据
  700. // 通知会员发送信息绑定客服的id
  701. $noticeUser = [
  702. 'message_type' => 'connect',
  703. 'data' => [
  704. 'kf_id' => $res['data']['0'],
  705. 'kf_name' => $res['data']['1']
  706. ]
  707. ];
  708. Gateway::sendToClient($res['data']['3']['client_id'], json_encode($noticeUser, 256));
  709. unset($noticeUser);
  710. // 通知客服端绑定会员的信息
  711. $noticeKf = [
  712. 'message_type' => 'connect',
  713. 'data' => [
  714. 'user_info' => $res['data']['3']
  715. ]
  716. ];
  717. Gateway::sendToClient($res['data']['2'], json_encode($noticeKf, 256));
  718. unset($noticeKf);
  719. // 逐一通知
  720. $number = 1;
  721. foreach (self::$global->userList as $vo) {
  722. $waitMsg = '您前面还有 ' . $number . ' 位会员在等待。';
  723. $waitMessage = [
  724. 'message_type' => 'wait',
  725. 'data' => [
  726. 'content' => $waitMsg,
  727. ]
  728. ];
  729. Gateway::sendToClient($vo['client_id'], json_encode($waitMessage, 256));
  730. $number++;
  731. }
  732. unset($waitMessage, $number);
  733. // 写入接入值
  734. $key = date('Ymd') . 'success_in';
  735. self::$global->$key = 0;
  736. do {
  737. $oldKey = date('Ymd', strtotime('-1 day')); // 删除前一天的统计值
  738. unset(self::$global->$oldKey);
  739. } while (!self::$global->increment($key));
  740. unset($key);
  741. } else {
  742. switch ($res['code']) {
  743. case -1:
  744. $waitMsg = '暂时没有客服上班,请稍后再咨询。';
  745. // 逐一通知
  746. foreach (self::$global->userList as $vo) {
  747. $waitMessage = [
  748. 'message_type' => 'wait',
  749. 'data' => [
  750. 'content' => $waitMsg,
  751. ]
  752. ];
  753. Gateway::sendToClient($vo['client_id'], json_encode($waitMessage, 256));
  754. }
  755. break;
  756. case -2:
  757. break;
  758. case -3:
  759. break;
  760. case -4:
  761. // 逐一通知
  762. $number = 1;
  763. foreach (self::$global->userList as $vo) {
  764. $waitMsg = '您前面还有 ' . $number . ' 位会员在等待。';
  765. $waitMessage = [
  766. 'message_type' => 'wait',
  767. 'data' => [
  768. 'content' => $waitMsg,
  769. ]
  770. ];
  771. Gateway::sendToClient($vo['client_id'], json_encode($waitMessage, 256));
  772. $number++;
  773. }
  774. break;
  775. }
  776. unset($waitMessage, $number);
  777. }
  778. }
  779. /**
  780. * 有人进入执行分配
  781. * @param $client_id
  782. * @param $group
  783. * @param $uid
  784. */
  785. private static function userOnlineTask($client_id, $group, $uid = 0)
  786. {
  787. // TODO 此处查询最大的可服务人数,后面可以用其他的方式,存储这个数值,让其更高效的访问
  788. $maxNumber = self::getMaxServiceNum();
  789. $res = self::assignmentTask(self::$global->kfList, self::$global->userList, $group, $maxNumber, $uid);
  790. unset($maxNumber);
  791. if (1 == $res['code']) {
  792. while (!self::$global->cas('kfList', self::$global->kfList, $res['data']['4'])) {
  793. }; // 更新客服数据
  794. while (!self::$global->cas('userList', self::$global->userList, $res['data']['5'])) {
  795. }; // 更新会员数据
  796. $userToKf = self::$global->userToKf;
  797. $userToKf[$res['data']['3']['id']] = [
  798. $res['data']['3']['id'],
  799. $res['data']['0']
  800. ];
  801. self::$global->userToKf = $userToKf;
  802. // 服务信息入库
  803. $serviceLog = [
  804. 'user_id' => $res['data']['3']['id'],
  805. 'client_id' => $res['data']['3']['client_id'],
  806. 'user_name' => $res['data']['3']['name'],
  807. 'user_ip' => $res['data']['3']['ip'],
  808. 'user_avatar' => $res['data']['3']['avatar'],
  809. 'kf_id' => intval(ltrim($res['data']['0'], 'KF')),
  810. 'start_time' => time(),
  811. 'group_id' => $group,
  812. 'website' => $res['data']['3']['website'],
  813. 'system' => $res['data']['3']['system'],
  814. 'browse' => $res['data']['3']['browse'],
  815. 'status' => 1,
  816. 'end_time' => 0
  817. ];
  818. $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();
  819. if (!$hisSession) {
  820. $conversationId = self::$db->insert('ws_service_log')->cols($serviceLog)->query();
  821. } else {
  822. self::$db->update('ws_service_log')->cols(['status' => 1])->where('servicelog_id=' . $hisSession['servicelog_id'])->query();
  823. $conversationId = $hisSession['servicelog_id'];
  824. }
  825. unset($serviceLog);
  826. // 通知会员发送信息绑定客服的id
  827. $noticeUser = [
  828. 'message_type' => 'connect',
  829. 'data' => [
  830. 'kf_id' => $res['data']['0'],
  831. 'conversationId' => $conversationId,
  832. 'kf_name' => $res['data']['1']
  833. ]
  834. ];
  835. Gateway::sendToClient($client_id, json_encode($noticeUser, 256));
  836. unset($noticeUser);
  837. // 通知客服端绑定会员的信息
  838. $noticeKf = [
  839. 'message_type' => 'connect',
  840. 'data' => [
  841. 'user_info' => $res['data']['3'],
  842. 'conversationId' => $conversationId,
  843. ]
  844. ];
  845. Gateway::sendToClient($res['data']['2'], json_encode($noticeKf, 256));
  846. unset($noticeKf);
  847. // 写入接入值
  848. $key = date('Ymd') . 'success_in';
  849. self::$global->$key = 0;
  850. do {
  851. $oldKey = date('Ymd', strtotime('-1 day')); // 删除前一天的统计值
  852. unset(self::$global->$oldKey);
  853. } while (!self::$global->increment($key));
  854. unset($key);
  855. } else {
  856. $waitMsg = '';
  857. switch ($res['code']) {
  858. case -1:
  859. $waitMsg = '暂时没有客服上班,请稍后再咨询。';
  860. break;
  861. case -2:
  862. break;
  863. case -3:
  864. break;
  865. case -4:
  866. $number = count(self::$global->userList);
  867. $waitMsg = '您前面还有 ' . $number . ' 位会员在等待。';
  868. break;
  869. }
  870. $waitMessage = [
  871. 'message_type' => 'wait',
  872. 'data' => [
  873. 'content' => $waitMsg,
  874. ]
  875. ];
  876. Gateway::sendToClient($client_id, json_encode($waitMessage, 256));
  877. unset($waitMessage);
  878. }
  879. }
  880. /**
  881. * 给客服分配会员【均分策略】
  882. * @param $kfList
  883. * @param $userList
  884. * @param $group
  885. * @param $total
  886. */
  887. private static function assignmentTask($kfList, $userList, $group, $total, $uid = 0)
  888. {
  889. // 没有客服上线
  890. if (empty($kfList) || empty($kfList[$group])) {
  891. return ['code' => -1];
  892. }
  893. // 没有待分配的会员
  894. if (empty($userList)) {
  895. return ['code' => -2];
  896. }
  897. // 未设置每个客服可以服务多少人
  898. if (0 == $total) {
  899. return ['code' => -3];
  900. }
  901. // 查看该组的客服是否在线
  902. if (!isset($kfList[$group])) {
  903. return ['code' => -1];
  904. }
  905. //上次用户掉线后,还可以继续上一次 (如果没有关闭) 的会话 --1
  906. $odltalksession = false;
  907. $user = $user_first = array_shift($userList);
  908. if ($uid > 0 && $user['id'] != $uid && count($userList) > 1) {
  909. $timevalielimit = time() - 60 * 5;
  910. $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();
  911. if ($odltalksession) {
  912. foreach ($userList as $ttkey => $ttval) {
  913. if ($ttval['id'] == $uid) {
  914. array_unshift($userList, $user);
  915. $user = $userList[$ttkey];
  916. unset($userList[$ttkey]);
  917. break;
  918. }
  919. }
  920. }
  921. }
  922. //上次用户掉线后,还可以继续上一次 (如果没有关闭) 的会话 --2
  923. if ($odltalksession) {
  924. $oldkrid = 'KF' . $odltalksession['kf_id'];
  925. if (isset($kfList[$group][$oldkrid])) {
  926. $kf = $kfList[$group][$oldkrid];
  927. $min = $kf['task'];
  928. $flag = $kf['id'];
  929. unset($kfList[$group][$oldkrid]);
  930. } else {
  931. goto NOSIGNKF;
  932. }
  933. } else {
  934. NOSIGNKF:
  935. $kf = $kfList[$group];
  936. $kf = array_shift($kf);
  937. $min = $kf['task'];
  938. $flag = $kf['id'];
  939. foreach ($kfList[$group] as $key => $vo) {
  940. if ($vo['task'] < $min) {
  941. $min = $vo['task'];
  942. $flag = $key;
  943. }
  944. }
  945. unset($kf);
  946. }
  947. // 需要排队了
  948. if ($kfList[$group][$flag]['task'] == $total) {
  949. return ['code' => -4];
  950. }
  951. $kfList[$group][$flag]['task'] += 1;
  952. array_push($kfList[$group][$flag]['user_info'], $user['client_id']); // 被分配的用户信息
  953. return [
  954. 'code' => 1,
  955. 'data' => [
  956. $kfList[$group][$flag]['id'],
  957. $kfList[$group][$flag]['name'],
  958. $kfList[$group][$flag]['client_id'],
  959. $user,
  960. $kfList,
  961. $userList
  962. ]
  963. ];
  964. }
  965. /**
  966. * 获取最大的服务人数
  967. * @return int
  968. */
  969. private static function getMaxServiceNum()
  970. {
  971. $maxNumber = self::$db->query('select `max_service` from `ws_kf_config` where `id` = 1');
  972. if (!empty($maxNumber)) {
  973. $maxNumber = 5;
  974. } else {
  975. $maxNumber = $maxNumber['0']['max_service'];
  976. }
  977. return $maxNumber;
  978. }
  979. /**
  980. * 将内存中的数据写入统计表
  981. * @param int $flag
  982. */
  983. private static function writeLog($flag = 1)
  984. {
  985. // 上午 8点 到 22 点开始统计
  986. if (date('H') < 8 || date('H') > 22) {
  987. return;
  988. }
  989. // 当前正在接入的人 和 在线客服数
  990. $kfList = self::$global->kfList;
  991. $nowTalking = 0;
  992. $onlineKf = 0;
  993. if (!empty($kfList)) {
  994. foreach ($kfList as $key => $vo) {
  995. $onlineKf += count($vo);
  996. foreach ($vo as $k => $v) {
  997. $nowTalking += count($v['user_info']);
  998. }
  999. }
  1000. }
  1001. // 在队列中的用户
  1002. $inQueue = count(self::$global->userList);
  1003. $key = date('Ymd') . 'total_in';
  1004. $key2 = date('Ymd') . 'success_in';
  1005. $param = [
  1006. 'is_talking' => $nowTalking,
  1007. 'in_queue' => $inQueue,
  1008. 'online_kf' => $onlineKf,
  1009. 'success_in' => self::$global->$key2,
  1010. 'total_in' => self::$global->$key,
  1011. 'now_date' => date('Y-m-d')
  1012. ];
  1013. self::$db->update('ws_now_data')->cols($param)->where('id=1')->query();
  1014. if (2 == $flag) {
  1015. $param = [
  1016. 'is_talking' => $nowTalking,
  1017. 'in_queue' => $inQueue,
  1018. 'online_kf' => $onlineKf,
  1019. 'success_in' => self::$global->$key2,
  1020. 'total_in' => self::$global->$key,
  1021. 'add_date' => date('Y-m-d'),
  1022. 'add_hour' => date('H'),
  1023. 'add_minute' => date('i'),
  1024. ];
  1025. self::$db->insert('ws_service_data')->cols($param)->query();
  1026. }
  1027. unset($kfList, $nowTalking, $inQueue, $onlineKf, $key, $key2, $param);
  1028. }
  1029. /**
  1030. * 机器人问答
  1031. * @param $client_id 服务ID
  1032. * @param $message 数据
  1033. */
  1034. private static function toRobot($client_id, $message)
  1035. {
  1036. $groups_id = $message['data']['groups_id'];
  1037. $robot_name = $message['data']['robot_name'];
  1038. $robotgroups_id = $message['data']['robotgroups_id'];
  1039. // 查询问题.
  1040. $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 . "'");
  1041. $chat_message = [
  1042. 'message_type' => 'chatMessage',
  1043. 'data' => [
  1044. 'name' => '智能助手',
  1045. 'time' => date('H:i'),
  1046. 'content' => $getRobot ? htmlspecialchars($getRobot[0]['robot_content']) : 'error',
  1047. ]
  1048. ];
  1049. Gateway::sendToClient($client_id, json_encode($chat_message, 256));
  1050. }
  1051. /**
  1052. * 评价
  1053. * @param $client_id 服务ID
  1054. * @param $message 数据
  1055. */
  1056. private static function evaluate($client_id, $message)
  1057. {
  1058. // 修改数据库.
  1059. $evaluate_id = $message['data']['evaluate_id'];
  1060. $result = self::$db->query("UPDATE `ws_service_log` SET `evaluate_id` = '" . $evaluate_id . "' WHERE `client_id`='" . $client_id . "'");
  1061. if ($result) {
  1062. $chat_message = [
  1063. 'message_type' => 'evaluate',
  1064. 'data' => [
  1065. 'status' => 1,
  1066. 'time' => date('H:i'),
  1067. ]
  1068. ];
  1069. } else {
  1070. $chat_message = [
  1071. 'message_type' => 'evaluate',
  1072. 'data' => [
  1073. 'status' => 2,
  1074. 'time' => date('H:i'),
  1075. ]
  1076. ];
  1077. }
  1078. Gateway::sendToClient($client_id, json_encode($chat_message));
  1079. }
  1080. //踢掉同一用户的旧用户
  1081. private static function tickOlduser($uid)
  1082. {
  1083. }
  1084. }