Chat.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. <?php
  2. namespace Community\Lib;
  3. use Dever;
  4. class Chat
  5. {
  6. # 生成key
  7. private function getKey($uid, $to_uid)
  8. {
  9. if ($uid > $to_uid) {
  10. return $uid . '_' . $to_uid;
  11. } else {
  12. return $to_uid . '_' . $uid;
  13. }
  14. }
  15. # 加入聊天信息
  16. public function add($uid, $to_uid, $collection_id, $text, $pic, $day = false)
  17. {
  18. $data['uid'] = $uid;
  19. $data['to_uid'] = $to_uid;
  20. $data['collection_id'] = $collection_id;
  21. $user = Dever::db('community/chat_user')->one($data);
  22. $data['key'] = $this->getKey($uid, $to_uid);
  23. if (!$user) {
  24. Dever::db('community/chat_user')->insert($data);
  25. }
  26. $data['text'] = $text;
  27. $data['pic'] = $pic;
  28. if ($day) {
  29. $data['day'] = $day;
  30. }
  31. return Dever::db('community/chat_info')->insert($data);
  32. }
  33. # 获取聊天对象
  34. public function getUser($uid, $collection_id, $times = false)
  35. {
  36. $data['to_uid'] = $uid;
  37. $data['collection_id'] = $collection_id;
  38. $user = Dever::db('community/chat_user')->getAll($data);
  39. # 获取最新的一条聊天记录
  40. if ($user) {
  41. $time = time();
  42. foreach ($user as $k => $v) {
  43. $where['uid'] = $v['uid'];
  44. $where['collection_id'] = $collection_id;
  45. $chat = Dever::db('community/chat_info')->getNew($where);
  46. $user[$k]['user'] = Dever::load('user/lib/info')->get($v['uid'], $collection_id, true);
  47. if ($chat) {
  48. if ($chat['pic'] && !$chat['text']) {
  49. $chat['text'] = '[图片]';
  50. } else {
  51. $chat['text'] = strip_tags($chat['text']);
  52. }
  53. $date = Dever::load('collection/lib/times')->getDate($chat['day'], $chat['cdate'], $times, true);
  54. $chat['day'] = $date[0];
  55. $chat['date'] = $date[1];
  56. }
  57. $user[$k]['chat'] = $chat;
  58. }
  59. }
  60. return $user;
  61. }
  62. # 获取聊天记录
  63. public function getInfo($uid, $to_uid, $collection_id, $times = false)
  64. {
  65. $where['key'] = $this->getKey($uid, $to_uid);
  66. $where['collection_id'] = $collection_id;
  67. $data['chat'] = Dever::db('community/chat_info')->getAll($where);
  68. if ($data['chat']) {
  69. $data['user'][$uid] = Dever::load('user/lib/info')->get($uid, $collection_id, true);
  70. $data['user'][$to_uid] = Dever::load('user/lib/info')->get($to_uid, $collection_id, true);
  71. $data['title'] = $data['user'][$to_uid]['username'];
  72. foreach ($data['chat'] as $k => $v) {
  73. $data['chat'][$k]['date'] = Dever::load('collection/lib/times')->getDate($v['day'], $v['cdate'], $times);
  74. $data['chat'][$k]['self'] = false;
  75. if ($uid == $v['uid']) {
  76. $data['chat'][$k]['self'] = true;
  77. }
  78. }
  79. $data['chat'] = array_reverse($data['chat']);
  80. }
  81. return $data;
  82. }
  83. }