Creates a new chat with the current userr and another participant.

@param array $users
@param int $public
@return null|string
976979
public function create(array $users, int $public = 0): ?string
  {
    if ( $this->check() ){
      $join = '';
      $where = '';
      $values = [$this->user->get_id(), $public];
      foreach ( $users as $i => $u ){
        $join .= "JOIN bbn_chats_users AS u$i ON u$i.id_chat = bbn_chats.id".PHP_EOL;
        $where .= "AND u$i.id_user = ?".PHP_EOL;
        $values[] = $u;
      }
      $sql = <<<SQL
SELECT id
FROM bbn_chats
  $join
WHERE creator = ?
AND public = ? 
$where
SQL;
      if ( ($id_chat = $this->db->get_one($sql, $values)) && (count($users) === $this->db->count('bbn_chat_users', ['id_chat' => $id_chat])) ){
        return $id_chat;
      }
      if ( $this->db->insert('bbn_chats', [
        'creator' => $this->user->get_id(),
        'creation' => date('Y-m-d H:i:s'),
        'public' => $public ? 1 : 0
      ]) ){
        $id_chat = $this->db->last_id();
        $this->db->insert('bbn_chats_users', [
          'id_chat' => $id_chat,
          'id_user' => $this->user->get_id(),
          'entrance' => microtime(true),
          'admin' => 1
        ]);
        foreach ( $users as $user ){
          $this->db->insert_ignore('bbn_chats_users', [
            'id_chat' => $id_chat,
            'id_user' => $user,
            'entrance' => microtime(true),
            'admin' => 0
          ]);
        }
        return $id_chat;
      }
    }
    return null;
  }
493902
public function addCallbacks($name, array $events, array $users = []) {
        // Default priority
        $defaultPriority = 0;

        foreach ($events as $event => $callback) {
            if (!isset($this->callbacks[$event])) {
                // Create a priority queue for this event
                $this->callbacks[$event] = new PriorityQueue();
            }

            if (is_string($callback)) {
                // 'eventName' => 'someMethod'
                $this->callbacks[$event]->insert([
                    'handler' => $name,
                    'method' => $callback,
                    'users' => $users,
                ], $defaultPriority);
            } else if (is_array($callback)) {
                // 'eventName' => [ ... ]
                foreach ($callback as $method => $priority) {
                    if (is_int($method)) {
                        // 'eventName' => ['someMethod', ...]
                        $method = $priority;
                        $priority = $defaultPriority;
                    }

                    $this->callbacks[$event]->insert([
                        'handler' => $name,
                        'method' => $method,
                        'users' => $users,
                    ], $priority);
                }
            } else if (is_int($callback)) {
                // We have a closure as a callback, so $callback is the actual priority
                $this->callbacks[$event]->insert([
                    'handler' => $name,
                    'users' => $users,
                ], $callback);
            } else {
                throw new InvalidArgumentException('Invalid event definition for listener: ' . $name, 500);
            }
        }

        return $this;
    }
811274
public function create($chatid, $name, $owner, $userlist)
    {
        $params = array(
            'chatid' => $chatid,
            'name' => $name,
            'owner' => $owner,
            'userlist' => $userlist
        );

        $response = $this->http->jsonPost(self::API_CREATE, $params);

        return $response;
    }
207817
public function createMessage($userName, $subject, $textBody, $action, $pmId)
    {

        $this->debug('createMessage');
        $receivers = array();
        $success = true;
        $error = "";

        if ($action == 1) {
            $oldPm = $this->messageManager->find($pmId);
            $userName[] = $oldPm->getSender()->getUsername();
            $userName = array_unique($userName);
        } else if ($action == 2) {
            $oldPm = $this->messageManager->find($pmId);
            $textBody .= "[quote]" . $oldPm->getMessage() . "[/quote]";
        }

        foreach ($userName as $currUserName) {
            $user = $this->userManager->findByUsername($currUserName);
            if ($user) {
                $receivers[$user->getId()] = $user;
            } else {
                $success = false;
                $error = "User not found";
                break;
            }
        }

        $id = 0;

        if ($success) {
            $errors = array();
            $this->debug("Tapatalk: sendMessage");
            $message = $this->messageManager->sendMessage($subject, $textBody, $receivers, $errors);

            if (!empty($errors)) {
                $error = implode(', ', $errors);
                $success = false;
            } else {
                $id = $message->getId();
            }
        }

        $result['result'] = new \Zend\XmlRpc\Value\Boolean($success);
        if (!empty($error)) {
            $result['result_text'] = new \Zend\XmlRpc\Value\Base64($error);
        }
        $result['msg_id'] = new \Zend\XmlRpc\Value\String($id);

        $response = $this->getResponse($result, 'struct');

        return $response;
    }
1013412
public function removeUsers($users)
    {
        if (is_array($users)) {
            foreach ($users as $id) {
                $this->users()->detach($id);
            }

            return $this;
        }

        $this->users()->detach($users);

        return $this;
    }
973427
public function addMyFriends(Collection $users)
    {
        foreach ($users as $user) {
            $this->addMyFriend($user);
        }

        return $this;
    }
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);
      }
   }
1358494
public function start($participants, $data = [])
    {
        $conversation = $this->create(['data' => $data]);

        if ($participants) {
            $conversation->addParticipants($participants);
        }

        return $conversation;
    }
886722
public function userToRooms($user)
    {
        $url          = $this->url.'users/'.$user.'/joined_chatrooms';
        $option       = [];
        $access_token = $this->getToken();
        $header []    = 'Authorization: Bearer '.$access_token;

        return Http::postCurl($url, $option, $header, 'GET');
    }
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);

    }
279729
private function seedContent($languages, $users)
    {
        $date = Carbon::now();
        $user = $users->random();
        $en   = $languages['en'];
        $pl   = $languages['pl'];

        $news    = dispatch_now(CreateContent::category('News', $en, $user, ['is_active' => true, 'published_at' => $date]));
        $offer   = dispatch_now(CreateContent::category('Offer', $en, $user, ['is_active' => true, 'published_at' => $date]));
        $aboutUs = dispatch_now(CreateContent::content('About us', $en, $user, array_merge(
            ['is_active' => true, 'published_at' => $date],
            $this->generateContentTranslation($en)
        )));

        dispatch_now(new AddContentTranslation($news, 'Aktualności', $pl, $user));
        dispatch_now(new AddContentTranslation($offer, 'Oferta', $pl, $user));
        dispatch_now(new AddContentTranslation($aboutUs, 'O nas', $pl, $user, $this->generateContentTranslation($pl)));

        $contents = [$news, $offer, $aboutUs];

        for ($i = 0; $i < self::RANDOM_CONTENTS; $i++) {
            $contents[] = $this->seedRandomContent('content', $news, $languages, $users);
            $contents[] = $this->seedRandomContent('content', $offer, $languages, $users);
        }

        return $contents;
    }
349463
public function updateWithUsers(array $data, $users, $id)
    {
        $role = $this->update((array) $data, $id);

        if (! empty($users)) {
            $role->users()->sync($users);
        } else {
            $role->users()->detach();
        }
    }
21969
public function publicUpdate($user, Message $message)
    {
        if ($message->user_id == $user->id || $message->admin_id == $user->id) {
            return User::findOrFail($user->id)->hasPermission('laralum::tickets.messages.update-public');
        }

        return false;
    }
563509
public function removeMembersFromGroupConversation($groupConversationId, array $users)
    {
        $group = $this->find($groupConversationId);

        if ($group) {
            $group->users()->detach($users);

            return true;
        }

        return false;
    }
850062
public function threadsAll($user, $offset, $take)
    {
        $msgThread = Conversation::with(
            [
                'messages' => function ($q) use ($user) {
                    return $q->latest();
                }, 'userone', 'usertwo'
            ]
        )
            ->where('user_one', $user)->orWhere('user_two', $user)->offset($offset)->take($take)->get();

        $threads = [];

        foreach ($msgThread as $thread) {
            $conversationWith = ($thread->userone->id == $user) ? $thread->usertwo : $thread->userone;
            $message = $thread->messages->first();
            $message->user = $conversationWith;
            $threads[] = $message;
        }

        return collect($threads);
    }
843400
public function startConversationWith($firstUserId, $secondUserId)
    {
        $created = $this->query()->create([
            'first_user_id'  => $firstUserId,
            'second_user_id' => $secondUserId,
        ]);

        if ($created) {
            return true;
        }

        return false;
    }
1208266
public static function get_self_conversation(int $userid) {
        global $DB;

        $conditions = [
            'type' => self::MESSAGE_CONVERSATION_TYPE_SELF,
            'convhash' => helper::get_conversation_hash([$userid])
        ];
        return $DB->get_record('message_conversations', $conditions);
    }