public function preSave() { $result = parent::preSave(); if (!isset($this->id)) { $fromUser = new UserModel((array) $result['from_user_info']); $toUser = new UserModel((array) $result['to_user_info']); $isGuest = !$fromUser->hasRole('OPERATOR'); $guestInTalk = false; $lastMessages = $this->getUserLastMessages($this->from_id, $this->to_id, $isGuest); $lastMessage = null; // Group message into a talk if (empty($lastMessages)) { $this->talk_id = $this->generateTalkId(); } else { $lastMessage = end($lastMessages); if ($isGuest) { // Continue the current talk $this->talk_id = $lastMessage->talk_id; } else { if (!$toUser->hasRole('OPERATOR')) { // Check if guest is already talking with an operator foreach ($lastMessages as $msg) { if ($msg->to_id == $this->to_id) { $guestInTalk = true; if ($msg->from_id == $this->from_id) { $lastMessage = $msg; $this->talk_id = $msg->talk_id; } } else { if ($msg->to_id == self::TALK_ID_ALL) { $lastMessage = $msg; $this->talk_id = $msg->talk_id; } } } } if ($this->talk_id == self::TALK_ID_ALL) { $this->talk_id = $this->generateTalkId(); } } } // Assign talk to an operator if ($this->to_id != self::TALK_ID_CANCELLED && !($fromUser->hasRole('OPERATOR') && $toUser->hasRole('OPERATOR'))) { // Assign message to talk's operator, if any if ($this->to_id == self::TALK_ID_ALL && $lastMessage->to_id != self::TALK_ID_ALL) { if ($lastMessage->from_id == $this->from_id) { $this->to_id = $lastMessage->to_id; $this->to_user_info = $lastMessage->to_user_info; } else { if ($lastMessage->to_id === $this->from_id) { $this->to_id = $lastMessage->from_id; $this->to_user_info = $lastMessage->from_user_info; } } } else { if (!$isGuest) { if ($lastMessage) { if ($lastMessage->to_id == self::TALK_ID_ALL || $lastMessage->talk_id == $this->talk_id) { $operator = $fromUser; $guest = $toUser; // Assign operator to messages in the talk and mark the messages as read self::$db->execute('UPDATE ' . $this->getTableName() . ' SET to_id = ?, is_new = ? WHERE from_id = ? AND (to_id = ? OR to_id = ?) AND talk_id = ?', array($operator->id, 'n', $guest->id, self::TALK_ID_ALL, $operator->id, $this->talk_id)); } else { if ($guestInTalk) { $this->to_id = self::TALK_ID_CANCELLED; $this->id = self::CANCEL_SAVE_ID; } } } } } } // Encode from/to users data $result = $this->getData(); if ($result['from_user_info'] !== self::USER_INFO_ALL) { $result['from_user_info'] = json_encode($result['from_user_info']); } if ($result['to_user_info'] !== self::USER_INFO_ALL) { $result['to_user_info'] = json_encode($result['to_user_info']); } } // Store current time for new messages if (!isset($this->id)) { $result['datetime'] = date('Y-m-d H:i:s'); } return $result; }
public function preSave() { $result = parent::preSave(); if (isset($result['roles'])) { $result['roles'] = implode(',', $result['roles']); } if (isset($result['info'])) { $result['info'] = json_encode($result['info']); } return $result; }