Adds a message to a conversation.

@param Conversation $conversation
@param string       $body
@param int          $userId
@param string       $type

@return Message
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;
    }
835525
public static function mute_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::mute_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) {
            if (!\core_message\api::is_conversation_muted($params['userid'], $conversationid)) {
                \core_message\api::mute_conversation($params['userid'], $conversationid);
            }
        }

        return [];
    }
730172
public function ConversationQuery($ViewingUserID, $Join = '') {
      $this->SQL
         ->Select('c.*')
         ->Select('lm.InsertUserID', '', 'LastMessageUserID')
         ->Select('lm.DateInserted', '', 'DateLastMessage')
         ->Select('lm.Body', '', 'LastMessage')
         ->Select('lm.Format')
         ->Select('lmu.Name', '', 'LastMessageName')
         ->Select('lmu.Photo', '', 'LastMessagePhoto')
         ->From('Conversation c');


      if ($ViewingUserID !== FALSE) {
         $this->SQL
            ->Select('c.CountMessages - uc.CountReadMessages', '', 'CountNewMessages')
            ->Select('uc.LastMessageID, uc.CountReadMessages, uc.DateLastViewed, uc.Bookmarked')
            ->Join('UserConversation uc', "c.ConversationID = uc.ConversationID and uc.UserID = $ViewingUserID")
            ->Join('ConversationMessage lm', 'uc.LastMessageID = lm.MessageID')
            ->Join('User lmu', 'lm.InsertUserID = lmu.UserID')
            ->Where('uc.Deleted', 0);
      } else {
         $this->SQL
            ->Select('0', '', 'CountNewMessages')
            ->Select('c.CountMessages', '', 'CountReadMessages')
            ->Select('lm.DateInserted', '', 'DateLastViewed')
            ->Select('0', '', 'Bookmarked')
            ->Join('ConversationMessage lm', 'c.LastMessageID = lm.MessageID')
            ->Join('User lmu', 'lm.InsertUserID = lmu.UserID');
      }
   }
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;
    }
50236
public function addMessage($message, $type) {
		if(!($this->session->get($this->sessionKey, [])) == null)
		{
			$messages = $this->session->get($this->sessionKey, []);
		}
		
		$messages[] = [
			'message' => $message,
			'type' => $type,
		];
		
		$this->session->set($this->sessionKey, $messages);
	}
844337
public Chat createChat(EntityJid userJID, String thread, ChatMessageListener listener) {
        if (thread == null) {
            thread = nextID();
        }
        Chat chat = threadChats.get(thread);
        if (chat != null) {
            throw new IllegalArgumentException("ThreadID is already used");
        }
        chat = createChat(userJID, thread, true);
        chat.addMessageListener(listener);
        return chat;
    }
482742
public function message($to, $body, $type = 'chat', $subject = null, $payload = null) {
	    if(is_null($type))
	    {
	        $type = 'chat';
	    }
	    
		$to	  = htmlspecialchars($to);
		$body	= htmlspecialchars($body);
		$subject = htmlspecialchars($subject);
		
		$out = "<message from=\"{$this->fulljid}\" to=\"$to\" type='$type'>";
		if($subject) $out .= "<subject>$subject</subject>";
		$out .= "<body>$body</body>";
		if($payload) $out .= $payload;
		$out .= "</message>";
		
		$this->send($out);
	}
1280127
public static function mute_conversation(int $userid, int $conversationid) : void {
        global $DB;

        $mutedconversation = new \stdClass();
        $mutedconversation->userid = $userid;
        $mutedconversation->conversationid = $conversationid;
        $mutedconversation->action = self::CONVERSATION_ACTION_MUTED;
        $mutedconversation->timecreated = time();

        $DB->insert_record('message_conversation_actions', $mutedconversation);
    }
863788
public function Save($FormPostValues, $Conversation = NULL) {
      $Session = Gdn::Session();
      
      // Define the primary key in this model's table.
      $this->DefineSchema();
      
      // Add & apply any extra validation rules:      
      $this->Validation->ApplyRule('Body', 'Required');
      $this->AddInsertFields($FormPostValues);
      
      $this->EventArguments['FormPostValues'] = $FormPostValues;
      $this->FireEvent('BeforeSaveValidation');
      
      // Validate the form posted values
      $MessageID = FALSE;
      if($this->Validate($FormPostValues)) {
         $Fields = $this->Validation->SchemaValidationFields(); // All fields on the form that relate to the schema
         TouchValue('Format', $Fields, C('Garden.InputFormatter', 'Html'));
         
         $this->EventArguments['Fields'] = $Fields;
         $this->FireEvent('BeforeSave');
         
         $MessageID = $this->SQL->Insert($this->Name, $Fields);
         $this->LastMessageID = $MessageID;
         $ConversationID = ArrayValue('ConversationID', $Fields, 0);

         if (!$Conversation)
            $Conversation = $this->SQL->GetWhere('Conversation', array('ConversationID' => $ConversationID))->FirstRow(DATASET_TYPE_ARRAY);

         $Message = $this->GetID($MessageID);
         $this->EventArguments['Conversation'] = $Conversation;
         $this->EventArguments['Message'] = $Message;
         $this->FireEvent('AfterSave');
         
         // Get the new message count for the conversation.
         $SQLR = $this->SQL
            ->Select('MessageID', 'count', 'CountMessages')
            ->Select('MessageID', 'max', 'LastMessageID')
            ->From('ConversationMessage')
            ->Where('ConversationID', $ConversationID)
            ->Get()->FirstRow(DATASET_TYPE_ARRAY);
         if (sizeof($SQLR)) {
            list($CountMessages, $LastMessageID) = array_values($SQLR);
         } else { return; }
         
         // Update the conversation's DateUpdated field.
         $DateUpdated = Gdn_Format::ToDateTime();
         
         $this->SQL
            ->Update('Conversation c')
            ->Set('CountMessages', $CountMessages)
            ->Set('LastMessageID', $LastMessageID)
            ->Set('UpdateUserID', Gdn::Session()->UserID)
            ->Set('DateUpdated', $DateUpdated)
            ->Where('ConversationID', $ConversationID)
            ->Put();

         // Update the last message of the users that were previously up-to-date on their read messages.
         $this->SQL
            ->Update('UserConversation uc')
            ->Set('uc.LastMessageID', $MessageID)
            ->Set('uc.DateConversationUpdated', $DateUpdated)
            ->Where('uc.ConversationID', $ConversationID)
            ->Where('uc.Deleted', '0')
            ->Where('uc.CountReadMessages', $CountMessages - 1)
            ->Where('uc.UserID <>', $Session->UserID)
            ->Put();
         
         // Update the date updated of the users that were not up-to-date.
         $this->SQL
            ->Update('UserConversation uc')
            ->Set('uc.DateConversationUpdated', $DateUpdated)
            ->Where('uc.ConversationID', $ConversationID)
            ->Where('uc.Deleted', '0')
            ->Where('uc.CountReadMessages <>', $CountMessages - 1)
            ->Where('uc.UserID <>', $Session->UserID)
            ->Put();

         // Update the sending user.
         $this->SQL
            ->Update('UserConversation uc')
            ->Set('uc.CountReadMessages', $CountMessages)
            ->Set('Deleted', 0)
            ->Set('uc.DateConversationUpdated', $DateUpdated)
            ->Where('ConversationID', $ConversationID)
            ->Where('UserID', $Session->UserID)
            ->Put();

         // Find users involved in this conversation
         $UserData = $this->SQL
            ->Select('UserID')
            ->Select('LastMessageID')
            ->Select('Deleted')
            ->From('UserConversation')
            ->Where('ConversationID', $ConversationID)
            ->Get()->Result(DATASET_TYPE_ARRAY);
         
         $UpdateCountUserIDs = array();
         $NotifyUserIDs = array();
         
         // Collapse for call to UpdateUserCache and ActivityModel.
         $InsertUserFound = FALSE;
         foreach ($UserData as $UpdateUser) {
            $LastMessageID = GetValue('LastMessageID', $UpdateUser);
            $UserID = GetValue('UserID', $UpdateUser);
            $Deleted = GetValue('Deleted', $UpdateUser);
            
            if ($UserID == GetValue('InsertUserID', $Fields)) {
               $InsertUserFound = TRUE;
               if ($Deleted) {
                  $this->SQL->Put('UserConversation', array('Deleted' => 0, 'DateConversationUpdated' => $DateUpdated), array('ConversationID' => $ConversationID, 'UserID' => $UserID));
               }
            }
            
            // Update unread for users that were up to date
            if ($LastMessageID == $MessageID)
               $UpdateCountUserIDs[] = $UserID;
            
            // Send activities to users that have not deleted the conversation
            if (!$Deleted)
               $NotifyUserIDs[] = $UserID;
         }
         
         if (!$InsertUserFound) {
            $UserConversation = array(
               'UserID' => GetValue('InsertUserID', $Fields),
               'ConversationID' => $ConversationID,
               'LastMessageID' => $LastMessageID,
               'CountReadMessages' => $CountMessages,
               'DateConversationUpdated' => $DateUpdated);
            $this->SQL->Insert('UserConversation', $UserConversation);
         }
         
         if (sizeof($UpdateCountUserIDs)) {
            $ConversationModel = new ConversationModel();
            $ConversationModel->UpdateUserUnreadCount($UpdateCountUserIDs, TRUE);
         }
         
         $this->FireEvent('AfterAdd');

         $ActivityModel = new ActivityModel();
         foreach ($NotifyUserIDs as $NotifyUserID) {
            if ($Session->UserID == $NotifyUserID)
               continue; // don't notify self.

            // Notify the users of the new message.
            $ActivityID = $ActivityModel->Add(
               $Session->UserID,
               'ConversationMessage',
               '',
               $NotifyUserID,
               '',
               "/messages/{$ConversationID}#{$MessageID}",
               FALSE
            );
            $Story = GetValue('Body', $Fields, '');
            
            if (C('Conversations.Subjects.Visible')) {
               $Story = ConcatSep("\n\n", GetValue('Subject', $Conversation, ''), $Story);
            }
            $ActivityModel->SendNotification($ActivityID, $Story);
         }
      }
      return $MessageID;
   }
347081
private function createAndPersistConversationPerson(ConversationInterface $conversation, PersonInterface $person)
    {
        $conversationPerson = $this->driver->createConversationPersonModel($conversation, $person);

        $this->driver->persistConversationPerson($conversationPerson);

        return $conversationPerson;
    }
504580
protected function makeMessage($conversationId, $message)
    {
        $message = $this->message->create([
            'message' => $message,
            'conversation_id' => $conversationId,
            'user_id' => $this->authUserId,
            'is_seen' => 0,
        ]);

        $message->conversation->touch();

        $this->broadcast->transmission($message);

        return $message;
    }
146483
public function addInteraction(Interaction $interaction, $body){
        $returnValue = false;

        if(!is_null($interaction)){
            $returnValue = $this->getBody()->setElement($interaction, $body);
        }

        return (bool) $returnValue;
    }
1284838
public function updateCustomFields(int $conversationId, $customFields): void
    {
        if ($customFields instanceof CustomFieldsCollection) {
            $customFieldsCollection = $customFields;
        } else {
            if ($customFields instanceof Collection) {
                $customFields = $customFields->toArray();
            }

            $customFieldsCollection = new CustomFieldsCollection();
            $customFieldsCollection->setCustomFields($customFields);
        }

        $this->restClient->updateResource(
            $customFieldsCollection,
            sprintf('/v2/conversations/%d/fields', $conversationId)
        );
    }
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();      
   }
686196
public function send($entityId, $text, $userIds, $emails)
    {
        $messageData = $this->buildMessageData($text, $entityId);

        return $this->callSendMessage($userIds, $emails, $messageData);
    }
528276
public static function delete_conversations_by_id($userid, array $conversationids) {
        global $CFG;

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

        // Validate params.
        $params = [
            'userid' => $userid,
            'conversationids' => $conversationids,
        ];
        $params = self::validate_parameters(self::delete_conversations_by_id_parameters(), $params);

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

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

        foreach ($params['conversationids'] as $conversationid) {
            if (\core_message\api::can_delete_conversation($user->id, $conversationid)) {
                \core_message\api::delete_conversation_by_id($user->id, $conversationid);
            } else {
                throw new moodle_exception("You do not have permission to delete the conversation '$conversationid'");
            }
        }

        return [];
    }
99097
public static function reply($discussionId, $userId, $oldTitle, $newTitle)
    {
        $post = new static;

        $post->content = static::buildContent($oldTitle, $newTitle);
        $post->created_at = Carbon::now();
        $post->discussion_id = $discussionId;
        $post->user_id = $userId;

        return $post;
    }