Im.php 51 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325
  1. <?php
  2. namespace app\enterprise\controller;
  3. use app\BaseController;
  4. use think\facade\Session;
  5. use think\facade\Db;
  6. use app\enterprise\model\{User, Message, GroupUser, Friend,Group,ChatDelog};
  7. use GatewayClient\Gateway;
  8. use Exception;
  9. use think\facade\Cache;
  10. use app\manage\model\{Config};
  11. use app\admin\model\GuessAskLanguages;
  12. use app\admin\model\QuestionLanguages;
  13. use app\admin\model\Complaint;
  14. use app\admin\model\ComplaintItem;
  15. use app\admin\model\Score;
  16. class Im extends BaseController
  17. {
  18. protected $fileType = ['file', 'image','video','voice','emoji'];
  19. /**
  20. * 给客服打分
  21. */
  22. public function Score()
  23. {
  24. $score = $this->request->param('score');
  25. $msg_id = $this->request->param('msg_id');
  26. if (empty($msg_id)) {
  27. return $this->error('参数有误',[], 10009);
  28. }
  29. if (empty($score)) {
  30. return $this->error('请打分',[], 10009);
  31. }
  32. $user_id = $this->userInfo['user_id'];
  33. $user = User::where('user_id', $user_id)->find();
  34. if (!$user) {
  35. return $this->error('用户不存在',[], 10009);
  36. }
  37. $exist = Message::where('msg_id', $msg_id)->where('to_user', $user_id)->find();
  38. if ($exist) {
  39. if ( $exist['is_click'] == 1) {
  40. return $this->error('已评价',[], 10009);
  41. }
  42. $extends = $exist['extends'] && !is_array($exist['extends']) ? json_decode($exist['extends'], true) : $exist['extends'];
  43. if (!empty($extends['cs_uid'])) {
  44. Score::create([
  45. 'user_id' => $user_id,
  46. 'cs_uid' => $extends['cs_uid'],
  47. 'score' => (int)$score,
  48. ]);
  49. //保留一位小数
  50. $avg_score = Score::where('cs_uid', $extends['cs_uid'])->avg('score');
  51. $avg_score = number_format($avg_score, 1);
  52. User::where('user_id', $extends['cs_uid'])->update(['score' => $avg_score]);
  53. }
  54. $exist->is_click = 1;
  55. $exist->save();
  56. }
  57. return $this->success([],'提交成功');
  58. }
  59. /**
  60. */
  61. public function complaintList()
  62. {
  63. try {
  64. $params = $this->request->param();
  65. $page = $params['page'] ?? 1;
  66. $limit = $params['limit'] ?? 15;
  67. $language_code = $params['language_code'] ?? $this->lang;
  68. $query = ComplaintItem::where('language_code', $language_code);
  69. $count = $query->count();
  70. $list = $query->order('weight','desc')
  71. ->limit($limit)
  72. ->page($page)
  73. ->select();
  74. } catch (Exception $e) {
  75. return $this->error($e->getMessage());
  76. }
  77. return $this->success(['count' => $count, 'list' => $list]);
  78. }
  79. /**
  80. * 投诉客服
  81. */
  82. public function complaint()
  83. {
  84. $params = $this->request->param();
  85. if (empty($params['complaint_item_id'])) {
  86. return $this->error('请选择投诉项',[], 10009);
  87. }
  88. $user_id = $this->userInfo['user_id'];
  89. $user = User::where('user_id', $user_id)->find();
  90. if (!$user) {
  91. return $this->error('用户不存在',[], 10009);
  92. }
  93. $exist = Complaint::where('user_id', $user_id)->where('cs_uid', $user->cs_uid)->find();
  94. if ($exist) {
  95. return $this->error('您已投诉过该客服,无需重复投诉',[], 10009);
  96. }
  97. Complaint::create([
  98. 'user_id' => $user_id,
  99. 'cs_uid' => $user->cs_uid,
  100. 'complaint_item_id' => $params['complaint_item_id'],
  101. 'remark' => $params['remark'] ?? '',
  102. 'language_code' => $this->lang,
  103. ]);
  104. return $this->success([],'提交成功');
  105. }
  106. /**
  107. * 猜你想问列表
  108. */
  109. public function guessask()
  110. {
  111. try {
  112. $params = $this->request->param();
  113. $page = $params['page'] ?? 1;
  114. $limit = $params['limit'] ?? 15;
  115. $language_code = $this->lang;
  116. $query = GuessAskLanguages::where('language_code', $language_code)->where('status', 1);
  117. if (!empty($params['keyword'])) {
  118. $query = $query->where('name', 'like', '%'.$params['keyword'].'%');
  119. }
  120. if (isset($params['type']) && $params['type'] != '') {
  121. $query = $query->where('type', $params['type']);
  122. }
  123. $count = $query->count();
  124. $list = $query->order('is_top','desc')
  125. ->order('is_rec','desc')
  126. ->order('click_num','desc')
  127. ->limit($limit)
  128. ->page($page)
  129. ->select();
  130. } catch (Exception $e) {
  131. return $this->error($e->getMessage());
  132. }
  133. return $this->success(['count' => $count, 'list' => $list]);
  134. }
  135. /**
  136. * 猜你想问点击使用
  137. */
  138. function guessaskClick()
  139. {
  140. try {
  141. $id = $this->request->param('id');
  142. $info = GuessAskLanguages::where('id', $id)->where('status', 1)->find();
  143. if ($info) {
  144. $info->click_num = $info->click_num + 1;
  145. $info->save();
  146. }
  147. } catch (Exception $e) {
  148. return $this->error($e->getMessage());
  149. }
  150. return $this->success([]);
  151. }
  152. /**
  153. * 问题列表
  154. */
  155. function question()
  156. {
  157. try {
  158. $params = $this->request->param();
  159. $page = $params['page'] ?? 1;
  160. $limit = $params['limit'] ?? 15;
  161. $language_code = $this->lang;
  162. $query = QuestionLanguages::where('language_code', $language_code)->where('status', 1);
  163. if (isset($params['question_type']) && $params['question_type'] != '') {
  164. $query = $query->where('question_type', $params['question_type']);
  165. }
  166. $count = $query->count();
  167. $list = $query->order('weight','desc')
  168. ->limit($limit)
  169. ->page($page)
  170. ->select();
  171. } catch (Exception $e) {
  172. return error($e->getMessage());
  173. }
  174. return $this->success(['count' => $count, 'list' => $list]);
  175. }
  176. /**
  177. * 问题点赞、点否
  178. */
  179. function questionClick()
  180. {
  181. try {
  182. $is_like = $this->request->param('is_like');
  183. $msg_id = $this->request->param('msg_id');
  184. if (empty($msg_id) || !in_array($is_like, [1, 0])) {
  185. return $this->error('参数有误',[], 10009);
  186. }
  187. $user_id = $this->userInfo['user_id'];
  188. $exist = Message::where('msg_id', $msg_id)->where('to_user', $user_id)->find();
  189. if ($exist && $exist['is_click'] == 0) {
  190. $extends = $exist['extends'];
  191. $id = $extends['question_id'] ?? 0;
  192. if ($id) {
  193. if ($is_like == 1) {
  194. QuestionLanguages::where('id', $id)->update(['like_count'=>Db::raw('like_count+1')]);
  195. } else {
  196. QuestionLanguages::where('id', $id)->update(['dislike_count'=>Db::raw('dislike_count+1')]);
  197. }
  198. }
  199. $exist->is_click = $is_like == 1 ? 1 : 2;
  200. $exist->save();
  201. }
  202. } catch (Exception $e) {
  203. return $this->error($e->getMessage());
  204. }
  205. return $this->success([]);
  206. }
  207. /**
  208. * 转人工客服
  209. */
  210. function transferHuman()
  211. {
  212. try {
  213. $user_id = $this->userInfo['user_id'];
  214. $user = User::where('user_id', $user_id)->find();
  215. if (!$user) {
  216. return $this->error('用户不存在',[], 10009);
  217. }
  218. if ($user->role > 0) {
  219. return $this->error('系统管理员无法转人工',[], 10009);
  220. }
  221. if($user->service_status == -1) {
  222. //机器人客服
  223. $auto_cs_uid = getAutoCsUid();
  224. $user->service_status = 0;
  225. $user->service_start = time();
  226. $user->timeout_type = 0;
  227. $user->cs_uid = $auto_cs_uid;
  228. $user->save();
  229. $param = [
  230. 'id' => \utils\Str::getUuid(),
  231. 'type' => 'text',
  232. 'status' => 'going',
  233. 'sendTime' => time() * 1000,
  234. 'toContactId' => $user_id,
  235. 'content' => Config::getFieldValue('transfer_to_human', $this->lang),
  236. 'file_id' => 0,
  237. 'is_group' => 0,
  238. 'user_id' => $auto_cs_uid,
  239. ];
  240. Message::sendMsg($param, 0);
  241. //通知客服已接线
  242. wsSendMsg(0,'handleChat',['user_id'=>$user_id]);
  243. }
  244. } catch (Exception $e) {
  245. return $this->error($e->getMessage());
  246. }
  247. return $this->success([]);
  248. }
  249. // 获取联系人列表
  250. public function getContacts()
  251. {
  252. $this->userInfo['cs_uid'] = User::where('user_id', $this->userInfo['user_id'])->value('cs_uid');
  253. $map = [['status', '=', 1], ['user_id', '<>', $this->userInfo['user_id']]];
  254. // if ($this->userInfo['role'] != 0) {
  255. // $map[] = ['service_status', '<>', -1];
  256. // }
  257. $data = User::getUserList($this->userInfo, $map, $this->userInfo['user_id'] , '', $this->userInfo['role']);
  258. $count=Friend::where(['status'=>2,'friend_user_id'=>$this->uid])->count();
  259. $time=Friend::where(['friend_user_id'=>$this->uid,'is_invite'=>1])->order('create_time desc')->value('create_time');
  260. return success('', $data,$count,$time*1000);
  261. }
  262. // 获取聊天列表
  263. public function getChatList()
  264. {
  265. $data = User::getChatList($this->userInfo['user_id']);
  266. $count=Friend::where(['status'=>2,'friend_user_id'=>$this->uid])->count();
  267. $time=Friend::where(['friend_user_id'=>$this->uid,'is_invite'=>1])->order('create_time desc')->value('create_time');
  268. return success('', $data,$count,$time*1000);
  269. }
  270. // 获取好友列表
  271. public function getFriendList()
  272. {
  273. $data = User::getFriendList([['status', '=', 1], ['user_id', '<>', $this->userInfo['user_id']]],$this->userInfo['user_id']);
  274. return success('', $data);
  275. }
  276. // 获取群聊列表
  277. public function getGroupList()
  278. {
  279. $data = User::getGroupList($this->userInfo['user_id']);
  280. return success('', $data);
  281. }
  282. // 获取单个人员的信息
  283. public function getContactInfo(){
  284. $id = $this->request->param('id');
  285. $is_group = is_string($id) ? 1 : 0;
  286. $user=new User;
  287. $data=$user->setContact($id,$is_group);
  288. if(!$data){
  289. return warning($user->getError());
  290. }
  291. return success('',$data);
  292. }
  293. //发送消息
  294. public function sendMessage()
  295. {
  296. $param = $this->request->param();
  297. $content = strip_tags($param['content']);
  298. if (empty($content) || $content == '') {
  299. return warning("请输入内容");
  300. }
  301. $param['user_id'] = $this->userInfo['user_id'];
  302. $param['language_code'] = $this->lang;
  303. if ($this->userInfo['role'] != 0 && $param['type'] == 'text') {
  304. //客服或管理员给用户发送消息,需要按照用户的语言做翻译
  305. $toContactId = $param['toContactId'];
  306. $toUser = User::where('user_id', $toContactId)->field(['role', 'language_code'])->find();
  307. if ($toUser && $toUser['role'] == 0 && $toUser['language_code']) {
  308. //谷歌翻译
  309. $param['translate_content'] = google_translate($param['content'], $toUser['language_code']);
  310. $param['language_code'] = $toUser['language_code'];
  311. }
  312. }
  313. // if ($this->userInfo['role'] == 0) {
  314. // //用户发送消息时,如果是机器人对话的状态,则变更为排队中
  315. // $service_status = User::where('user_id', $this->userInfo['user_id'])->value('service_status');
  316. // if ($service_status == -1) {
  317. // User::where('user_id', $this->userInfo['user_id'])->update(['service_status' => 0]);
  318. // }
  319. // }
  320. $param['language_code'] = $this->lang;
  321. $message=new Message();
  322. $data = $message->sendMessage($param,$this->globalConfig);
  323. //已发送的消息,设置成已读
  324. // if (isset($data['is_read'])) {
  325. // $data['is_read'] = 1;
  326. // }
  327. if ($data) {
  328. return success('', $data);
  329. } else {
  330. return warning($message->getError());
  331. }
  332. }
  333. //转发消息
  334. public function forwardMessage()
  335. {
  336. $param = $this->request->param();
  337. $userIds=$param['user_ids'] ?? [];
  338. if(!$userIds || count($userIds)>5){
  339. return warning(lang('im.forwardLimit',['count'=>5]));
  340. }
  341. $msg_id=$param['msg_id'] ?? 0;
  342. $message=Message::find($msg_id);
  343. if(!$message){
  344. return warning(lang('im.exist'));
  345. }
  346. $msg=$message->toArray();
  347. $userInfo=$this->userInfo;
  348. queuePush([
  349. 'action'=>'forwardMessage',
  350. 'message'=>$msg,
  351. 'user_ids'=>$userIds,
  352. 'config'=>$this->globalConfig,
  353. 'userInfo'=>$userInfo
  354. ]);
  355. return success(lang('im.forwardOk'));
  356. }
  357. // 获取用户信息
  358. public function getUserInfo()
  359. {
  360. $user_id = $this->request->param('user_id');
  361. $group_id = $this->request->param('group_id');
  362. $groupInfo=[];
  363. if($group_id){
  364. $group_id = explode('-', $group_id)[1];
  365. $groupInfo=Group::where(['group_id'=>$group_id])->find();
  366. if($groupInfo){
  367. // 查询操作对象的角色
  368. $groupInfo['userInfo']=GroupUser::where(['user_id'=>$user_id,'group_id'=>$group_id])->find() ?: [];
  369. // 查询我的角色
  370. $groupInfo['manageRole']=GroupUser::where(['user_id'=>$this->userInfo['user_id'],'group_id'=>$group_id])->value('role') ?: 3;
  371. }
  372. }
  373. $user=User::find($user_id);
  374. if(!$user){
  375. return error(lang('user.exist'));
  376. }
  377. $user->avatar=avatarUrl($user->avatar,$user->realname,$user->user_id,120);
  378. // 账号前面截取3位,后面截取两位,中间星号展示
  379. $user->account=substr($user->account, 0, 3).'******'.substr($user->account, -2, 2);
  380. // 查询好友关系
  381. $friend=Friend::where(['friend_user_id'=>$user_id,'create_user'=>$this->userInfo['user_id'],'status'=>1])->find();
  382. $user->friend=$friend ? : '';
  383. $location='';
  384. if($user->last_login_ip){
  385. $location=implode(" ", \Ip::find($user->last_login_ip));
  386. }
  387. $user->location=$location;
  388. $user->groupInfo=$groupInfo ? : [];
  389. $user->password='';
  390. $userModel=new User;
  391. $user->contactInfo=$userModel->setContact($user_id,0) ?? [];
  392. return success('', $user);
  393. }
  394. // 扫码登录,向客户端推送数据
  395. public function tokenLogin(){
  396. $param = $this->request->param();
  397. $token=$param['token'] ?? '';
  398. $client_id='';
  399. if($token){
  400. $client_id=authcode(urldecode($token),"DECODE", config('app.app_id'));
  401. if(!$client_id){
  402. return warning(lang('user.loginError'));
  403. }
  404. }else{
  405. return warning(lang('user.loginError'));
  406. }
  407. $userInfo=$this->userInfo;
  408. if(!$userInfo){
  409. return warning(lang('user.loginError'));
  410. }
  411. // 如果用户已经有设置
  412. $setting=$userInfo['setting'] ?: '';
  413. if($setting){
  414. $setting['hideMessageName']= $setting['hideMessageName']=='true' ? true : false;
  415. $setting['hideMessageTime']= $setting['hideMessageTime']=='true' ? true : false;
  416. $setting['avatarCricle']= $setting['avatarCricle']=='true' ? true : false;
  417. $setting['isVoice']= $setting['isVoice']=='true' ? true : false;
  418. $setting['sendKey']= 1;//(int)$setting['sendKey'];
  419. }
  420. $userInfo['setting']=$setting;
  421. Gateway::$registerAddress = config('gateway.registerAddress');
  422. //如果登录信息中含有client——id则自动进行绑定
  423. if($client_id){
  424. $user_id=$userInfo['user_id'];
  425. // 如果当前ID在线,将其他地方登陆挤兑下线
  426. if(Gateway::isUidOnline($user_id)){
  427. wsSendMsg($user_id,'offline',['id'=>$user_id,'client_id'=>$client_id,'isMobile'=>false]);
  428. }
  429. Gateway::bindUid($client_id, $user_id);
  430. // 查询团队,如果有团队则加入团队
  431. $group=Group::getMyGroup(['gu.user_id'=>$user_id,'gu.status'=>1]);
  432. if($group){
  433. $group=$group->toArray();
  434. $group_ids=arrayToString($group,'group_id',false);
  435. foreach($group_ids as $v){
  436. Gateway::joinGroup($client_id, $v);
  437. }
  438. }
  439. }
  440. $update=[
  441. 'last_login_time'=>time(),
  442. 'last_login_ip'=>$this->request->ip(),
  443. 'login_count'=>Db::raw('login_count+1')
  444. ];
  445. User::where('user_id',$userInfo['user_id'])->update($update);
  446. $authToken=User::refreshToken($userInfo,'web');
  447. $data=[
  448. 'sessionId'=>Session::getId(),
  449. 'authToken'=>$authToken,
  450. 'userInfo'=>$userInfo
  451. ];
  452. Gateway::sendToClient($client_id, json_encode(array(
  453. 'type' => 'tokenLogin',
  454. 'data' => $data,
  455. )));
  456. return success(lang('user.loginOk'),$data);
  457. }
  458. // 搜索用户
  459. public function searchUser(){
  460. $keywords=$this->request->param('keywords','');
  461. if(!$keywords){
  462. return success('',[]);
  463. }
  464. $map=['status'=>1,'account'=>$keywords];
  465. $list=User::where($map)->field(User::$defaultField)->where([['account','<>',$this->userInfo['account']]])->select()->toArray();
  466. if($list){
  467. $ids=array_column($list,'user_id');
  468. $friendList=Friend::getFriend([['create_user','=',$this->uid],['friend_user_id','in',$ids]]);
  469. foreach($list as $k=>$v){
  470. $list[$k]['avatar']=avatarUrl($v['avatar'],$v['realname'],$v['user_id'],120);
  471. $list[$k]['friend']=$friendList[$v['user_id']] ?? '';
  472. }
  473. }
  474. return success('', $list);
  475. }
  476. // 获取系统所有人员加搜索
  477. public function userList(){
  478. $keywords=$this->request->param('keywords','');
  479. $listRows=$this->request->param('limit',20);
  480. $page=$this->request->param('page',1);
  481. $map=['status'=>1];
  482. $field="user_id,realname,avatar";
  483. if(!$keywords){
  484. $list=User::where($map)->field($field)->order('user_id asc')->limit(20)->paginate(['list_rows'=>$listRows,'page'=>$page]);;
  485. if($list){
  486. $list=$list->toArray()['data'];
  487. }
  488. }else{
  489. $list=User::where($map)->field($field)->where([['account','<>',$this->userInfo['account']]])->whereLike('account|realname|name_py','%'.$keywords.'%')->select()->toArray();
  490. }
  491. if($list){
  492. foreach($list as $k=>$v){
  493. $list[$k]['avatar']=avatarUrl($v['avatar'],$v['realname'],$v['user_id'],120);
  494. $list[$k]['id']=$v['user_id'];
  495. }
  496. }
  497. return success('', $list);
  498. }
  499. // 获取聊天记录
  500. public function getMessageList()
  501. {
  502. $param = $this->request->param();
  503. $is_group = isset($param['is_group']) ? $param['is_group'] : 0;
  504. // 如果toContactId是数字,绝对是单聊
  505. $is_group = is_numeric($param['toContactId']) ? 0 : $is_group;
  506. // 设置当前聊天消息为已读
  507. $chat_identify = $this->setIsRead($is_group, $param['toContactId']);
  508. $type = isset($param['type']) ? $param['type'] : '';
  509. $is_at = isset($param['is_at']) ? $param['is_at'] : '';
  510. $map = ['chat_identify' => $chat_identify, 'status' => 1];
  511. $where = [];
  512. if ($type && $type != "all") {
  513. $map['type'] = $type;
  514. } else {
  515. if (isset($param['type'])) {
  516. $where[] = ['type', '<>', 'event'];
  517. }
  518. }
  519. $groupManage=[];
  520. // 群聊查询入群时间以后的消息
  521. if($is_group==1){
  522. $group_id = explode('-', $param['toContactId'])[1];
  523. $group=Group::where(['group_id'=> $group_id])->find();
  524. $groupManage=GroupUser::getGroupManage($group_id);
  525. if($group && $group['setting']){
  526. $groupSetting=json_decode($group['setting'],true);
  527. $history=$groupSetting['history'] ?? false;
  528. // 如果开启了历史记录才可以查看所有记录,否者根据进群时间查询记录
  529. if(!$history){
  530. $createTime=GroupUser::where(['group_id'=> $group_id,'user_id'=>$this->userInfo['user_id']])->value('create_time');
  531. $where[] = ['create_time', '>=', $createTime ? : 0];
  532. }
  533. }
  534. }
  535. $keywords = isset($param['keywords']) ? $param['keywords'] : '';
  536. if ($keywords && in_array($type, ['text', 'all'])) {
  537. $where[] = ['content', 'like', '%' . $keywords . '%'];
  538. }
  539. // 如果是查询@数据
  540. if($is_at){
  541. $atList=Db::name('message')->where($map)->where($where)->whereFindInSet('at',$this->userInfo['user_id'])->order('msg_id desc')->select()->toArray();
  542. if($atList){
  543. $data = $this->recombileMsg($atList,false);
  544. Message::setAtread($data,$this->userInfo['user_id']);
  545. return success('', $data, count($data));
  546. }else{
  547. return success('', [], 0);
  548. }
  549. }
  550. $listRows = $param['limit'] ?: 20;
  551. $pageSize = $param['page'] ?: 1;
  552. $last_id = $param['last_id'] ?? 0;
  553. if($last_id){
  554. $where[]=['msg_id','<',$last_id];
  555. $pageSize=1;
  556. }
  557. //判断是客服还是用户
  558. if ($this->userInfo['role'] == 0) {
  559. //用户可见历史记录的时长
  560. $hours = Config::where('field', 'user_show_message')->value('val');
  561. if ($hours > 0) {
  562. $start_time = time() - $hours * 60 * 60;
  563. $where[] = ['create_time', '>=', $start_time];
  564. }
  565. } elseif ($this->userInfo['role'] > 0) {
  566. //客服可见历史记录的时长
  567. $hours = Config::where('field', 'kefu_show_message')->value('val');
  568. if ($hours > 0) {
  569. $start_time = time() - $hours * 60 * 60;
  570. $where[] = ['create_time', '>=', $start_time];
  571. }
  572. $auto_cs_uid = getAutoCsUid();//获取机器人ID
  573. $toUser = User::where('user_id', $param['toContactId'])->find();
  574. if ($toUser && $toUser->service_status == 1 && $toUser->cs_uid == $this->userInfo['user_id']) {
  575. //将用户待处理的状态更新成服务中
  576. $toUser->service_status = 2;
  577. $toUser->service_time = time();
  578. $toUser->save();
  579. //通知客服-会话服务中
  580. wsSendMsg(0,'handleChat',['user_id'=>$param['toContactId']]);
  581. } elseif ($toUser->cs_uid == $auto_cs_uid) {
  582. //如果当前用户归属到机器人,则修改查询条件
  583. $map['chat_identify'] = $auto_cs_uid.'-'.$param['toContactId'];
  584. }
  585. }
  586. $list = Message::getList($map, $where, 'msg_id desc', $listRows, $pageSize);
  587. $data = $this->recombileMsg($list,true,$groupManage);
  588. // 如果是群聊并且是第一页消息,需要推送@数据给用户
  589. if($param['is_group']==1 && $param['page']==1){
  590. $isPush=Cache::get('atMsgPush'.$chat_identify) ?? '';
  591. $atList=Db::name('message')->where(['chat_identify'=>$chat_identify,'is_group'=>1])->whereFindInSet('at',$this->userInfo['user_id'])->order('msg_id desc')->select()->toArray();
  592. $msgIda=array_column($atList,'msg_id');
  593. // 如果两次推送at数据的列表不一样,则推送
  594. if($isPush!=json_encode($msgIda)){
  595. $atData=$this->recombileMsg($atList,false);
  596. wsSendMsg($this->userInfo['user_id'],'atMsgList',[
  597. 'list'=>$atData,
  598. 'count'=>count($atData),
  599. 'toContactId'=>$param['toContactId']
  600. ]);
  601. Cache::set('atMsgPush'.$chat_identify,json_encode($msgIda),60);
  602. }
  603. }
  604. // 如果是消息管理器则不用倒序
  605. if (!isset($param['type'])) {
  606. $data = array_reverse($data);
  607. }
  608. return success('', $data, $list->total());
  609. }
  610. // 获取单条消息详情
  611. public function getMessageInfo()
  612. {
  613. $param = $this->request->param();
  614. $id = $param['msg_id'] ?? 0;
  615. $message = Message::where(['msg_id' => $id])->find();
  616. if ($message) {
  617. $data = $this->recombileMsg([$message], false);
  618. return success('', $data);
  619. } else {
  620. return warning(lang('im.exist'));
  621. }
  622. }
  623. // 获取单条消息上下文
  624. public function getMessageContext()
  625. {
  626. $param = $this->request->param();
  627. $is_group = isset($param['is_group']) ? $param['is_group'] : 0;
  628. $id = $param['msg_id'] ?? 0;
  629. $direction = $param['direction'] ?? 0;
  630. $message = Message::where(['msg_id' => $id])->find();
  631. if (!$message) {
  632. return warning(lang('im.exist'));
  633. }
  634. $groupManage=[];
  635. $where = [];
  636. $map = ['chat_identify' => $message['chat_identify'], 'status' => 1];
  637. if($is_group==1 && $direction<2){
  638. $group_id = $message['to_user'];
  639. $group=Group::where(['group_id'=> $group_id])->find();
  640. $groupManage=GroupUser::getGroupManage($group_id);
  641. if($group && $group['setting']){
  642. $groupSetting=json_decode($group['setting'],true);
  643. $history=$groupSetting['history'] ?? false;
  644. // 如果开启了历史记录才可以查看所有记录,否者根据进群时间查询记录
  645. if(!$history){
  646. $createTime=GroupUser::where(['group_id'=> $group_id,'user_id'=>$this->userInfo['user_id']])->value('create_time');
  647. $where[] = ['create_time', '>=', $createTime ? : 0];
  648. }
  649. }
  650. }
  651. if($direction==0){
  652. $where[] = ['msg_id', '<', $id];
  653. $beforeList = Message::where($map)->where($where)->order('msg_id desc')->limit(5)->select()->toArray();
  654. $beforeList = array_reverse($beforeList);
  655. $where2 = [];
  656. $where2[] = ['msg_id', '>=', $id];
  657. $afterList = Message::where($map)->where($where2)->order('msg_id asc')->limit(5)->select()->toArray();
  658. $data = array_merge($beforeList, $afterList);
  659. }elseif($direction==1){
  660. $where[] = ['msg_id', '<', $id];
  661. $data = Message::where($map)->where($where)->order('msg_id desc')->limit(5)->select()->toArray();
  662. $data = array_reverse($data);
  663. }else{
  664. $where[] = ['msg_id', '>', $id];
  665. $data = Message::where($map)->where($where)->order('msg_id asc')->limit(5)->select()->toArray();
  666. }
  667. if($data){
  668. $data = $this->recombileMsg($data, false,$groupManage);
  669. }
  670. return success('', $data);
  671. }
  672. protected function recombileMsg($list,$isPagination=true,$manage=[])
  673. {
  674. $data = [];
  675. $userInfo = $this->userInfo;
  676. if ($list) {
  677. $listData = $isPagination ? $list->toArray()['data'] : $list;
  678. $userList = User::matchUser($listData, true, 'from_user', 120);
  679. foreach ($listData as $k => $v) {
  680. // 屏蔽已删除的消息
  681. if ($v['del_user']) {
  682. $delUser = explode(',', $v['del_user']);
  683. if (in_array($userInfo['user_id'], $delUser)) {
  684. unset($list[$k]);
  685. continue;
  686. // $v['type']="event";
  687. // $v['content']="删除了一条消息";
  688. }
  689. }
  690. $content = str_encipher($v['content'],false);
  691. $preview = '';
  692. $ext='';
  693. if (in_array($v['type'], $this->fileType)) {
  694. $content = getFileUrl($content);
  695. $preview = previewUrl($content);
  696. $ext=getExtUrl($content);
  697. }
  698. $fromUser = $userList[$v['from_user']];
  699. // 处理撤回的消息
  700. if ($v['type'] == "event" && $v['is_undo']==1) {
  701. if ($v['from_user'] == $userInfo['user_id']) {
  702. $content = lang('im.you'). $content;
  703. } elseif ($v['is_group'] == 1) {
  704. $content = $fromUser['realname'] . $content;
  705. } else {
  706. $content = lang('im.other') . $content;
  707. }
  708. }
  709. $toContactId=$v['is_group'] ==1 ? 'group-'.$v['to_user'] : $v['to_user'];
  710. $atList=($v['at'] ?? null) ? explode(',',$v['at']): [];
  711. $role=$manage[$v['from_user']] ?? 3;
  712. $data[] = [
  713. 'msg_id' => $v['msg_id'],
  714. 'id' => $v['id'],
  715. 'status' => "succeed",
  716. 'type' => $v['type'],
  717. 'sendTime' => (is_string($v['create_time']) ? strtotime($v['create_time']) : $v['create_time'])* 1000,
  718. 'content' => $content,
  719. 'preview' => $preview,
  720. 'download' => $v['file_id'] ? getMainHost().'/filedown/'.encryptIds($v['file_id']) : '',
  721. 'is_read' => $v['is_read'],
  722. 'is_group' => $v['is_group'],
  723. 'at' => $atList,
  724. 'toContactId' => $toContactId,
  725. 'from_user' => $v['from_user'],
  726. 'file_id' => $v['file_id'],
  727. 'file_cate' => $v['file_cate'],
  728. 'fileName' => $v['file_name'],
  729. 'fileSize' => $v['file_size'],
  730. 'is_click' => $v['is_click'],
  731. 'fromUser' => $fromUser,
  732. 'extUrl'=>$ext,
  733. 'role'=>$role,
  734. 'extends'=>is_string($v['extends'])?json_decode($v['extends'],true) : $v['extends'],
  735. 'translate_content' => $v['translate_content'],
  736. 'language_code' => $v['language_code'],
  737. ];
  738. }
  739. }
  740. return $data;
  741. }
  742. // 设置当前窗口的消息默认为已读
  743. public function setMsgIsRead()
  744. {
  745. $param = $this->request->param();
  746. // 判断是否是一个二维数组
  747. if (is_array($param['messages'][0] ?? '')) {
  748. $messages=$param['messages'];
  749. } else {
  750. $messages=[$param['messages']];
  751. }
  752. $this->setIsRead($param['is_group'], $param['toContactId'],$messages);
  753. if (!$param['is_group']) {
  754. wsSendMsg($param['fromUser'], 'isRead', $messages, 0);
  755. }
  756. return success('');
  757. }
  758. // 设置全部为已读
  759. public function readAllMsg()
  760. {
  761. // 阅读所有单聊
  762. $map = ['to_user' => $this->userInfo['user_id'], 'is_read' => 0, 'is_group' => 0];
  763. Message::where($map)->update(['is_read' => 1]);
  764. // 阅读所有群聊
  765. GroupUser::where(['user_id' => $this->userInfo['user_id'], 'status' => 1])->update(['unread'=>0]);
  766. return success('');
  767. }
  768. // 设置消息已读
  769. protected function setIsRead($is_group, $to_user,$messages=[])
  770. {
  771. if ($is_group==1) {
  772. $chat_identify = $to_user;
  773. } else if($is_group==0) {
  774. $chat_identify = chat_identify($this->userInfo['user_id'], $to_user);
  775. } else if($is_group==2){
  776. $chat_identify = $to_user;
  777. }
  778. $data=[
  779. 'action'=>'setIsRead',
  780. 'is_group'=>$is_group,
  781. 'to_user'=>$to_user,
  782. 'messages'=>$messages,
  783. 'user_id'=>$this->userInfo['user_id']
  784. ];
  785. queuePush($data,3);
  786. return $chat_identify;
  787. }
  788. // 聊天设置
  789. public function setting()
  790. {
  791. $param = $this->request->param();
  792. if ($param) {
  793. User::where(['user_id' => $this->userInfo['user_id']])->update(['setting' => $param]);
  794. return success('');
  795. }
  796. return warning('');
  797. }
  798. // 撤回消息
  799. public function undoMessage()
  800. {
  801. // echo Lang::getLangSet();
  802. // echo \think\facade\Lang::get('ok');
  803. // echo \think\facade\Lang::get('im.other');
  804. // die;
  805. // Lang::clear();
  806. // $setRes = Lang::setLangSet('en');
  807. // dump('设置语言是否成功:', $setRes); // 应返回 true
  808. // dump('当前语言标识:', Lang::getLangSet()); // 应返回 en
  809. // dump('已加载的语言文件:', Lang::getLoadFiles()); // 应包含 en.php 路径
  810. // dump('im.other 值:', Lang::get('im.other')); // 看实际返回值
  811. // die;
  812. $param = $this->request->param();
  813. $id = $param['id'];
  814. $message = Message::where(['id' => $id])->find();
  815. if ($message) {
  816. // 如果时间超过了2分钟也不能撤回
  817. $createTime=is_string($message['create_time']) ? strtotime($message['create_time']) : $message['create_time'];
  818. $redoTime=$this->globalConfig['chatInfo']['redoTime'] ?? 120;
  819. if ($this->userInfo['role'] == 0 && $this->globalConfig['user_cancel_message'] && $this->globalConfig['user_cancel_message']) {
  820. $redoTime=$this->globalConfig['user_cancel_message_time'] * 60;
  821. } elseif ($this->userInfo['role'] != 0 && $this->globalConfig['kefu_cancel_message']) {
  822. $redoTime=$this->globalConfig['kefu_cancel_message'] * 60;
  823. }
  824. if(time()-$createTime>$redoTime && $message['is_group']==0){
  825. return warning(lang('im.redoLimitTime',['time'=>floor($redoTime/60)]));
  826. }
  827. $text = lang('im.redo');
  828. $fromUserName = lang('im.other');
  829. $toContactId = $message['to_user'];
  830. if ($message['is_group'] == 1) {
  831. $fromUserName = $this->userInfo['realname'];
  832. $toContactId = explode('-', $message['chat_identify'])[1];
  833. // 如果是群聊消息撤回,需要判断是否是群主或者管理员,如果是则可以撤回
  834. if($message['from_user']!=$this->userInfo['user_id']){
  835. $groupUser=GroupUser::where(['user_id'=>$this->userInfo['user_id'],'group_id'=>$toContactId])->find();
  836. if(!$groupUser || !in_array($groupUser['role'],[1,2])){
  837. return warning(lang('system.notAuth'));
  838. }
  839. $text=lang('im.manageRedo');
  840. }
  841. }
  842. $message->content = str_encipher($text);
  843. $message->type = 'event';
  844. $message->is_undo = 1;
  845. //@的数据清空
  846. $message->at = '';
  847. $message->save();
  848. $info = $message->toArray();
  849. // $data = $info;
  850. $data['content'] = $fromUserName . $text;
  851. $data['sendTime'] = $createTime * 1000;
  852. $data['id'] = $info['id'];
  853. $data['from_user'] = $info['from_user'];
  854. $data['msg_id'] = $info['msg_id'];
  855. $data['status'] = $info['status'];
  856. $data['type'] = 'event';
  857. $data['is_last'] = $info['is_last'];
  858. $data['toContactId'] = $message['is_group'] == 1 ? $info['chat_identify'] : $toContactId;
  859. $data['isMobile'] = $this->request->isMobile() ? 1 : 0;
  860. wsSendMsg($toContactId, 'undoMessage', $data, $info['is_group']);
  861. if($info['is_group']==0){
  862. // 给自己也发一份推送,多端同步
  863. $data['content'] =lang('im.you'). $text;
  864. wsSendMsg($this->userInfo['user_id'], 'undoMessage', $data, $info['is_group']);
  865. }
  866. return success('');
  867. } else {
  868. return warning();
  869. }
  870. }
  871. // 删除消息
  872. public function removeMessage()
  873. {
  874. $param = $this->request->param();
  875. $id = $param['id'];
  876. $map = ['id' => $id];
  877. $message = Message::where($map)->find();
  878. if ($message) {
  879. $message->del_user = $this->userInfo['user_id'];
  880. if ($message['is_group'] == 1) {
  881. if ($message['del_user']) {
  882. $message->del_user .= ',' . $this->userInfo['user_id'];
  883. }
  884. } else {
  885. if ($message['del_user'] > 0) {
  886. $message->where($map)->delete();
  887. return success(lang('system.delOk'));
  888. }
  889. }
  890. $message->save();
  891. return success('');
  892. } else {
  893. return warning('');
  894. }
  895. }
  896. // 消息免打扰
  897. public function isNotice()
  898. {
  899. $param = $this->request->param();
  900. $user_id = $this->userInfo['user_id'];
  901. $id = $param['id'];
  902. if ($param['is_group'] == 1) {
  903. $group_id = explode('-', $param['id'])[1];
  904. GroupUser::update(['is_notice' => $param['is_notice']], ['user_id' => $user_id, 'group_id' => $group_id]);
  905. } else {
  906. $map = ['create_user' => $user_id, 'friend_user_id' => $id];
  907. $friend = Friend::where($map)->find();
  908. try {
  909. if ($friend) {
  910. $friend->is_notice = $param['is_notice'];
  911. $friend->save();
  912. } else {
  913. $info = [
  914. 'create_user' => $user_id,
  915. 'friend_user_id' => $id,
  916. 'is_notice' => $param['is_notice']
  917. ];
  918. Friend::create($info);
  919. }
  920. return success('');
  921. } catch (Exception $e) {
  922. return error($e->getMessage());
  923. }
  924. }
  925. wsSendMsg($user_id,"setIsNotice",['id'=>$id,'is_notice'=>$param['is_notice'],'is_group'=>$param['is_group']]);
  926. return success('');
  927. }
  928. // 设置聊天置顶
  929. public function setChatTop()
  930. {
  931. $param = $this->request->param();
  932. $user_id = $this->userInfo['user_id'];
  933. $is_group = $param['is_group'] ?: 0;
  934. $id = $param['id'];
  935. try {
  936. if ($is_group == 1) {
  937. $group_id = explode('-', $param['id'])[1];
  938. GroupUser::update(['is_top' => $param['is_top']], ['user_id' => $user_id, 'group_id' => $group_id]);
  939. } else {
  940. $map = ['create_user' => $user_id, 'friend_user_id' => $id];
  941. $friend = Friend::where($map)->find();
  942. if ($friend) {
  943. $friend->is_top = $param['is_top'];
  944. $friend->save();
  945. } else {
  946. $info = [
  947. 'create_user' => $user_id,
  948. 'friend_user_id' => $id,
  949. 'is_top' => $param['is_top']
  950. ];
  951. Friend::create($info);
  952. }
  953. }
  954. wsSendMsg($user_id,"setChatTop",['id'=>$id,'is_top'=>$param['is_top'],'is_group'=>$is_group]);
  955. return success('');
  956. } catch (Exception $e) {
  957. return error($e->getMessage());
  958. }
  959. }
  960. // 删除聊天
  961. public function delChat()
  962. {
  963. $param = $this->request->param();
  964. $user_id = $this->userInfo['user_id'];
  965. $is_group = $param['is_group'] ?: 0;
  966. $id = $param['id'];
  967. $data=[
  968. 'user_id'=>$user_id,
  969. 'is_group'=>$is_group,
  970. 'to_user'=>$id
  971. ];
  972. ChatDelog::create($data);
  973. ChatDelog::updateCache($user_id);
  974. return success('');
  975. }
  976. // 向用户发送消息
  977. public function sendToMsg(){
  978. $param=$this->request->param();
  979. $toContactId=$param['toContactId'];
  980. $type=$param['type'];
  981. $status=$param['status'];
  982. $event=$param['event'] ?? 'calling';
  983. if($event=='calling'){
  984. $status=3;
  985. }
  986. $sdp=$param['sdp'] ?? '';
  987. $iceCandidate=$param['iceCandidate'] ?? '';
  988. $callTime=$param['callTime'] ?? '';
  989. $msg_id=$param['msg_id'] ?? '';
  990. $id=$param['id'] ?? '';
  991. $code=($param['code'] ?? '') ?: 901;
  992. // 如果该用户不在线,则发送忙线
  993. Gateway::$registerAddress = config('gateway.registerAddress');
  994. if(!Gateway::isUidOnline($toContactId)){
  995. $toContactId=$this->userInfo['user_id'];
  996. $code=907;
  997. $event='busy';
  998. sleep(1);
  999. }
  1000. switch($code){
  1001. case 902:
  1002. $content=lang('webRtc.cancel');
  1003. break;
  1004. case 903:
  1005. $content=lang('webRtc.refuse');
  1006. break;
  1007. case 905:
  1008. $content=lang('webRtc.notConnected');
  1009. break;
  1010. case 906:
  1011. $content=lang('webRtc.duration',['time'=>date("i:s",$callTime)]);
  1012. break;
  1013. case 907:
  1014. $content=lang('webRtc.busy');
  1015. break;
  1016. case 908:
  1017. $content=lang('webRtc.other');
  1018. break;
  1019. default:
  1020. $content=$type==1 ?lang('webRtc.video') : lang('webRtc.audio');
  1021. break;
  1022. }
  1023. switch($event){
  1024. case 'calling':
  1025. $content=$type==1 ?lang('webRtc.video'): lang('webRtc.audio');
  1026. break;
  1027. case 'acceptRtc':
  1028. $content=lang('webRtc.answer');
  1029. break;
  1030. case 'iceCandidate':
  1031. $content=lang('webRtc.exchange');
  1032. break;
  1033. }
  1034. $userInfo=$this->userInfo;
  1035. $userInfo['id']=$userInfo['user_id'];
  1036. $user = new User();
  1037. $data=[
  1038. 'id'=>$id,
  1039. 'msg_id'=>$msg_id,
  1040. 'sendTime'=>time()*1000,
  1041. 'toContactId'=>$toContactId,
  1042. 'content'=>$content,
  1043. 'type'=>'webrtc',
  1044. 'status'=>'succeed',
  1045. 'is_group'=>0,
  1046. 'is_read'=>0,
  1047. 'fromUser'=>$userInfo,
  1048. 'at'=>[],
  1049. 'extends'=>[
  1050. 'type'=>$type, //通话类型,1视频,0语音。
  1051. 'status'=>$status, //,1拨打方,2接听方
  1052. 'event'=>$event,
  1053. 'callTime'=>$callTime,
  1054. 'sdp'=>$sdp,
  1055. 'code'=>$code, //通话状态:呼叫901,取消902,拒绝903,接听904,未接通905,接通后挂断906,忙线907,其他端操作908
  1056. 'iceCandidate'=>$iceCandidate,
  1057. 'isMobile'=>$this->request->isMobile() ? 1 : 0,
  1058. ]
  1059. ];
  1060. if($event=='calling'){
  1061. $chat_identify=chat_identify($userInfo['id'],$toContactId);
  1062. $msg=[
  1063. 'from_user'=>$userInfo['id'],
  1064. 'to_user'=>$toContactId,
  1065. 'id'=>$id,
  1066. 'content'=>str_encipher($content),
  1067. 'chat_identify'=>$chat_identify,
  1068. 'create_time'=>time(),
  1069. 'type'=>$data['type'],
  1070. 'is_group'=>0,
  1071. 'is_read'=>0,
  1072. 'extends'=>$data['extends'],
  1073. ];
  1074. $message=new Message();
  1075. $message->update(['is_last'=>0],['chat_identify'=>$chat_identify]);
  1076. $message->save($msg);
  1077. $msg_id=$message->msg_id;
  1078. $data['msg_id']=$msg_id;
  1079. // 将接收人设置为发送人才能定位到该消息
  1080. $data['toContactId']=$userInfo['id'];
  1081. $data['toUser']=$toContactId;
  1082. }elseif($event=='hangup'){
  1083. $message=Message::where(['id'=>$id])->find();
  1084. if(!$message){
  1085. return error(lang('webRtc.fail'));
  1086. }
  1087. if($message){
  1088. $message->content=str_encipher($content);
  1089. $extends=$message->extends;
  1090. $extends['code']=$code;
  1091. $extends['callTime']=$callTime;
  1092. $message->extends=$extends;
  1093. $message->save();
  1094. }
  1095. }
  1096. wsSendMsg($toContactId,'webrtc',$data);
  1097. $wsData=$data;
  1098. if(in_array($event,['calling','acceptRtc','hangup'])){
  1099. if(in_array($event,['acceptRtc','hangup'])){
  1100. $data['extends']['event']='otherOpt'; //其他端操作
  1101. }
  1102. $data['toContactId']=$toContactId;
  1103. $data['contactInfo']=$user->setContact($toContactId,0,'webrtc',$content) ? : [];
  1104. wsSendMsg($userInfo['id'],'webrtc',$data);
  1105. }
  1106. return success('',$wsData);
  1107. }
  1108. // 修改密码
  1109. public function editPassword()
  1110. {
  1111. if(env('app.demon_mode',false)){
  1112. return warning(lang('system.demoMode'));
  1113. }
  1114. $user_id = $this->userInfo['user_id'];
  1115. $user=User::find($user_id);
  1116. if(!$user){
  1117. return warning(lang('user.exist'));
  1118. }
  1119. $account=$user->account;
  1120. $code=$this->request->param('code','');
  1121. $originalPassword = $this->request->param('originalPassword', '');
  1122. if($code){
  1123. if(Cache::get($account)!=$code){
  1124. return warning(lang('user.codeErr'));
  1125. }
  1126. }elseif($originalPassword){
  1127. if(password_hash_tp($originalPassword,$user->salt)!= $user->password){
  1128. return warning(lang('user.passErr'));
  1129. }
  1130. }else{
  1131. return warning(lang('system.parameterError'));
  1132. }
  1133. try{
  1134. $password = $this->request->param('password','');
  1135. if($password){
  1136. $salt=$user->salt;
  1137. $user->password= password_hash_tp($password,$salt);
  1138. }
  1139. $user->save();
  1140. return success(lang('system.editOk'));
  1141. }catch (\Exception $e){
  1142. return error(lang('system.editFail'));
  1143. }
  1144. }
  1145. // 修改用户信息
  1146. public function updateUserInfo(){
  1147. try{
  1148. $data = $this->request->param();
  1149. $user=User::find($this->uid);
  1150. if(!$user){
  1151. return warning(lang('user.exist'));
  1152. }
  1153. // 接入用户名检测服务
  1154. event('GreenText',['content'=>$data['realname'],'service'=>"nickname_detection"]);
  1155. // 个性签名检测服务
  1156. event('GreenText',['content'=>$data['motto'],'service'=>"comment_detection"]);
  1157. $user->realname =$data['realname'];
  1158. $user->email =$data['email'];
  1159. $user->motto=$data['motto'];
  1160. $user->sex =$data['sex'];
  1161. $user->name_py= pinyin_sentence($data['realname']);
  1162. $user->save();
  1163. return success(lang('system.editOk'), $data);
  1164. }catch (\Exception $e){
  1165. return error($e->getMessage());
  1166. }
  1167. }
  1168. // 修改账户
  1169. public function editAccount(){
  1170. if(env('app.demon_mode',false)){
  1171. return warning(lang('system.demoMode'));
  1172. }
  1173. $code=$this->request->param('code','');
  1174. $newCode=$this->request->param('newCode','');
  1175. $account=$this->request->param('account','');
  1176. $isUser=User::where('account',$account)->find();
  1177. if($isUser){
  1178. return warning(lang('user.already'));
  1179. }
  1180. $user=User::find($this->uid);
  1181. if(!$user){
  1182. return warning(lang('user.exist'));
  1183. }
  1184. // 如果已经认证过了,则需要验证验证码
  1185. if($user->is_auth){
  1186. if(Cache::get($user->account)!=$code){
  1187. return warning(lang('user.codeErr'));
  1188. }
  1189. }
  1190. if(Cache::get($account)!=$newCode){
  1191. return warning(lang('user.newCodeErr'));
  1192. }
  1193. try{
  1194. $user->account=$account;
  1195. $user->is_auth=1;
  1196. $user->save();
  1197. return success(lang('system.editOk'));
  1198. }catch (\Exception $e){
  1199. return error(lang('system.editFail'));
  1200. }
  1201. }
  1202. // 阅读@消息
  1203. public function readAtMsg(){
  1204. $param = $this->request->param();
  1205. $atList=Db::name('message')->where(['chat_identify'=>$param['toContactId'],'is_group'=>1])->whereFindInSet('at',$this->userInfo['user_id'])->order('msg_id desc')->select();
  1206. $atData=$this->recombileMsg($atList,false);
  1207. Message::setAtRead($atData,$this->userInfo['user_id']);
  1208. // $message=Message::where('msg_id',$param['msg_id'])->select();
  1209. // $atList=($message ?? null) ? explode(',',$message): [];
  1210. // // 两个数组取差集
  1211. // $newAtList = array_diff($atList, [$this->userInfo['user_id']]);
  1212. // Message::where('msg_id',$param['msg_id'])->update(['at'=>implode(',',$newAtList)]);
  1213. return success('');
  1214. }
  1215. // 获取系统公告
  1216. public function getAdminNotice(){
  1217. $data=Message::where(['chat_identify'=>'admin_notice'])->order('msg_id desc')->find();
  1218. $extends=$data['extends'] ?? [];
  1219. if(!$extends){
  1220. $extends['title']='';
  1221. }
  1222. $createTime=$data['create_time'] ?? 0;
  1223. if(!$createTime){
  1224. $extends['create_time']=$createTime;
  1225. }else{
  1226. $extends['create_time']=is_string($data['create_time']) ? strtotime($data['create_time']) : $data['create_time'];
  1227. }
  1228. return success('',$extends);
  1229. }
  1230. // 双向删除消息
  1231. public function delMessage(){
  1232. $param = $this->request->param();
  1233. $id = $param['id'];
  1234. // if(!$this->globalConfig['chatInfo']['dbDelMsg']){
  1235. // return warning(lang('system.notAuth'));
  1236. // }
  1237. $message = Message::where(['id' => $id])->find();
  1238. if ($message) {
  1239. if($message['from_user']!=$this->userInfo['user_id']){
  1240. return warning(lang('system.notAuth'));
  1241. }
  1242. Message::where(['id' => $id])->delete();
  1243. // 如果是最后一条消息,需要将上一条设置为最后一条
  1244. if($message['is_last']){
  1245. Message::where(['chat_identify'=>$message['chat_identify']])->order('msg_id desc')->limit(1)->update(['is_last'=>1]);
  1246. }
  1247. $toContactId = $message['to_user'];
  1248. if ($message['is_group'] == 1) {
  1249. $toContactId = explode('-', $message['chat_identify'])[1];
  1250. }
  1251. wsSendMsg($toContactId, 'delMessage', $message, $message['is_group']);
  1252. return success('');
  1253. } else {
  1254. return warning(lang('im.exist'));
  1255. }
  1256. }
  1257. }