@param $userId
@param $conversationId

@return bool
356474
public function acceptMessageRequest($userId, $conversationId)
    {
        if ($this->checkUserExist($userId, $conversationId)) {
            $conversation = $this->find($conversationId);
            $conversation->is_accepted = true;
            $conversation->save();

            return true;
        }

        return false;
    }
256343
public static function can_create_contact(int $userid, int $requesteduserid) : bool {
        global $CFG;

        // If we can't message at all, then we can't create a contact.
        if (empty($CFG->messaging)) {
            return false;
        }

        // If we can message anyone on the site then we can create a contact.
        if ($CFG->messagingallusers) {
            return true;
        }

        // We need to check if they are in the same course.
        return enrol_sharing_course($userid, $requesteduserid);
    }
236668
public static function legacy_messages_exist($userid) {
        global $DB;

        $sql = "SELECT id
                  FROM {message} m
                 WHERE useridfrom = ?
                    OR useridto = ?";
        $messageexists = $DB->record_exists_sql($sql, [$userid, $userid]);

        $sql = "SELECT id
                  FROM {message_read} m
                 WHERE useridfrom = ?
                    OR useridto = ?";
        $messagereadexists = $DB->record_exists_sql($sql, [$userid, $userid]);

        return $messageexists || $messagereadexists;
    }
281929
public function join($userId, $chatroomId) {
    	try{
			if (empty($userId))
				throw new Exception('Paramer "userId" is required');

			if (empty($chatroomId))
				throw new Exception('Paramer "chatroomId" is required');


    		$params = array (
    		'userId' => $userId,
    		'chatroomId' => $chatroomId
    		);

    		$ret = $this->SendRequest->curl('/chatroom/join.json',$params,'urlencoded','im','POST');
    		if(empty($ret))
    			throw new Exception('bad request');
    		return $ret;

    	}catch (Exception $e) {
    		print_r($e->getMessage());
    	}
   }
1288611
public static function unmute_conversation(int $userid, int $conversationid) : void {
        global $DB;

        $DB->delete_records('message_conversation_actions',
            [
                'userid' => $userid,
                'conversationid' => $conversationid,
                'action' => self::CONVERSATION_ACTION_MUTED
            ]
        );
    }
1065827
public function chatroomUserGagRollback($userId,$chatroomId) {
        try{
            if(empty($userId))
                throw new Exception('用户 Id 不能为空');
            if(empty($chatroomId))
                throw new Exception('聊天室 Id 不能为空');
            $params['userId'] = $userId;
            $params['chatroomId'] = $chatroomId;
            $ret = $this->curl('/chatroom/user/gag/rollback',$params);
            if(empty($ret))
                throw new Exception('请求失败');
            return $ret;
        }catch (Exception $e) {
            print_r($e->getMessage());
        }
    }
271126
public static function create_contact_request(int $userid, int $requesteduserid) {
        global $CFG, $USER;

        // Check if messaging is enabled.
        if (empty($CFG->messaging)) {
            throw new moodle_exception('disabled', 'message');
        }

        // Validate context.
        $context = context_system::instance();
        self::validate_context($context);

        $params = ['userid' => $userid, 'requesteduserid' => $requesteduserid];
        $params = self::validate_parameters(self::create_contact_request_parameters(), $params);

        $capability = 'moodle/site:manageallmessaging';
        if (($USER->id != $params['userid']) && !has_capability($capability, $context)) {
            throw new required_capability_exception($context, $capability, 'nopermissions', '');
        }

        $result = [
            'warnings' => []
        ];

        if (!\core_message\api::can_create_contact($params['userid'], $params['requesteduserid'])) {
            $result['warnings'][] = [
                'item' => 'user',
                'itemid' => $params['requesteduserid'],
                'warningcode' => 'cannotcreatecontactrequest',
                'message' => 'You are unable to create a contact request for this user'
            ];
        } else {
            if ($requests = \core_message\api::get_contact_requests_between_users($params['userid'], $params['requesteduserid'])) {
                // There should only ever be one but just in case there are multiple then we can return the first.
                $result['request'] = array_shift($requests);
            } else {
                $result['request'] = \core_message\api::create_contact_request($params['userid'], $params['requesteduserid']);
            }
        }

        return $result;
    }
826852
public static function get_unread_conversation_counts(int $userid) : array {
        global $DB;

        // Get all conversations the user is in, and check unread.
        $unreadcountssql = 'SELECT conv.id, conv.type, indcounts.unreadcount
                              FROM {message_conversations} conv
                        INNER JOIN (
                                      SELECT m.conversationid, count(m.id) as unreadcount
                                        FROM {messages} m
                                  INNER JOIN {message_conversations} mc
                                          ON mc.id = m.conversationid
                                  INNER JOIN {message_conversation_members} mcm
                                          ON m.conversationid = mcm.conversationid
                                   LEFT JOIN {message_user_actions} mua
                                          ON (mua.messageid = m.id AND mua.userid = ? AND
                                             (mua.action = ? OR mua.action = ?))
                                       WHERE mcm.userid = ?
                                         AND m.useridfrom != ?
                                         AND mua.id is NULL
                                    GROUP BY m.conversationid
                                   ) indcounts
                                ON indcounts.conversationid = conv.id
                             WHERE conv.enabled = 1';

        $unreadcounts = $DB->get_records_sql($unreadcountssql, [$userid, self::MESSAGE_ACTION_READ, self::MESSAGE_ACTION_DELETED,
            $userid, $userid]);

        // Get favourites, so we can track these separately.
        $service = \core_favourites\service_factory::get_service_for_user_context(\context_user::instance($userid));
        $favouriteconversations = $service->find_favourites_by_type('core_message', 'message_conversations');
        $favouriteconvids = array_flip(array_column($favouriteconversations, 'itemid'));

        // Assemble the return array.
        $counts = ['favourites' => 0, 'types' => [
            self::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL => 0,
            self::MESSAGE_CONVERSATION_TYPE_GROUP => 0,
            self::MESSAGE_CONVERSATION_TYPE_SELF => 0
        ]];
        foreach ($unreadcounts as $convid => $info) {
            if (isset($favouriteconvids[$convid])) {
                $counts['favourites']++;
                continue;
            }
            $counts['types'][$info->type]++;
        }

        return $counts;
    }
1252245
public function DismissAnnouncement($DiscussionID, $UserID) {
      $Count = $this->SQL
         ->Select('UserID')
         ->From('UserDiscussion')
         ->Where('DiscussionID', $DiscussionID)
         ->Where('UserID', $UserID)
         ->Get()
         ->NumRows();
         
      $CountComments = $this->SQL
         ->Select('CountComments')
         ->From('Discussion')
         ->Where('DiscussionID', $DiscussionID)
         ->Get()
         ->FirstRow()
         ->CountComments;
      
      if ($Count > 0) {
         $this->SQL
            ->Update('UserDiscussion')
            ->Set('CountComments', $CountComments)
            ->Set('DateLastViewed', Gdn_Format::ToDateTime())
            ->Set('Dismissed', '1')
            ->Where('DiscussionID', $DiscussionID)
            ->Where('UserID', $UserID)
            ->Put();
      } else {
         $this->SQL->Options('Ignore', TRUE);
         $this->SQL->Insert(
            'UserDiscussion',
            array(
               'UserID' => $UserID,
               'DiscussionID' => $DiscussionID,
               'CountComments' => $CountComments,
               'DateLastViewed' => Gdn_Format::ToDateTime(),
               'Dismissed' => '1'
            )
         );
      }
   }
161131
public function send(Conversation $conversation, $body, $userId, $type = 'text')
    {
        $message = $conversation->messages()->create([
            'body' => $body,
            'user_id' => $userId,
            'type' => $type,
        ]);

        $messageWasSent = Chat::sentMessageEvent();
        $message->load('sender');
        $this->raise(new $messageWasSent($message));

        return $message;
    }
599587
public function getMessagesById($conversationId, $userId, $offset, $take)
    {
        return Conversation::with(
            [
                'messages' => function ($query) use ($userId, $offset, $take) {
                    $query->where(
                        function ($qr) use ($userId) {
                            $qr->where('user_id', '=', $userId)
                                ->where('deleted_from_sender', 0);
                        }
                    )
                        ->orWhere(
                            function ($q) use ($userId) {
                                $q->where('user_id', '!=', $userId)
                                    ->where('deleted_from_receiver', 0);
                            }
                        );

                    $query->offset($offset)->take($take);

                }
            ]
        )->with(['userone', 'usertwo'])->find($conversationId);

    }
808205
public static function disable_conversation(int $conversationid) {
        global $DB;

        $conversation = new \stdClass();
        $conversation->id = $conversationid;
        $conversation->enabled = self::MESSAGE_CONVERSATION_DISABLED;
        $conversation->timemodified = time();
        $DB->update_record('message_conversations', $conversation);
    }
300618
public static function can_grade_user_in_course($userid, $courseid) {
        $ratecap = 'moodle/competency:competencygrade';
        return has_capability($ratecap, context_course::instance($courseid))
            || static::can_grade_user($userid);
    }
1034
public function AddUserToConversation($ConversationID, $UserID) {
      if (!is_array($UserID))
         $UserID = array($UserID);
         
      // First define the current users in the conversation
      $OldContributorData = $this->GetRecipients($ConversationID);
      $OldContributorData = Gdn_DataSet::Index($OldContributorData, 'UserID');
      $AddedUserIDs = array();
      
      // Get some information about this conversation
      $ConversationData = $this->SQL
         ->Select('LastMessageID')
         ->Select('DateUpdated')
         ->Select('CountMessages')
         ->From('Conversation')
         ->Where('ConversationID', $ConversationID)
         ->Get()
         ->FirstRow();
      
      // Add the user(s) if they are not already in the conversation
      foreach ($UserID as $NewUserID) {
         if (!array_key_exists($NewUserID, $OldContributorData)) {
            $AddedUserIDs[] = $NewUserID;
            $this->SQL->Insert('UserConversation', array(
               'UserID' => $NewUserID,
               'ConversationID' => $ConversationID,
               'LastMessageID' => $ConversationData->LastMessageID,
               'CountReadMessages' => 0,
               'DateConversationUpdated' => $ConversationData->DateUpdated
            ));
         } elseif ($OldContributorData[$NewUserID]->Deleted) {
            $AddedUserIDs[] = $NewUserID;
            
            $this->SQL->Put('UserConversation',
               array('Deleted' => 0),
               array('ConversationID' => $ConversationID, 'UserID' => $NewUserID));
         }
      }
      if (count($AddedUserIDs) > 0) {
         $Session = Gdn::Session();
         
         // Update the Contributors field on the conversation
         $Contributors = array_unique(array_merge($AddedUserIDs, array_keys($OldContributorData)));
         sort($Contributors);
         $this->SQL
            ->Update('Conversation')
            ->Set('Contributors', Gdn_Format::Serialize($Contributors))
            ->Where('ConversationID', $ConversationID)
            ->Put();
         
         $ActivityModel = new ActivityModel();
         foreach ($AddedUserIDs as $AddedUserID) {
            $ActivityModel->Queue(array(
                  'ActivityType' => 'AddedToConversation',
                  'NotifyUserID' => $AddedUserID,
                  'HeadlineFormat' => T('You were added to a conversation.', '{ActivityUserID,User} added you to a <a href="{Url,htmlencode}">conversation</a>.'),
                  'Route' => '/messages/'.$ConversationID
                ),
                'ConversationMessage'
            );
         }
         $ActivityModel->SaveQueue();
         
         $this->UpdateUserUnreadCount($AddedUserIDs);
      }
   }
843400
public function startConversationWith($firstUserId, $secondUserId)
    {
        $created = $this->query()->create([
            'first_user_id'  => $firstUserId,
            'second_user_id' => $secondUserId,
        ]);

        if ($created) {
            return true;
        }

        return false;
    }
330536
public static function mark_all_conversation_messages_as_read(int $userid, int $conversationid) {
        global $CFG;

        // Check if messaging is enabled.
        if (empty($CFG->messaging)) {
            throw new moodle_exception('disabled', 'message');
        }

        $params = array(
            'userid' => $userid,
            'conversationid' => $conversationid,
        );
        $params = self::validate_parameters(self::mark_all_conversation_messages_as_read_parameters(), $params);

        $context = context_system::instance();
        self::validate_context($context);

        $user = core_user::get_user($params['userid'], '*', MUST_EXIST);
        core_user::require_active_user($user);

        if (\core_message\api::can_mark_all_messages_as_read($params['userid'], $params['conversationid'])) {
            \core_message\api::mark_all_messages_as_read($params['userid'], $params['conversationid']);
        } else {
            throw new moodle_exception('accessdenied', 'admin');
        }
    }
523207
public function existstUserCountryCodeAndPhoneNumber($userId) {
        $countryCode = DB::table('users')
            ->where('id', '=', $userId)
            ->value('phone_country_code')
        ;

        $phoneNumber =  DB::table('users')
            ->where('id', '=', $userId)
            ->value('phone_number')
        ;

        if ((!$countryCode) || (!$phoneNumber)) {
            return false;
        }

        return true;
    }