Im.php 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323
  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. $toUser = User::where('user_id', $param['toContactId'])->find();
  573. if ($toUser && $toUser->service_status == 1 && $toUser->cs_uid == $this->userInfo['user_id']) {
  574. //将用户待处理的状态更新成服务中
  575. $toUser->service_status = 2;
  576. $toUser->service_time = time();
  577. $toUser->save();
  578. //通知客服-会话服务中
  579. wsSendMsg(0,'handleChat',['user_id'=>$param['toContactId']]);
  580. } else {
  581. $map['chat_identify'] = $toUser->cs_uid.'-'.$param['toContactId'];
  582. }
  583. }
  584. $list = Message::getList($map, $where, 'msg_id desc', $listRows, $pageSize);
  585. $data = $this->recombileMsg($list,true,$groupManage);
  586. // 如果是群聊并且是第一页消息,需要推送@数据给用户
  587. if($param['is_group']==1 && $param['page']==1){
  588. $isPush=Cache::get('atMsgPush'.$chat_identify) ?? '';
  589. $atList=Db::name('message')->where(['chat_identify'=>$chat_identify,'is_group'=>1])->whereFindInSet('at',$this->userInfo['user_id'])->order('msg_id desc')->select()->toArray();
  590. $msgIda=array_column($atList,'msg_id');
  591. // 如果两次推送at数据的列表不一样,则推送
  592. if($isPush!=json_encode($msgIda)){
  593. $atData=$this->recombileMsg($atList,false);
  594. wsSendMsg($this->userInfo['user_id'],'atMsgList',[
  595. 'list'=>$atData,
  596. 'count'=>count($atData),
  597. 'toContactId'=>$param['toContactId']
  598. ]);
  599. Cache::set('atMsgPush'.$chat_identify,json_encode($msgIda),60);
  600. }
  601. }
  602. // 如果是消息管理器则不用倒序
  603. if (!isset($param['type'])) {
  604. $data = array_reverse($data);
  605. }
  606. return success('', $data, $list->total());
  607. }
  608. // 获取单条消息详情
  609. public function getMessageInfo()
  610. {
  611. $param = $this->request->param();
  612. $id = $param['msg_id'] ?? 0;
  613. $message = Message::where(['msg_id' => $id])->find();
  614. if ($message) {
  615. $data = $this->recombileMsg([$message], false);
  616. return success('', $data);
  617. } else {
  618. return warning(lang('im.exist'));
  619. }
  620. }
  621. // 获取单条消息上下文
  622. public function getMessageContext()
  623. {
  624. $param = $this->request->param();
  625. $is_group = isset($param['is_group']) ? $param['is_group'] : 0;
  626. $id = $param['msg_id'] ?? 0;
  627. $direction = $param['direction'] ?? 0;
  628. $message = Message::where(['msg_id' => $id])->find();
  629. if (!$message) {
  630. return warning(lang('im.exist'));
  631. }
  632. $groupManage=[];
  633. $where = [];
  634. $map = ['chat_identify' => $message['chat_identify'], 'status' => 1];
  635. if($is_group==1 && $direction<2){
  636. $group_id = $message['to_user'];
  637. $group=Group::where(['group_id'=> $group_id])->find();
  638. $groupManage=GroupUser::getGroupManage($group_id);
  639. if($group && $group['setting']){
  640. $groupSetting=json_decode($group['setting'],true);
  641. $history=$groupSetting['history'] ?? false;
  642. // 如果开启了历史记录才可以查看所有记录,否者根据进群时间查询记录
  643. if(!$history){
  644. $createTime=GroupUser::where(['group_id'=> $group_id,'user_id'=>$this->userInfo['user_id']])->value('create_time');
  645. $where[] = ['create_time', '>=', $createTime ? : 0];
  646. }
  647. }
  648. }
  649. if($direction==0){
  650. $where[] = ['msg_id', '<', $id];
  651. $beforeList = Message::where($map)->where($where)->order('msg_id desc')->limit(5)->select()->toArray();
  652. $beforeList = array_reverse($beforeList);
  653. $where2 = [];
  654. $where2[] = ['msg_id', '>=', $id];
  655. $afterList = Message::where($map)->where($where2)->order('msg_id asc')->limit(5)->select()->toArray();
  656. $data = array_merge($beforeList, $afterList);
  657. }elseif($direction==1){
  658. $where[] = ['msg_id', '<', $id];
  659. $data = Message::where($map)->where($where)->order('msg_id desc')->limit(5)->select()->toArray();
  660. $data = array_reverse($data);
  661. }else{
  662. $where[] = ['msg_id', '>', $id];
  663. $data = Message::where($map)->where($where)->order('msg_id asc')->limit(5)->select()->toArray();
  664. }
  665. if($data){
  666. $data = $this->recombileMsg($data, false,$groupManage);
  667. }
  668. return success('', $data);
  669. }
  670. protected function recombileMsg($list,$isPagination=true,$manage=[])
  671. {
  672. $data = [];
  673. $userInfo = $this->userInfo;
  674. if ($list) {
  675. $listData = $isPagination ? $list->toArray()['data'] : $list;
  676. $userList = User::matchUser($listData, true, 'from_user', 120);
  677. foreach ($listData as $k => $v) {
  678. // 屏蔽已删除的消息
  679. if ($v['del_user']) {
  680. $delUser = explode(',', $v['del_user']);
  681. if (in_array($userInfo['user_id'], $delUser)) {
  682. unset($list[$k]);
  683. continue;
  684. // $v['type']="event";
  685. // $v['content']="删除了一条消息";
  686. }
  687. }
  688. $content = str_encipher($v['content'],false);
  689. $preview = '';
  690. $ext='';
  691. if (in_array($v['type'], $this->fileType)) {
  692. $content = getFileUrl($content);
  693. $preview = previewUrl($content);
  694. $ext=getExtUrl($content);
  695. }
  696. $fromUser = $userList[$v['from_user']];
  697. // 处理撤回的消息
  698. if ($v['type'] == "event" && $v['is_undo']==1) {
  699. if ($v['from_user'] == $userInfo['user_id']) {
  700. $content = lang('im.you'). $content;
  701. } elseif ($v['is_group'] == 1) {
  702. $content = $fromUser['realname'] . $content;
  703. } else {
  704. $content = lang('im.other') . $content;
  705. }
  706. }
  707. $toContactId=$v['is_group'] ==1 ? 'group-'.$v['to_user'] : $v['to_user'];
  708. $atList=($v['at'] ?? null) ? explode(',',$v['at']): [];
  709. $role=$manage[$v['from_user']] ?? 3;
  710. $data[] = [
  711. 'msg_id' => $v['msg_id'],
  712. 'id' => $v['id'],
  713. 'status' => "succeed",
  714. 'type' => $v['type'],
  715. 'sendTime' => (is_string($v['create_time']) ? strtotime($v['create_time']) : $v['create_time'])* 1000,
  716. 'content' => $content,
  717. 'preview' => $preview,
  718. 'download' => $v['file_id'] ? getMainHost().'/filedown/'.encryptIds($v['file_id']) : '',
  719. 'is_read' => $v['is_read'],
  720. 'is_group' => $v['is_group'],
  721. 'at' => $atList,
  722. 'toContactId' => $toContactId,
  723. 'from_user' => $v['from_user'],
  724. 'file_id' => $v['file_id'],
  725. 'file_cate' => $v['file_cate'],
  726. 'fileName' => $v['file_name'],
  727. 'fileSize' => $v['file_size'],
  728. 'is_click' => $v['is_click'],
  729. 'fromUser' => $fromUser,
  730. 'extUrl'=>$ext,
  731. 'role'=>$role,
  732. 'extends'=>is_string($v['extends'])?json_decode($v['extends'],true) : $v['extends'],
  733. 'translate_content' => $v['translate_content'],
  734. 'language_code' => $v['language_code'],
  735. ];
  736. }
  737. }
  738. return $data;
  739. }
  740. // 设置当前窗口的消息默认为已读
  741. public function setMsgIsRead()
  742. {
  743. $param = $this->request->param();
  744. // 判断是否是一个二维数组
  745. if (is_array($param['messages'][0] ?? '')) {
  746. $messages=$param['messages'];
  747. } else {
  748. $messages=[$param['messages']];
  749. }
  750. $this->setIsRead($param['is_group'], $param['toContactId'],$messages);
  751. if (!$param['is_group']) {
  752. wsSendMsg($param['fromUser'], 'isRead', $messages, 0);
  753. }
  754. return success('');
  755. }
  756. // 设置全部为已读
  757. public function readAllMsg()
  758. {
  759. // 阅读所有单聊
  760. $map = ['to_user' => $this->userInfo['user_id'], 'is_read' => 0, 'is_group' => 0];
  761. Message::where($map)->update(['is_read' => 1]);
  762. // 阅读所有群聊
  763. GroupUser::where(['user_id' => $this->userInfo['user_id'], 'status' => 1])->update(['unread'=>0]);
  764. return success('');
  765. }
  766. // 设置消息已读
  767. protected function setIsRead($is_group, $to_user,$messages=[])
  768. {
  769. if ($is_group==1) {
  770. $chat_identify = $to_user;
  771. } else if($is_group==0) {
  772. $chat_identify = chat_identify($this->userInfo['user_id'], $to_user);
  773. } else if($is_group==2){
  774. $chat_identify = $to_user;
  775. }
  776. $data=[
  777. 'action'=>'setIsRead',
  778. 'is_group'=>$is_group,
  779. 'to_user'=>$to_user,
  780. 'messages'=>$messages,
  781. 'user_id'=>$this->userInfo['user_id']
  782. ];
  783. queuePush($data,3);
  784. return $chat_identify;
  785. }
  786. // 聊天设置
  787. public function setting()
  788. {
  789. $param = $this->request->param();
  790. if ($param) {
  791. User::where(['user_id' => $this->userInfo['user_id']])->update(['setting' => $param]);
  792. return success('');
  793. }
  794. return warning('');
  795. }
  796. // 撤回消息
  797. public function undoMessage()
  798. {
  799. // echo Lang::getLangSet();
  800. // echo \think\facade\Lang::get('ok');
  801. // echo \think\facade\Lang::get('im.other');
  802. // die;
  803. // Lang::clear();
  804. // $setRes = Lang::setLangSet('en');
  805. // dump('设置语言是否成功:', $setRes); // 应返回 true
  806. // dump('当前语言标识:', Lang::getLangSet()); // 应返回 en
  807. // dump('已加载的语言文件:', Lang::getLoadFiles()); // 应包含 en.php 路径
  808. // dump('im.other 值:', Lang::get('im.other')); // 看实际返回值
  809. // die;
  810. $param = $this->request->param();
  811. $id = $param['id'];
  812. $message = Message::where(['id' => $id])->find();
  813. if ($message) {
  814. // 如果时间超过了2分钟也不能撤回
  815. $createTime=is_string($message['create_time']) ? strtotime($message['create_time']) : $message['create_time'];
  816. $redoTime=$this->globalConfig['chatInfo']['redoTime'] ?? 120;
  817. if ($this->userInfo['role'] == 0 && $this->globalConfig['user_cancel_message'] && $this->globalConfig['user_cancel_message']) {
  818. $redoTime=$this->globalConfig['user_cancel_message_time'] * 60;
  819. } elseif ($this->userInfo['role'] != 0 && $this->globalConfig['kefu_cancel_message']) {
  820. $redoTime=$this->globalConfig['kefu_cancel_message'] * 60;
  821. }
  822. if(time()-$createTime>$redoTime && $message['is_group']==0){
  823. return warning(lang('im.redoLimitTime',['time'=>floor($redoTime/60)]));
  824. }
  825. $text = lang('im.redo');
  826. $fromUserName = lang('im.other');
  827. $toContactId = $message['to_user'];
  828. if ($message['is_group'] == 1) {
  829. $fromUserName = $this->userInfo['realname'];
  830. $toContactId = explode('-', $message['chat_identify'])[1];
  831. // 如果是群聊消息撤回,需要判断是否是群主或者管理员,如果是则可以撤回
  832. if($message['from_user']!=$this->userInfo['user_id']){
  833. $groupUser=GroupUser::where(['user_id'=>$this->userInfo['user_id'],'group_id'=>$toContactId])->find();
  834. if(!$groupUser || !in_array($groupUser['role'],[1,2])){
  835. return warning(lang('system.notAuth'));
  836. }
  837. $text=lang('im.manageRedo');
  838. }
  839. }
  840. $message->content = str_encipher($text);
  841. $message->type = 'event';
  842. $message->is_undo = 1;
  843. //@的数据清空
  844. $message->at = '';
  845. $message->save();
  846. $info = $message->toArray();
  847. // $data = $info;
  848. $data['content'] = $fromUserName . $text;
  849. $data['sendTime'] = $createTime * 1000;
  850. $data['id'] = $info['id'];
  851. $data['from_user'] = $info['from_user'];
  852. $data['msg_id'] = $info['msg_id'];
  853. $data['status'] = $info['status'];
  854. $data['type'] = 'event';
  855. $data['is_last'] = $info['is_last'];
  856. $data['toContactId'] = $message['is_group'] == 1 ? $info['chat_identify'] : $toContactId;
  857. $data['isMobile'] = $this->request->isMobile() ? 1 : 0;
  858. wsSendMsg($toContactId, 'undoMessage', $data, $info['is_group']);
  859. if($info['is_group']==0){
  860. // 给自己也发一份推送,多端同步
  861. $data['content'] =lang('im.you'). $text;
  862. wsSendMsg($this->userInfo['user_id'], 'undoMessage', $data, $info['is_group']);
  863. }
  864. return success('');
  865. } else {
  866. return warning();
  867. }
  868. }
  869. // 删除消息
  870. public function removeMessage()
  871. {
  872. $param = $this->request->param();
  873. $id = $param['id'];
  874. $map = ['id' => $id];
  875. $message = Message::where($map)->find();
  876. if ($message) {
  877. $message->del_user = $this->userInfo['user_id'];
  878. if ($message['is_group'] == 1) {
  879. if ($message['del_user']) {
  880. $message->del_user .= ',' . $this->userInfo['user_id'];
  881. }
  882. } else {
  883. if ($message['del_user'] > 0) {
  884. $message->where($map)->delete();
  885. return success(lang('system.delOk'));
  886. }
  887. }
  888. $message->save();
  889. return success('');
  890. } else {
  891. return warning('');
  892. }
  893. }
  894. // 消息免打扰
  895. public function isNotice()
  896. {
  897. $param = $this->request->param();
  898. $user_id = $this->userInfo['user_id'];
  899. $id = $param['id'];
  900. if ($param['is_group'] == 1) {
  901. $group_id = explode('-', $param['id'])[1];
  902. GroupUser::update(['is_notice' => $param['is_notice']], ['user_id' => $user_id, 'group_id' => $group_id]);
  903. } else {
  904. $map = ['create_user' => $user_id, 'friend_user_id' => $id];
  905. $friend = Friend::where($map)->find();
  906. try {
  907. if ($friend) {
  908. $friend->is_notice = $param['is_notice'];
  909. $friend->save();
  910. } else {
  911. $info = [
  912. 'create_user' => $user_id,
  913. 'friend_user_id' => $id,
  914. 'is_notice' => $param['is_notice']
  915. ];
  916. Friend::create($info);
  917. }
  918. return success('');
  919. } catch (Exception $e) {
  920. return error($e->getMessage());
  921. }
  922. }
  923. wsSendMsg($user_id,"setIsNotice",['id'=>$id,'is_notice'=>$param['is_notice'],'is_group'=>$param['is_group']]);
  924. return success('');
  925. }
  926. // 设置聊天置顶
  927. public function setChatTop()
  928. {
  929. $param = $this->request->param();
  930. $user_id = $this->userInfo['user_id'];
  931. $is_group = $param['is_group'] ?: 0;
  932. $id = $param['id'];
  933. try {
  934. if ($is_group == 1) {
  935. $group_id = explode('-', $param['id'])[1];
  936. GroupUser::update(['is_top' => $param['is_top']], ['user_id' => $user_id, 'group_id' => $group_id]);
  937. } else {
  938. $map = ['create_user' => $user_id, 'friend_user_id' => $id];
  939. $friend = Friend::where($map)->find();
  940. if ($friend) {
  941. $friend->is_top = $param['is_top'];
  942. $friend->save();
  943. } else {
  944. $info = [
  945. 'create_user' => $user_id,
  946. 'friend_user_id' => $id,
  947. 'is_top' => $param['is_top']
  948. ];
  949. Friend::create($info);
  950. }
  951. }
  952. wsSendMsg($user_id,"setChatTop",['id'=>$id,'is_top'=>$param['is_top'],'is_group'=>$is_group]);
  953. return success('');
  954. } catch (Exception $e) {
  955. return error($e->getMessage());
  956. }
  957. }
  958. // 删除聊天
  959. public function delChat()
  960. {
  961. $param = $this->request->param();
  962. $user_id = $this->userInfo['user_id'];
  963. $is_group = $param['is_group'] ?: 0;
  964. $id = $param['id'];
  965. $data=[
  966. 'user_id'=>$user_id,
  967. 'is_group'=>$is_group,
  968. 'to_user'=>$id
  969. ];
  970. ChatDelog::create($data);
  971. ChatDelog::updateCache($user_id);
  972. return success('');
  973. }
  974. // 向用户发送消息
  975. public function sendToMsg(){
  976. $param=$this->request->param();
  977. $toContactId=$param['toContactId'];
  978. $type=$param['type'];
  979. $status=$param['status'];
  980. $event=$param['event'] ?? 'calling';
  981. if($event=='calling'){
  982. $status=3;
  983. }
  984. $sdp=$param['sdp'] ?? '';
  985. $iceCandidate=$param['iceCandidate'] ?? '';
  986. $callTime=$param['callTime'] ?? '';
  987. $msg_id=$param['msg_id'] ?? '';
  988. $id=$param['id'] ?? '';
  989. $code=($param['code'] ?? '') ?: 901;
  990. // 如果该用户不在线,则发送忙线
  991. Gateway::$registerAddress = config('gateway.registerAddress');
  992. if(!Gateway::isUidOnline($toContactId)){
  993. $toContactId=$this->userInfo['user_id'];
  994. $code=907;
  995. $event='busy';
  996. sleep(1);
  997. }
  998. switch($code){
  999. case 902:
  1000. $content=lang('webRtc.cancel');
  1001. break;
  1002. case 903:
  1003. $content=lang('webRtc.refuse');
  1004. break;
  1005. case 905:
  1006. $content=lang('webRtc.notConnected');
  1007. break;
  1008. case 906:
  1009. $content=lang('webRtc.duration',['time'=>date("i:s",$callTime)]);
  1010. break;
  1011. case 907:
  1012. $content=lang('webRtc.busy');
  1013. break;
  1014. case 908:
  1015. $content=lang('webRtc.other');
  1016. break;
  1017. default:
  1018. $content=$type==1 ?lang('webRtc.video') : lang('webRtc.audio');
  1019. break;
  1020. }
  1021. switch($event){
  1022. case 'calling':
  1023. $content=$type==1 ?lang('webRtc.video'): lang('webRtc.audio');
  1024. break;
  1025. case 'acceptRtc':
  1026. $content=lang('webRtc.answer');
  1027. break;
  1028. case 'iceCandidate':
  1029. $content=lang('webRtc.exchange');
  1030. break;
  1031. }
  1032. $userInfo=$this->userInfo;
  1033. $userInfo['id']=$userInfo['user_id'];
  1034. $user = new User();
  1035. $data=[
  1036. 'id'=>$id,
  1037. 'msg_id'=>$msg_id,
  1038. 'sendTime'=>time()*1000,
  1039. 'toContactId'=>$toContactId,
  1040. 'content'=>$content,
  1041. 'type'=>'webrtc',
  1042. 'status'=>'succeed',
  1043. 'is_group'=>0,
  1044. 'is_read'=>0,
  1045. 'fromUser'=>$userInfo,
  1046. 'at'=>[],
  1047. 'extends'=>[
  1048. 'type'=>$type, //通话类型,1视频,0语音。
  1049. 'status'=>$status, //,1拨打方,2接听方
  1050. 'event'=>$event,
  1051. 'callTime'=>$callTime,
  1052. 'sdp'=>$sdp,
  1053. 'code'=>$code, //通话状态:呼叫901,取消902,拒绝903,接听904,未接通905,接通后挂断906,忙线907,其他端操作908
  1054. 'iceCandidate'=>$iceCandidate,
  1055. 'isMobile'=>$this->request->isMobile() ? 1 : 0,
  1056. ]
  1057. ];
  1058. if($event=='calling'){
  1059. $chat_identify=chat_identify($userInfo['id'],$toContactId);
  1060. $msg=[
  1061. 'from_user'=>$userInfo['id'],
  1062. 'to_user'=>$toContactId,
  1063. 'id'=>$id,
  1064. 'content'=>str_encipher($content),
  1065. 'chat_identify'=>$chat_identify,
  1066. 'create_time'=>time(),
  1067. 'type'=>$data['type'],
  1068. 'is_group'=>0,
  1069. 'is_read'=>0,
  1070. 'extends'=>$data['extends'],
  1071. ];
  1072. $message=new Message();
  1073. $message->update(['is_last'=>0],['chat_identify'=>$chat_identify]);
  1074. $message->save($msg);
  1075. $msg_id=$message->msg_id;
  1076. $data['msg_id']=$msg_id;
  1077. // 将接收人设置为发送人才能定位到该消息
  1078. $data['toContactId']=$userInfo['id'];
  1079. $data['toUser']=$toContactId;
  1080. }elseif($event=='hangup'){
  1081. $message=Message::where(['id'=>$id])->find();
  1082. if(!$message){
  1083. return error(lang('webRtc.fail'));
  1084. }
  1085. if($message){
  1086. $message->content=str_encipher($content);
  1087. $extends=$message->extends;
  1088. $extends['code']=$code;
  1089. $extends['callTime']=$callTime;
  1090. $message->extends=$extends;
  1091. $message->save();
  1092. }
  1093. }
  1094. wsSendMsg($toContactId,'webrtc',$data);
  1095. $wsData=$data;
  1096. if(in_array($event,['calling','acceptRtc','hangup'])){
  1097. if(in_array($event,['acceptRtc','hangup'])){
  1098. $data['extends']['event']='otherOpt'; //其他端操作
  1099. }
  1100. $data['toContactId']=$toContactId;
  1101. $data['contactInfo']=$user->setContact($toContactId,0,'webrtc',$content) ? : [];
  1102. wsSendMsg($userInfo['id'],'webrtc',$data);
  1103. }
  1104. return success('',$wsData);
  1105. }
  1106. // 修改密码
  1107. public function editPassword()
  1108. {
  1109. if(env('app.demon_mode',false)){
  1110. return warning(lang('system.demoMode'));
  1111. }
  1112. $user_id = $this->userInfo['user_id'];
  1113. $user=User::find($user_id);
  1114. if(!$user){
  1115. return warning(lang('user.exist'));
  1116. }
  1117. $account=$user->account;
  1118. $code=$this->request->param('code','');
  1119. $originalPassword = $this->request->param('originalPassword', '');
  1120. if($code){
  1121. if(Cache::get($account)!=$code){
  1122. return warning(lang('user.codeErr'));
  1123. }
  1124. }elseif($originalPassword){
  1125. if(password_hash_tp($originalPassword,$user->salt)!= $user->password){
  1126. return warning(lang('user.passErr'));
  1127. }
  1128. }else{
  1129. return warning(lang('system.parameterError'));
  1130. }
  1131. try{
  1132. $password = $this->request->param('password','');
  1133. if($password){
  1134. $salt=$user->salt;
  1135. $user->password= password_hash_tp($password,$salt);
  1136. }
  1137. $user->save();
  1138. return success(lang('system.editOk'));
  1139. }catch (\Exception $e){
  1140. return error(lang('system.editFail'));
  1141. }
  1142. }
  1143. // 修改用户信息
  1144. public function updateUserInfo(){
  1145. try{
  1146. $data = $this->request->param();
  1147. $user=User::find($this->uid);
  1148. if(!$user){
  1149. return warning(lang('user.exist'));
  1150. }
  1151. // 接入用户名检测服务
  1152. event('GreenText',['content'=>$data['realname'],'service'=>"nickname_detection"]);
  1153. // 个性签名检测服务
  1154. event('GreenText',['content'=>$data['motto'],'service'=>"comment_detection"]);
  1155. $user->realname =$data['realname'];
  1156. $user->email =$data['email'];
  1157. $user->motto=$data['motto'];
  1158. $user->sex =$data['sex'];
  1159. $user->name_py= pinyin_sentence($data['realname']);
  1160. $user->save();
  1161. return success(lang('system.editOk'), $data);
  1162. }catch (\Exception $e){
  1163. return error($e->getMessage());
  1164. }
  1165. }
  1166. // 修改账户
  1167. public function editAccount(){
  1168. if(env('app.demon_mode',false)){
  1169. return warning(lang('system.demoMode'));
  1170. }
  1171. $code=$this->request->param('code','');
  1172. $newCode=$this->request->param('newCode','');
  1173. $account=$this->request->param('account','');
  1174. $isUser=User::where('account',$account)->find();
  1175. if($isUser){
  1176. return warning(lang('user.already'));
  1177. }
  1178. $user=User::find($this->uid);
  1179. if(!$user){
  1180. return warning(lang('user.exist'));
  1181. }
  1182. // 如果已经认证过了,则需要验证验证码
  1183. if($user->is_auth){
  1184. if(Cache::get($user->account)!=$code){
  1185. return warning(lang('user.codeErr'));
  1186. }
  1187. }
  1188. if(Cache::get($account)!=$newCode){
  1189. return warning(lang('user.newCodeErr'));
  1190. }
  1191. try{
  1192. $user->account=$account;
  1193. $user->is_auth=1;
  1194. $user->save();
  1195. return success(lang('system.editOk'));
  1196. }catch (\Exception $e){
  1197. return error(lang('system.editFail'));
  1198. }
  1199. }
  1200. // 阅读@消息
  1201. public function readAtMsg(){
  1202. $param = $this->request->param();
  1203. $atList=Db::name('message')->where(['chat_identify'=>$param['toContactId'],'is_group'=>1])->whereFindInSet('at',$this->userInfo['user_id'])->order('msg_id desc')->select();
  1204. $atData=$this->recombileMsg($atList,false);
  1205. Message::setAtRead($atData,$this->userInfo['user_id']);
  1206. // $message=Message::where('msg_id',$param['msg_id'])->select();
  1207. // $atList=($message ?? null) ? explode(',',$message): [];
  1208. // // 两个数组取差集
  1209. // $newAtList = array_diff($atList, [$this->userInfo['user_id']]);
  1210. // Message::where('msg_id',$param['msg_id'])->update(['at'=>implode(',',$newAtList)]);
  1211. return success('');
  1212. }
  1213. // 获取系统公告
  1214. public function getAdminNotice(){
  1215. $data=Message::where(['chat_identify'=>'admin_notice'])->order('msg_id desc')->find();
  1216. $extends=$data['extends'] ?? [];
  1217. if(!$extends){
  1218. $extends['title']='';
  1219. }
  1220. $createTime=$data['create_time'] ?? 0;
  1221. if(!$createTime){
  1222. $extends['create_time']=$createTime;
  1223. }else{
  1224. $extends['create_time']=is_string($data['create_time']) ? strtotime($data['create_time']) : $data['create_time'];
  1225. }
  1226. return success('',$extends);
  1227. }
  1228. // 双向删除消息
  1229. public function delMessage(){
  1230. $param = $this->request->param();
  1231. $id = $param['id'];
  1232. // if(!$this->globalConfig['chatInfo']['dbDelMsg']){
  1233. // return warning(lang('system.notAuth'));
  1234. // }
  1235. $message = Message::where(['id' => $id])->find();
  1236. if ($message) {
  1237. if($message['from_user']!=$this->userInfo['user_id']){
  1238. return warning(lang('system.notAuth'));
  1239. }
  1240. Message::where(['id' => $id])->delete();
  1241. // 如果是最后一条消息,需要将上一条设置为最后一条
  1242. if($message['is_last']){
  1243. Message::where(['chat_identify'=>$message['chat_identify']])->order('msg_id desc')->limit(1)->update(['is_last'=>1]);
  1244. }
  1245. $toContactId = $message['to_user'];
  1246. if ($message['is_group'] == 1) {
  1247. $toContactId = explode('-', $message['chat_identify'])[1];
  1248. }
  1249. wsSendMsg($toContactId, 'delMessage', $message, $message['is_group']);
  1250. return success('');
  1251. } else {
  1252. return warning(lang('im.exist'));
  1253. }
  1254. }
  1255. }