Add another user to the conversation.

@since 2.0.0
@access public

@param int $ConversationID Unique ID of conversation effected.
@param int $UserID Unique ID of current user.
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);
      }
   }
15823
public function AddMessage($ConversationID = '') {
      $this->Form->SetModel($this->ConversationMessageModel);
      if (is_numeric($ConversationID) && $ConversationID > 0)
         $this->Form->AddHidden('ConversationID', $ConversationID);
      
      if ($this->Form->AuthenticatedPostBack()) {
         $ConversationID = $this->Form->GetFormValue('ConversationID', '');
         $Conversation = $this->ConversationModel->GetID($ConversationID, Gdn::Session()->UserID);   
         
         $this->EventArguments['Conversation'] = $Conversation;
         $this->EventArguments['ConversationID'] = $ConversationID;
         $this->FireEvent('BeforeAddMessage');
         
         $NewMessageID = $this->Form->Save();
         
         if ($NewMessageID) {
            if ($this->DeliveryType() == DELIVERY_TYPE_ALL)
               Redirect('messages/'.$ConversationID.'/#'.$NewMessageID, 302);
               
            $this->SetJson('MessageID', $NewMessageID);
            // If this was not a full-page delivery type, return the partial response
            // Load all new messages that the user hasn't seen yet (including theirs)
            $LastMessageID = $this->Form->GetFormValue('LastMessageID');
            if (!is_numeric($LastMessageID))
               $LastMessageID = $NewMessageID - 1;
            
            $Session = Gdn::Session();
            $MessageData = $this->ConversationMessageModel->GetNew($ConversationID, $LastMessageID);
            $this->Conversation = $Conversation;
            $this->MessageData = $MessageData;

            $this->View = 'messages';
         } else {
            // Handle ajax based errors...
            if ($this->DeliveryType() != DELIVERY_TYPE_ALL)
               $this->ErrorMessage($this->Form->Errors());
         }
      }
      $this->Render();      
   }
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);

    }
217935
public function Clear($ConversationID, $ClearingUserID) {
      $this->SQL->Update('UserConversation')
         ->Set('Deleted', 1)
         ->Set('DateLastViewed', Gdn_Format::ToDateTime())
         ->Where('UserID', $ClearingUserID)
         ->Where('ConversationID', $ConversationID)
         ->Put();

      $this->CountUnread($ClearingUserID);
   }
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());
    	}
   }
1172746
public void addActiveParticipant(String userId)
	{
		addActiveParticipant(
				userId, 
				null, 
				null, 
				false, 
				null, 
				null);
	}
725129
public function canJoinConversation($user, $conversation)
    {
        $thread = $this->find($conversation);

        if ($thread) {
            if (($thread->first_user_id == $user->id) || ($thread->second_user_id == $user->id)) {
                return true;
            }
        }

        return false;
    }
479354
public function addParticipants($userIds)
    {
        if (is_array($userIds)) {
            foreach ($userIds as $id) {
                $this->users()->attach($id);
            }
        } else {
            $this->users()->attach($userIds);
        }

        if (Chat::makeThreeOrMoreUsersPublic() && $this->fresh()->users->count() > 2) {
            $this->private = false;
            $this->save();
        }

        return $this;
    }
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'
            )
         );
      }
   }
991102
public function Bookmark($ConversationID, $UserID) {
      $Bookmark = FALSE;
      $Discussion = $this->GetID($ConversationID, $UserID);
      if (is_object($Discussion)) {
         $Bookmark = $Discussion->Bookmark == '0' ? '1' : '0';
         $this->SQL->Update('UserConversation')
            ->Set('Bookmark', $Bookmark)
            ->Where('ConversationID', $ConversationID)
            ->Where('UserID', $UserID)
            ->Put();
         $Bookmark == '1' ? TRUE : FALSE;
      }
      return $Bookmark;
   }
1110085
public static function unmute_conversations(int $userid, array $conversationids) {
        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, 'conversationids' => $conversationids];
        $params = self::validate_parameters(self::unmute_conversations_parameters(), $params);

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

        foreach ($params['conversationids'] as $conversationid) {
            \core_message\api::unmute_conversation($params['userid'], $conversationid);
        }

        return [];
    }
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');
        }
    }
700134
public static function count_contacts(int $userid) : int {
        global $DB;

        $sql = "SELECT COUNT(id)
                  FROM {message_contacts}
                 WHERE userid = ? OR contactid = ?";
        return $DB->count_records_sql($sql, [$userid, $userid]);
    }
1173345
public static function is_contact(int $userid, int $contactid) : bool {
        global $DB;

        $sql = "SELECT id
                  FROM {message_contacts} mc
                 WHERE (mc.userid = ? AND mc.contactid = ?)
                    OR (mc.userid = ? AND mc.contactid = ?)";
        return $DB->record_exists_sql($sql, [$userid, $contactid, $contactid, $userid]);
    }
882285
protected static function delete_user_data($userid) {
        global $DB;
        $DB->delete_records_select('messageinbound_messagelist', 'userid = :userid', ['userid' => $userid]);
        \core_userkey\privacy\provider::delete_userkeys('messageinbound_handler', $userid);
    }
1079560
private function migrate_data($userid, $otheruserid) {
        global $DB;

        if ($userid == $otheruserid) {
            // Since 3.7, pending self-conversations should be migrated during the upgrading process so shouldn't be any
            // self-conversations on the legacy tables. However, this extra-check has been added just in case.
            $conversation = \core_message\api::get_self_conversation($userid);
            if (empty($conversation)) {
                $conversation = \core_message\api::create_conversation(
                    \core_message\api::MESSAGE_CONVERSATION_TYPE_SELF,
                    [$userid]
                );
            }
            $conversationid = $conversation->id;
        } else if (!$conversationid = \core_message\api::get_conversation_between_users([$userid, $otheruserid])) {
            $conversation = \core_message\api::create_conversation(
                \core_message\api::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL,
                [
                    $userid,
                    $otheruserid
                ]
            );
            $conversationid = $conversation->id;
        }

        // First, get the rows from the 'message' table.
        $select = "(useridfrom = ? AND useridto = ?) OR (useridfrom = ? AND useridto = ?)";
        $params = [$userid, $otheruserid, $otheruserid, $userid];
        $messages = $DB->get_recordset_select('message', $select, $params, 'id ASC');
        foreach ($messages as $message) {
            if ($message->notification) {
                $this->migrate_notification($message, false);
            } else {
                $this->migrate_message($conversationid, $message);
            }
        }
        $messages->close();

        // Ok, all done, delete the records from the 'message' table.
        $DB->delete_records_select('message', $select, $params);

        // Now, get the rows from the 'message_read' table.
        $messages = $DB->get_recordset_select('message_read', $select, $params, 'id ASC');
        foreach ($messages as $message) {
            if ($message->notification) {
                $this->migrate_notification($message, true);
            } else {
                $this->migrate_message($conversationid, $message);
            }
        }
        $messages->close();

        // Ok, all done, delete the records from the 'message_read' table.
        $DB->delete_records_select('message_read', $select, $params);
    }
1327344
public function getConversationMessageById($conversationId, $userID, $channel)
    {
        $conversation = $this->query()->with(['messages', 'messages.sender', 'messages.files', 'firstUser', 'secondUser', 'files'])->find($conversationId);

        $collection = (object) null;
        $collection->conversationId = $conversationId;
        $collection->channel_name = $channel;
        $collection->user = ($conversation->firstUser->id == $userID) ? $conversation->secondUser : $conversation->firstUser;
        $collection->messages = $conversation->messages;
        $collection->files = $conversation->files;

        return collect($collection);
    }