ConversationModel::save PHP Метод

save() публичный Метод

Save conversation from form submission.
public save ( array $formPostValues, array $settings = [] ) : integer
$formPostValues array Values submitted via form.
$settings array Not used.
Результат integer Unique ID of conversation created or updated.
    public function save($formPostValues, $settings = [])
    {
        if ($settings instanceof ConversationMessageModel) {
            deprecated('ConversationModel->save(array, ConversationMessageModel)');
            $MessageModel = $settings;
        } else {
            $MessageModel = ConversationMessageModel::instance();
        }
        // Define the primary key in this model's table.
        $this->defineSchema();
        $MessageModel->defineSchema();
        $this->EventArguments['FormPostValues'] = $formPostValues;
        $this->fireEvent('BeforeSaveValidation');
        if (!val('RecipientUserID', $formPostValues) && isset($formPostValues['To'])) {
            $To = explode(',', $formPostValues['To']);
            $To = array_map('trim', $To);
            $RecipientUserIDs = $this->SQL->select('UserID')->from('User')->whereIn('Name', $To)->get()->resultArray();
            $RecipientUserIDs = array_column($RecipientUserIDs, 'UserID');
            $formPostValues['RecipientUserID'] = $RecipientUserIDs;
        }
        if (c('Garden.ForceInputFormatter')) {
            $formPostValues['Format'] = c('Garden.InputFormatter');
        }
        // Add & apply any extra validation rules:
        $this->Validation->applyRule('Body', 'Required');
        $MessageModel->Validation->applyRule('Body', 'Required');
        // Make sure that there is at least one recipient
        $this->Validation->addRule('OneOrMoreArrayItemRequired', 'function:ValidateOneOrMoreArrayItemRequired');
        $this->Validation->applyRule('RecipientUserID', 'OneOrMoreArrayItemRequired');
        // Add insert/update fields
        $this->addInsertFields($formPostValues);
        $this->addUpdateFields($formPostValues);
        // Validate the form posted values
        $ConversationID = false;
        if ($this->validate($formPostValues) && $MessageModel->validate($formPostValues) && !$this->checkForSpam('Conversation')) {
            $Fields = $this->Validation->validationFields();
            // All fields on the form that relate to the schema
            // Define the recipients, and make sure that the sender is in the list
            $RecipientUserIDs = val('RecipientUserID', $Fields, 0);
            if (!in_array($formPostValues['InsertUserID'], $RecipientUserIDs)) {
                $RecipientUserIDs[] = $formPostValues['InsertUserID'];
            }
            // Also make sure there are no duplicates in the recipient list
            $RecipientUserIDs = array_unique($RecipientUserIDs);
            sort($RecipientUserIDs);
            $Fields = $this->Validation->schemaValidationFields();
            // All fields on the form that relate to the schema
            $ConversationID = $this->SQL->insert($this->Name, $Fields);
            $formPostValues['ConversationID'] = $ConversationID;
            // Notify the message model that it's being called as a direct result
            // of a new conversation being created. As of now, this is being used
            // so that spam checks between new conversations and conversation
            // messages each have a separate counter. Without this, a new
            // conversation will cause itself AND the message model spam counter
            // to increment by 1.
            $MessageID = $MessageModel->save($formPostValues, null, array('NewConversation' => true));
            $this->SQL->update('Conversation')->set('FirstMessageID', $MessageID)->where('ConversationID', $ConversationID)->put();
            // Now that the message & conversation have been inserted, insert all of the recipients
            foreach ($RecipientUserIDs as $UserID) {
                $CountReadMessages = $UserID == $formPostValues['InsertUserID'] ? 1 : 0;
                $this->SQL->options('Ignore', true)->insert('UserConversation', array('UserID' => $UserID, 'ConversationID' => $ConversationID, 'LastMessageID' => $MessageID, 'CountReadMessages' => $CountReadMessages, 'DateConversationUpdated' => $formPostValues['DateUpdated']));
            }
            // And update the CountUnreadConversations count on each user related to the discussion.
            $this->updateUserUnreadCount(array_diff($RecipientUserIDs, array($formPostValues['InsertUserID'])));
            $this->updateParticipantCount($ConversationID);
            $body = val('Body', $formPostValues, '');
            $subject = val('Subject', $Fields, '');
            $this->EventArguments['Recipients'] = $RecipientUserIDs;
            $Conversation = $this->getID($ConversationID);
            $this->EventArguments['Conversation'] = $Conversation;
            $Message = $MessageModel->getID($MessageID, DATASET_TYPE_ARRAY);
            $this->EventArguments['Message'] = $Message;
            $this->EventArguments['Body'] =& $body;
            $this->EventArguments['Subject'] =& $subject;
            $this->fireEvent('AfterAdd');
            // Add notifications (this isn't done by the conversationmessagemodule
            // because the conversation has not yet been created at the time they are
            // inserted)
            $UnreadData = $this->SQL->select('uc.UserID')->from('UserConversation uc')->where('uc.ConversationID', $ConversationID)->where('uc.UserID <>', $formPostValues['InsertUserID'])->get();
            $Activity = array('ActivityType' => 'ConversationMessage', 'ActivityUserID' => $formPostValues['InsertUserID'], 'HeadlineFormat' => t('HeadlineFormat.ConversationMessage', '{ActivityUserID,User} sent you a <a href="{Url,html}">message</a>'), 'RecordType' => 'Conversation', 'RecordID' => $ConversationID, 'Story' => $body, 'ActionText' => t('Reply'), 'Format' => val('Format', $formPostValues, c('Garden.InputFormatter')), 'Route' => "/messages/{$ConversationID}#Message_{$MessageID}");
            if ($subject) {
                $Activity['Story'] = sprintf(t('Re: %s'), $subject) . '<br>' . $body;
            }
            $ActivityModel = new ActivityModel();
            foreach ($UnreadData->result() as $User) {
                $Activity['NotifyUserID'] = $User->UserID;
                $ActivityModel->queue($Activity, 'ConversationMessage');
            }
            $ActivityModel->saveQueue();
        } else {
            // Make sure that all of the validation results from both validations are present for view by the form
            foreach ($MessageModel->validationResults() as $FieldName => $Results) {
                foreach ($Results as $Result) {
                    $this->Validation->addValidationResult($FieldName, $Result);
                }
            }
        }
        return $ConversationID;
    }

Usage Example

Пример #1
0
 /**
  *
  *
  * @return bool
  * @throws Exception
  * @throws Gdn_UserException
  */
 public function commit()
 {
     if (is_null($this->Type)) {
         throw new Exception(T("Adding a Regarding event requires a type."));
     }
     if (is_null($this->ForeignType)) {
         throw new Exception(T("Adding a Regarding event requires a foreign association type."));
     }
     if (is_null($this->ForeignID)) {
         throw new Exception(T("Adding a Regarding event requires a foreign association id."));
     }
     if (is_null($this->Comment)) {
         throw new Exception(T("Adding a Regarding event requires a comment."));
     }
     if (is_null($this->UserID)) {
         $this->UserID = Gdn::session()->UserID;
     }
     $RegardingModel = new RegardingModel();
     $CollapseMode = c('Garden.Regarding.AutoCollapse', true);
     $Collapse = false;
     if ($CollapseMode) {
         // Check for an existing report of this type
         $ExistingRegardingEntity = $RegardingModel->getRelated($this->Type, $this->ForeignType, $this->ForeignID);
         if ($ExistingRegardingEntity) {
             $Collapse = true;
             $RegardingID = val('RegardingID', $ExistingRegardingEntity);
         }
     }
     if (!$Collapse) {
         // Create a new Regarding entry
         $RegardingPreSend = array('Type' => $this->Type, 'ForeignType' => $this->ForeignType, 'ForeignID' => $this->ForeignID, 'InsertUserID' => $this->UserID, 'DateInserted' => date('Y-m-d H:i:s'), 'ParentType' => $this->ParentType, 'ParentID' => $this->ParentID, 'ForeignURL' => $this->ForeignURL, 'Comment' => $this->Comment, 'OriginalContent' => $this->OriginalContent, 'Reports' => 1);
         $RegardingID = $RegardingModel->save($RegardingPreSend);
         if (!$RegardingID) {
             return false;
         }
     }
     // Handle collaborations
     // Don't error on foreach
     if (!is_array($this->CollaborativeActions)) {
         $this->CollaborativeActions = array();
     }
     foreach ($this->CollaborativeActions as $Action) {
         $ActionType = val('Type', $Action);
         switch ($ActionType) {
             case 'discussion':
                 $DiscussionModel = new DiscussionModel();
                 if ($Collapse) {
                     $Discussion = Gdn::SQL()->select('*')->from('Discussion')->where(array('RegardingID' => $RegardingID))->get()->firstRow(DATASET_TYPE_ARRAY);
                 }
                 if (!$Collapse || !$Discussion) {
                     $CategoryID = val('Parameters', $Action);
                     // Make a new discussion
                     $DiscussionID = $DiscussionModel->save(array('Name' => $this->CollaborativeTitle, 'CategoryID' => $CategoryID, 'Body' => $this->OriginalContent, 'InsertUserID' => val('InsertUserID', $this->SourceElement), 'Announce' => 0, 'Close' => 0, 'RegardingID' => $RegardingID));
                     if (!$DiscussionID) {
                         throw new Gdn_UserException($DiscussionModel->Validation->resultsText());
                     }
                     $DiscussionModel->updateDiscussionCount($CategoryID);
                 } else {
                     // Add a comment to the existing discussion.
                     $CommentModel = new CommentModel();
                     $CommentID = $CommentModel->save(array('DiscussionID' => val('DiscussionID', $Discussion), 'Body' => $this->Comment, 'InsertUserID' => $this->UserID));
                     $CommentModel->save2($CommentID, true);
                 }
                 break;
             case 'conversation':
                 $ConversationModel = new ConversationModel();
                 $ConversationMessageModel = new ConversationMessageModel();
                 $Users = val('Parameters', $Action);
                 $UserList = explode(',', $Users);
                 if (!sizeof($UserList)) {
                     throw new Exception(sprintf(T("The userlist provided for collaboration on '%s:%s' is invalid.", $this->Type, $this->ForeignType)));
                 }
                 $ConversationID = $ConversationModel->save(array('To' => 'Admins', 'Body' => $this->CollaborativeTitle, 'RecipientUserID' => $UserList, 'RegardingID' => $RegardingID), $ConversationMessageModel);
                 break;
         }
     }
     return true;
 }