Message.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  1. <?php
  2. /**
  3. * raingad IM [ThinkPHP6]
  4. * @author xiekunyu <raingad@foxmail.com>
  5. */
  6. namespace app\enterprise\model;
  7. use app\admin\model\KeywordLanguages;
  8. use app\admin\model\QuestionLanguages;
  9. use app\manage\model\Config;
  10. use app\BaseModel;
  11. use think\facade\Db;
  12. use think\facade\Cache;
  13. class Message extends BaseModel
  14. {
  15. protected $pk="msg_id";
  16. protected $json = ["extends"];
  17. protected $jsonAssoc = true;
  18. protected static $fileType=['file','image','video','voice','emoji'];
  19. // 添加聊天记录
  20. public static function addData($data){
  21. return Db::name('message')->insert($data);
  22. }
  23. // 更新消息状态
  24. public static function editData($update,$map){
  25. return Db::name('message')->where($map)->update($update);
  26. }
  27. // 查询聊天记录
  28. public static function getList($map,$where,$sort,$listRows,$pageSize){
  29. $list= Db::name('message')
  30. ->where($map)
  31. ->where($where)
  32. ->order($sort)
  33. ->paginate(['list_rows'=>$listRows,'page'=>$pageSize]);
  34. return $list;
  35. }
  36. // 发送消息
  37. public function sendMessage($param,$globalConfig=false){
  38. $is_group = $param['is_group'] ?? 0;
  39. $uid=self::$uid ? : ($param['user_id'] ?? 1);
  40. $is_robot = false; //是否给机器人发送消息
  41. if($param['toContactId']==-1){
  42. $is_group=0;
  43. }
  44. // 如果是系统账号,直接禁言
  45. if($is_group>1){
  46. $this->error=lang('im.forbidChat');
  47. return false;
  48. }
  49. $isForward=$param['is_forward'] ?? 0;
  50. $sendInterval = $globalConfig['chatInfo']['sendInterval'] ?? 0;
  51. // 如果设置了消息频率则验证,转发不收限制
  52. if ($sendInterval && !$isForward) {
  53. if (Cache::has('send_' . $uid)) {
  54. $this->error=lang('im.sendTimeLimit',['time'=>$sendInterval]);
  55. return false;
  56. }
  57. }
  58. if($param['type']=='text'){
  59. // 限制文字内容长度
  60. $text = strip_tags($param['content']);
  61. $textLen = mb_strlen($text);
  62. if ($textLen > 2048) {
  63. $this->error=lang('im.msgContentLimit') . $textLen;
  64. return false;
  65. }
  66. $param['content'] = preg_link($param['content']);
  67. // 接入聊天内容检测服务
  68. event('GreenText',['content'=>$param['content'],'service'=>"chat_detection"]);
  69. }
  70. $chatSetting = $globalConfig['chatInfo'];
  71. if($param['toContactId']!=-1){
  72. if ($is_group == 0) {
  73. $kefuUser=$chatSetting['autoAddUser']['user_ids'] ?? [];
  74. $manageUser=User::where([['status','=',1],['role','>',0]])->column('user_id');
  75. $kefu=array_unique(array_merge($kefuUser,$manageUser));
  76. $csUid = self::$userInfo['cs_uid'] ?? 0;
  77. $manage=false;
  78. // 发送者和接受者是客服或者管理员也可以发送消息
  79. if(in_array($uid,$kefu) || in_array($param['toContactId'],$kefu)){
  80. $manage=true;
  81. }
  82. if($chatSetting['simpleChat'] == 0 && !$manage){
  83. $this->error=lang('im.forbidChat');
  84. return false;
  85. }
  86. // 如果是单聊,并且是社区模式和不是自己的客服、需要判断是否是好友
  87. if ($globalConfig['sysInfo']['runMode'] == 2 && $csUid != $param['toContactId'] && !$manage) {
  88. // 判断我是不是对方的客服
  89. $cus = User::where(['user_id' => $param['toContactId']])->value('cs_uid');
  90. if ($cus != $uid) {
  91. $friend = Friend::where(['friend_user_id' => $uid, 'create_user' => $param['toContactId']])->find();
  92. if (!$friend) {
  93. $this->error=lang('im.notFriend');
  94. return false;
  95. }
  96. $otherFriend = Friend::where(['friend_user_id' => $param['toContactId'], 'create_user' => $uid])->find();
  97. if (!$otherFriend) {
  98. $this->error=lang('im.friendNot');
  99. return false;
  100. }
  101. }
  102. }
  103. //判断是否给机器人客服发送消息
  104. $autoTask = Config::autoTask();
  105. if (!empty($autoTask['user_id']) && $param['toContactId'] == $autoTask['user_id']) {
  106. $is_robot = true;
  107. }
  108. }else{
  109. // 群聊必须群成员才能发送消息
  110. $group_id = explode('-', $param['toContactId'])[1] ?? '';
  111. if(!$group_id){
  112. $this->error=lang('system.parameterError');
  113. return false;
  114. }
  115. if(!self::nospeak($group_id,$uid)){
  116. if($isForward){
  117. return false;
  118. }
  119. return shutdown(lang('group.notSpeak'));
  120. }
  121. // 群聊必须群成员才能发送消息
  122. $groupUser=GroupUser::where(['user_id'=>$uid,'status'=>1,'group_id'=>$group_id,'delete_time'=>0])->find();
  123. if(!$groupUser){
  124. $this->error = lang('group.notCustom');
  125. return false;
  126. }
  127. if($groupUser['no_speak_time']>time()){
  128. $this->error = lang('group.notSpeak',['time'=>date('Y-m-d H:i:s',$groupUser['no_speak_time'])]);
  129. return false;
  130. }
  131. }
  132. }
  133. if ($sendInterval) {
  134. Cache::set('send_' . $uid, time(), $sendInterval);
  135. }
  136. $data = self::sendMsg($param,$is_group, 0, $uid);
  137. // 机器人自动回复问题推送给用户
  138. if ($is_robot && $param['type'] == 'text') {
  139. if (!empty($param['question_id'])) {
  140. $param['type'] = 'answer';
  141. $param['content'] = QuestionLanguages::where('id', $param['question_id'])->value('answer');
  142. $param['extends'] = json_encode([
  143. 'question_id' => $param['question_id'],
  144. ]);
  145. } else {
  146. //获取关键词匹配
  147. $keyword_ids = KeywordLanguages::getKeywordByContent($param['content']);
  148. $question = QuestionLanguages::getQuestion($keyword_ids, $param['content']);
  149. $data['question'] = $question;
  150. if ($question) {
  151. $param['type'] = 'list';
  152. $content = [
  153. 'title' => Config::getFieldValue('reply_keyword'),
  154. 'list' => $question,
  155. ];
  156. $param['content'] = json_encode($content);
  157. } else {
  158. $param['type'] = 'text';
  159. $param['content'] = Config::getFieldValue('reply_keyword_math_fail');
  160. }
  161. }
  162. $fromUserId = (int)$param['toContactId'];
  163. $user_id = (int)$param['user_id'];
  164. $param['toContactId'] = $user_id;
  165. $param['user_id'] = $fromUserId;
  166. $param['fromUser'] = null;
  167. $param['id'] = \utils\Str::getUuid();
  168. self::sendMsg($param,$is_group, 0, $user_id);
  169. //机器人自动回复消息
  170. //event('AutoReplyMessage', ['param' => $param, 'globalConfig' => $globalConfig]);
  171. }
  172. return $data;
  173. }
  174. //实际发送消息
  175. public static function sendMsg($param,$is_group=0,$is_sys=0, $uid=0){
  176. // $uid = $uid ?: ($param['user_id'] ?? 1);
  177. $uid = self::$uid ?: ($param['user_id'] ?? 1);
  178. $toContactId=$param['toContactId'];
  179. $manage=[];
  180. // 重新建立会话,更新会话删除记录
  181. $isDelChat=ChatDelog::where(['user_id'=>$uid,'to_user'=>$toContactId])->find();
  182. if($isDelChat){
  183. ChatDelog::where(['user_id'=>$uid,'to_user'=>$toContactId])->delete();
  184. ChatDelog::updateCache($uid);
  185. }
  186. if($is_group==1){
  187. $group_id = explode('-', $param['toContactId'])[1] ?? '';
  188. $chat_identify=$toContactId;
  189. $toContactId=$group_id;
  190. $manage=GroupUser::getGroupManage($group_id);
  191. }else{
  192. $chat_identify=chat_identify($param['user_id'],$toContactId);
  193. }
  194. $fileSzie=isset($param['file_size'])?$param['file_size']:'';
  195. $fileName=isset($param['file_name'])?$param['file_name']:'';
  196. $ossUrl=getDiskUrl();
  197. // 如果是转发图片文件的消息,必须把域名去除掉
  198. $content=$param['content'];
  199. if(in_array($param['type'],self::$fileType)){
  200. if(strpos($param['content'],$ossUrl)!==false){
  201. $content=str_replace($ossUrl,'',$param['content']);
  202. }
  203. }
  204. $param['content']=$content;
  205. $atList=($param['at'] ?? null) ? array_map('intval', $param['at']): [];
  206. // 如果at里面有0,代表@所有人
  207. if($atList && in_array(0,$atList)){
  208. $atList=GroupUser::where([['group_id','=',$toContactId],['status','=',1],['user_id','<>',$param['user_id']]])->column('user_id');
  209. }
  210. $at=$atList ? implode(',',$atList) : null;
  211. $data=[
  212. 'from_user'=>$param['user_id'],
  213. 'to_user'=>$toContactId,
  214. 'id'=>$param['id'],
  215. 'content'=>$param['type'] != 'list' ? str_encipher($param['content'],true) : $param['content'],
  216. 'chat_identify'=>$chat_identify,
  217. 'create_time'=>time(),
  218. 'type'=>$param['type'],
  219. 'is_group'=>$toContactId==-1 ? 3 : $is_group,
  220. 'is_read'=>$is_group ? 1 : 0,
  221. 'file_id'=>$param['file_id'] ?? 0,
  222. "file_cate"=>$param['file_cate'] ?? 0,
  223. 'file_size'=>$fileSzie,
  224. 'file_name'=>$fileName,
  225. 'at'=>$at,
  226. 'pid'=>$param['pid'] ?? 0,
  227. 'extends'=>($param['extends'] ?? null) ? $param['extends'] : null,
  228. ];
  229. $message=new self();
  230. $message->update(['is_last'=>0],['chat_identify'=>$chat_identify]);
  231. $message->save($data);
  232. // 拼接消息推送
  233. $type=$is_group?'group':'simple';
  234. $sendData=$param;
  235. $sendData['status']='succeed';
  236. $sendData['at']=$atList;
  237. $sendData['msg_id']=$message->msg_id;
  238. $sendData['is_read']=0;
  239. $sendData['to_user']=(string)$toContactId;
  240. $sendData['role']=$manage[self::$uid] ?? 3;
  241. $sendData['sendTime']=(int)$sendData['sendTime'];
  242. //这里单聊中发送对方的消息,对方是接受状态,自己是对方的联系人,要把发送对象设置为发送者的ID。
  243. if($is_group){
  244. $sendData['toContactId']=$param['toContactId'];
  245. // 将团队所有成员的未读状态+1
  246. GroupUser::editGroupUser([['group_id','=',$toContactId],['user_id','<>',$uid]],['unread'=>Db::raw('unread+1')]);
  247. }else{
  248. //$sendData['toContactId']=$toContactId;//$uid;
  249. $sendData['toContactId'] = $param['user_id'];
  250. }
  251. $sendData['fileSize']=$fileSzie;
  252. $sendData['fileName']=$fileName;
  253. if(in_array($sendData['type'],self::$fileType)){
  254. $sendData['content']=getFileUrl($sendData['content']);
  255. if($sendData['type']=='image'){
  256. $pre=1;
  257. }else{
  258. $pre=2;
  259. }
  260. $sendData['preview']=previewUrl($sendData['content'],$pre);
  261. $sendData['extUrl']=getExtUrl($sendData['content']);
  262. $sendData['download']= $sendData['file_id'] ? getMainHost().'/filedown/'.encryptIds($sendData['file_id']) : '';
  263. }
  264. $forContactId=$sendData['toContactId'];
  265. if($is_sys){
  266. $forContactId=$toContactId;
  267. }
  268. if($is_group==0){
  269. $toContactId=[$toContactId,$param['user_id']];
  270. }
  271. $sendData['toUser']=(string)$param['toContactId'];
  272. $user=new User();
  273. // 将聊天窗口的联系人信息带上,方便临时会话
  274. $sendData['contactInfo']=$user->setContact($forContactId,$is_group,$sendData['type'],$sendData['content']);
  275. if (empty($sendData['fromUser'])) {
  276. $sendData['fromUser'] = [
  277. 'id' => $sendData['contactInfo']['id'],
  278. 'displayName' => $sendData['contactInfo']['displayName'],
  279. 'avatar' => $sendData['contactInfo']['avatar'],
  280. 'account' => '',
  281. ];
  282. }
  283. $sendData['fromUser']['id']=(int)$sendData['fromUser']['id'];
  284. // 向发送方发送消息
  285. wsSendMsg($toContactId,$type,$sendData,$is_group);
  286. $sendData['toContactId']=$param['toContactId'];
  287. return $sendData;
  288. }
  289. // 群禁言
  290. public static function nospeak($group_id,$user_id){
  291. $group=Group::find($group_id);
  292. if($group->owner_id==$user_id){
  293. return true;
  294. }
  295. if($group->setting){
  296. $setting=json_decode($group->setting,true);
  297. $nospeak=isset($setting['nospeak'])?$setting['nospeak']:0;
  298. $role=GroupUser::where(['group_id'=>$group_id,'user_id'=>$user_id])->value('role');
  299. if($nospeak==1 && $role>2){
  300. return false;
  301. }elseif($nospeak==2 && $role!=1){
  302. return false;
  303. }
  304. }
  305. return true;
  306. }
  307. // 将消息中的@用户加入到atListQueue中
  308. public static function setAtread($messages,$user_id){
  309. foreach($messages as $k=>$v){
  310. if(!isset($v['at'])){
  311. continue;
  312. }
  313. if($v['at'] && in_array($user_id,$v['at'])){
  314. $atListQueue=Cache::get("atListQueue");
  315. $atListQueue[$v['msg_id']][]=$user_id;
  316. Cache::set("atListQueue",$atListQueue);
  317. }
  318. }
  319. }
  320. }