/**
  * Save message from form submission.
  * 
  * @since 2.0.0
  * @access public
  *
  * @param array $FormPostValues Values submitted via form.
  * @return int Unique ID of message created or updated.
  */
 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);
     // 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'));
         $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);
         }
         // 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);
         }
         $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;
 }
Example #2
0
 public function Save2($CommentID, $Insert, $CheckExisting = TRUE)
 {
     $Fields = $this->GetID($CommentID, DATASET_TYPE_ARRAY);
     $Session = Gdn::Session();
     // Make a quick check so that only the user making the comment can make the notification.
     // This check may be used in the future so should not be depended on later in the method.
     if ($Fields['InsertUserID'] != $Session->UserID) {
         return;
     }
     $DiscussionModel = new DiscussionModel();
     $DiscussionID = ArrayValue('DiscussionID', $Fields);
     $Discussion = $DiscussionModel->GetID($DiscussionID);
     if ($Insert) {
         // Notify any users who were mentioned in the comment
         $Usernames = GetMentions($Fields['Body']);
         $UserModel = Gdn::UserModel();
         $Story = ArrayValue('Body', $Fields, '');
         $NotifiedUsers = array();
         foreach ($Usernames as $Username) {
             $User = $UserModel->GetByUsername($Username);
             if ($User && $User->UserID != $Session->UserID) {
                 $NotifiedUsers[] = $User->UserID;
                 $ActivityModel = new ActivityModel();
                 $ActivityID = $ActivityModel->Add($Session->UserID, 'CommentMention', Anchor(Gdn_Format::Text($Discussion->Name), 'discussion/comment/' . $CommentID . '/#Comment_' . $CommentID), $User->UserID, '', 'discussion/comment/' . $CommentID . '/#Comment_' . $CommentID, FALSE);
                 $ActivityModel->SendNotification($ActivityID, $Story);
             }
         }
         // Notify users who have bookmarked the discussion
         $BookmarkData = $DiscussionModel->GetBookmarkUsers($DiscussionID);
         foreach ($BookmarkData->Result() as $Bookmark) {
             if (!in_array($Bookmark->UserID, $NotifiedUsers) && $Bookmark->UserID != $Session->UserID) {
                 $NotifiedUsers[] = $Bookmark->UserID;
                 $ActivityModel = new ActivityModel();
                 $ActivityID = $ActivityModel->Add($Session->UserID, 'BookmarkComment', Anchor(Gdn_Format::Text($Discussion->Name), 'discussion/comment/' . $CommentID . '/#Comment_' . $CommentID), $Bookmark->UserID, '', 'discussion/comment/' . $CommentID . '/#Comment_' . $CommentID, FALSE);
                 $ActivityModel->SendNotification($ActivityID, $Story);
             }
         }
         // Record user-comment activity
         if ($Discussion !== FALSE && !in_array($Session->UserID, $NotifiedUsers)) {
             $this->RecordActivity($Discussion, $Session->UserID, $CommentID, 'Only');
         }
     }
     $this->UpdateCommentCount($DiscussionID);
     // Mark the comment read (note: add 1 to $Discussion->CountComments because this comment has been added since $Discussion was loaded)
     $this->SetWatch($Discussion, $Discussion->CountComments, $Discussion->CountComments + 1, $Discussion->CountComments + 1);
     // Update the discussion author's CountUnreadDiscussions (ie.
     // the number of discussions created by the user that s/he has
     // unread messages in) if this comment was not added by the
     // discussion author.
     $Data = $this->SQL->Select('d.InsertUserID')->Select('d.DiscussionID', 'count', 'CountDiscussions')->From('Discussion d')->Join('Comment c', 'd.DiscussionID = c.DiscussionID')->Join('UserDiscussion w', 'd.DiscussionID = w.DiscussionID and w.UserID = d.InsertUserID')->Where('w.CountComments >', 0)->Where('c.InsertUserID', $Session->UserID)->Where('c.InsertUserID <>', 'd.InsertUserID', TRUE, FALSE)->GroupBy('d.InsertUserID')->Get();
     if ($Data->NumRows() > 0) {
         $UserData = $Data->FirstRow();
         $this->SQL->Update('User')->Set('CountUnreadDiscussions', $UserData->CountDiscussions)->Where('UserID', $UserData->InsertUserID)->Put();
     }
     $this->UpdateUser($Session->UserID);
 }
 /**
  * Save conversation from form submission.
  * 
  * @since 2.0.0
  * @access public
  *
  * @param array $FormPostValues Values submitted via form.
  * @param object $MessageModel Message starting the conversation.
  * @return int Unique ID of conversation created or updated.
  */
 public function Save($FormPostValues, $MessageModel)
 {
     $Session = Gdn::Session();
     // Define the primary key in this model's table.
     $this->DefineSchema();
     $MessageModel->DefineSchema();
     if (!GetValue('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();
         $RecipientUserIDs = ConsolidateArrayValuesByKey($RecipientUserIDs, 'UserID');
         $FormPostValues['RecipientUserID'] = $RecipientUserIDs;
     }
     // 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)) {
         $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 = GetValue('RecipientUserID', $Fields, 0);
         if (!in_array($Session->UserID, $RecipientUserIDs)) {
             $RecipientUserIDs[] = $Session->UserID;
         }
         // 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
         $Fields['Contributors'] = Gdn_Format::Serialize($RecipientUserIDs);
         $ConversationID = $this->SQL->Insert($this->Name, $Fields);
         $FormPostValues['ConversationID'] = $ConversationID;
         $MessageID = $MessageModel->Save($FormPostValues);
         $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 == $Session->UserID ? 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($RecipientUserIDs, TRUE);
         // 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 <>', $Session->UserID)->Get();
         $ActivityModel = new ActivityModel();
         foreach ($UnreadData->Result() as $User) {
             // Notify the users of the new message.
             $ActivityID = $ActivityModel->Add($Session->UserID, 'ConversationMessage', '', $User->UserID, '', "/messages/{$ConversationID}#{$MessageID}", FALSE);
             $Story = ArrayValue('Body', $FormPostValues, '');
             $ActivityModel->SendNotification($ActivityID, $Story);
         }
     } 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;
 }
 public function Save($FormPostValues)
 {
     $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);
     // 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
         $MessageID = $this->SQL->Insert($this->Name, $Fields);
         $ConversationID = ArrayValue('ConversationID', $Fields, 0);
         $Px = $this->SQL->Database->DatabasePrefix;
         // 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
         $this->SQL->Update('Conversation c')->History()->Set('CountMessages', $CountMessages)->Set('LastMessageID', $LastMessageID)->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.CountReadMessages', "case uc.UserID when {$Session->UserID} then {$CountMessages} else uc.CountReadMessages end", FALSE)->Where('uc.ConversationID', $ConversationID)->Where('uc.Deleted', '0')->Where('uc.CountReadMessages', $CountMessages - 1)->Put();
         // Incrememnt the users' inbox counts.
         $this->SQL->Update('User u')->Join('UserConversation uc', 'u.UserID = uc.UserID')->Set('u.CountUnreadConversations', 'coalesce(u.CountUnreadConversations, 0) + 1', FALSE)->Where('uc.ConversationID', $ConversationID)->Where('uc.LastMessageID', $MessageID)->Where('uc.UserID <>', $Session->UserID)->Put();
         // Grab the users that need to be notified.
         $UnreadData = $this->SQL->Select('uc.UserID')->From('UserConversation uc')->Where('uc.ConversationID', $ConversationID)->Where('uc.LastMessageID', $MessageID)->Where('uc.UserID <>', $Session->UserID)->Get();
         $ActivityModel = new ActivityModel();
         foreach ($UnreadData->Result() as $User) {
             // Notify the users of the new message.
             $ActivityID = $ActivityModel->Add($Session->UserID, 'ConversationMessage', '', $User->UserID, '', "/messages/{$ConversationID}#{$MessageID}", FALSE);
             $Story = ArrayValue('Body', $Fields, '');
             $ActivityModel->SendNotification($ActivityID, $Story);
         }
     }
     return $MessageID;
 }
Example #5
0
 public function Save($FormPostValues)
 {
     $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');
     $MaxCommentLength = Gdn::Config('Vanilla.Comment.MaxLength');
     if (is_numeric($MaxCommentLength) && $MaxCommentLength > 0) {
         $this->Validation->SetSchemaProperty('Body', 'Length', $MaxCommentLength);
         $this->Validation->ApplyRule('Body', 'Length');
     }
     $CommentID = ArrayValue('CommentID', $FormPostValues);
     $CommentID = is_numeric($CommentID) && $CommentID > 0 ? $CommentID : FALSE;
     $Insert = $CommentID === FALSE;
     if ($Insert) {
         $this->AddInsertFields($FormPostValues);
     } else {
         $this->AddUpdateFields($FormPostValues);
     }
     // Validate the form posted values
     if ($this->Validate($FormPostValues, $Insert)) {
         // If the post is new and it validates, check for spam
         if (!$Insert || !$this->CheckForSpam('Comment')) {
             $Fields = $this->Validation->SchemaValidationFields();
             $Fields = RemoveKeyFromArray($Fields, $this->PrimaryKey);
             $DiscussionModel = new DiscussionModel();
             $DiscussionID = ArrayValue('DiscussionID', $Fields);
             $Discussion = $DiscussionModel->GetID($DiscussionID);
             if ($Insert === FALSE) {
                 $this->SQL->Put($this->Name, $Fields, array('CommentID' => $CommentID));
             } else {
                 // Make sure that the comments get formatted in the method defined by Garden
                 $Fields['Format'] = Gdn::Config('Garden.InputFormatter', '');
                 $CommentID = $this->SQL->Insert($this->Name, $Fields);
                 $this->EventArguments['CommentID'] = $CommentID;
                 // IsNewDiscussion is passed when the first comment for new discussions are created.
                 $this->EventArguments['IsNewDiscussion'] = ArrayValue('IsNewDiscussion', $FormPostValues);
                 $this->FireEvent('AfterSaveComment');
                 // Notify any users who were mentioned in the comment
                 $Usernames = GetMentions($Fields['Body']);
                 $UserModel = Gdn::UserModel();
                 $Story = ArrayValue('Body', $Fields, '');
                 $NotifiedUsers = array();
                 foreach ($Usernames as $Username) {
                     $User = $UserModel->GetByUsername($Username);
                     if ($User && $User->UserID != $Session->UserID) {
                         $NotifiedUsers[] = $User->UserID;
                         $ActivityModel = new ActivityModel();
                         $ActivityID = $ActivityModel->Add($Session->UserID, 'CommentMention', Anchor(Gdn_Format::Text($Discussion->Name), 'discussion/comment/' . $CommentID . '/#Comment_' . $CommentID), $User->UserID, '', 'discussion/comment/' . $CommentID . '/#Comment_' . $CommentID, FALSE);
                         $ActivityModel->SendNotification($ActivityID, $Story);
                     }
                 }
                 // Notify users who have bookmarked the discussion
                 $BookmarkData = $DiscussionModel->GetBookmarkUsers($DiscussionID);
                 foreach ($BookmarkData->Result() as $Bookmark) {
                     if (!in_array($Bookmark->UserID, $NotifiedUsers) && $Bookmark->UserID != $Session->UserID) {
                         $NotifiedUsers[] = $Bookmark->UserID;
                         $ActivityModel = new ActivityModel();
                         $ActivityID = $ActivityModel->Add($Session->UserID, 'BookmarkComment', Anchor(Gdn_Format::Text($Discussion->Name), 'discussion/comment/' . $CommentID . '/#Comment_' . $CommentID), $Bookmark->UserID, '', 'discussion/comment/' . $CommentID . '/#Comment_' . $CommentID, FALSE);
                         $ActivityModel->SendNotification($ActivityID, $Story);
                     }
                 }
             }
             // Record user-comment activity
             if ($Insert === TRUE && $Discussion !== FALSE && !in_array($Session->UserID, $NotifiedUsers)) {
                 $this->RecordActivity($Discussion, $Session->UserID, $CommentID);
             }
             $this->UpdateCommentCount($DiscussionID);
             // Update the discussion author's CountUnreadDiscussions (ie.
             // the number of discussions created by the user that s/he has
             // unread messages in) if this comment was not added by the
             // discussion author.
             $Data = $this->SQL->Select('d.InsertUserID')->Select('d.DiscussionID', 'count', 'CountDiscussions')->From('Discussion d')->Join('Comment c', 'd.DiscussionID = c.DiscussionID')->Join('UserDiscussion w', 'd.DiscussionID = w.DiscussionID and w.UserID = d.InsertUserID')->Where('w.CountComments >', 0)->Where('c.InsertUserID', $Session->UserID)->Where('c.InsertUserID <>', 'd.InsertUserID', TRUE, FALSE)->GroupBy('d.InsertUserID')->Get();
             if ($Data->NumRows() > 0) {
                 $UserData = $Data->FirstRow();
                 $this->SQL->Update('User')->Set('CountUnreadDiscussions', $UserData->CountDiscussions)->Where('UserID', $UserData->InsertUserID)->Put();
             }
             $this->UpdateUser($Session->UserID);
         }
     }
     return $CommentID;
 }
 /**
  * Inserts or updates the discussion via form values.
  * 
  * Events: BeforeSaveDiscussion, AfterSaveDiscussion.
  *
  * @since 2.0.0
  * @access public
  * 
  * @param array $FormPostValues Data sent from the form model.
  * @return int $DiscussionID Unique ID of the discussion.
  */
 public function Save($FormPostValues)
 {
     $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');
     $MaxCommentLength = Gdn::Config('Vanilla.Comment.MaxLength');
     if (is_numeric($MaxCommentLength) && $MaxCommentLength > 0) {
         $this->Validation->SetSchemaProperty('Body', 'Length', $MaxCommentLength);
         $this->Validation->ApplyRule('Body', 'Length');
     }
     // Get the DiscussionID from the form so we know if we are inserting or updating.
     $DiscussionID = ArrayValue('DiscussionID', $FormPostValues, '');
     $Insert = $DiscussionID == '' ? TRUE : FALSE;
     $this->EventArguments['Insert'] = $Insert;
     if ($Insert) {
         unset($FormPostValues['DiscussionID']);
         // If no categoryid is defined, grab the first available.
         if (ArrayValue('CategoryID', $FormPostValues) === FALSE) {
             $FormPostValues['CategoryID'] = $this->SQL->Get('Category', '', '', 1)->FirstRow()->CategoryID;
         }
         $this->AddInsertFields($FormPostValues);
         // $FormPostValues['LastCommentUserID'] = $Session->UserID;
         $FormPostValues['DateLastComment'] = Gdn_Format::ToDateTime();
     }
     // Add the update fields because this table's default sort is by DateUpdated (see $this->Get()).
     $this->AddUpdateFields($FormPostValues);
     // Set checkbox values to zero if they were unchecked
     if (ArrayValue('Announce', $FormPostValues, '') === FALSE) {
         $FormPostValues['Announce'] = 0;
     }
     if (ArrayValue('Closed', $FormPostValues, '') === FALSE) {
         $FormPostValues['Closed'] = 0;
     }
     if (ArrayValue('Sink', $FormPostValues, '') === FALSE) {
         $FormPostValues['Sink'] = 0;
     }
     //	Prep and fire event
     $this->EventArguments['FormPostValues'] =& $FormPostValues;
     $this->EventArguments['DiscussionID'] = $DiscussionID;
     $this->FireEvent('BeforeSaveDiscussion');
     // Validate the form posted values
     if ($this->Validate($FormPostValues, $Insert)) {
         // If the post is new and it validates, make sure the user isn't spamming
         if (!$Insert || !$this->CheckForSpam('Discussion')) {
             // Get all fields on the form that relate to the schema
             $Fields = $this->Validation->SchemaValidationFields();
             // Get DiscussionID if one was sent
             $DiscussionID = intval(ArrayValue('DiscussionID', $Fields, 0));
             // Remove the primary key from the fields for saving
             $Fields = RemoveKeyFromArray($Fields, 'DiscussionID');
             $Discussion = FALSE;
             $StoredCategoryID = FALSE;
             if ($DiscussionID > 0) {
                 // Updating
                 $Stored = $this->GetID($DiscussionID);
                 $this->SQL->Put($this->Name, $Fields, array($this->PrimaryKey => $DiscussionID));
                 if ($Stored->CategoryID != $Fields['CategoryID']) {
                     $StoredCategoryID = $Stored->CategoryID;
                 }
             } else {
                 // Inserting
                 $Fields['Format'] = Gdn::Config('Garden.InputFormatter', '');
                 $DiscussionID = $this->SQL->Insert($this->Name, $Fields);
                 // Assign the new DiscussionID to the comment before saving
                 $FormPostValues['IsNewDiscussion'] = TRUE;
                 $FormPostValues['DiscussionID'] = $DiscussionID;
                 // Notify users of mentions
                 $DiscussionName = ArrayValue('Name', $Fields, '');
                 $Usernames = GetMentions($DiscussionName);
                 $UserModel = Gdn::UserModel();
                 foreach ($Usernames as $Username) {
                     $User = $UserModel->GetByUsername($Username);
                     if ($User && $User->UserID != $Session->UserID) {
                         AddActivity($Session->UserID, 'DiscussionMention', '', $User->UserID, '/discussion/' . $DiscussionID . '/' . Gdn_Format::Url($DiscussionName));
                     }
                 }
                 // Notify any users who were mentioned in the comment
                 $DiscussionName = ArrayValue('Name', $Fields, '');
                 $Story = ArrayValue('Body', $Fields, '');
                 $Usernames = GetMentions($Story);
                 $NotifiedUsers = array();
                 foreach ($Usernames as $Username) {
                     $User = $UserModel->GetByUsername($Username);
                     if ($User && $User->UserID != $Session->UserID) {
                         $NotifiedUsers[] = $User->UserID;
                         $ActivityModel = new ActivityModel();
                         $ActivityID = $ActivityModel->Add($Session->UserID, 'CommentMention', Anchor(Gdn_Format::Text($DiscussionName), '/discussion/' . $DiscussionID . '/' . Gdn_Format::Url($DiscussionName), FALSE), $User->UserID, '', '/discussion/' . $DiscussionID . '/' . Gdn_Format::Url($DiscussionName), FALSE);
                         $ActivityModel->SendNotification($ActivityID, $Story);
                     }
                 }
                 $this->RecordActivity($Session->UserID, $DiscussionID, $DiscussionName);
             }
             // Get CategoryID of this discussion
             $Data = $this->SQL->Select('CategoryID')->From('Discussion')->Where('DiscussionID', $DiscussionID)->Get();
             $CategoryID = FALSE;
             if ($Data->NumRows() > 0) {
                 $CategoryID = $Data->FirstRow()->CategoryID;
             }
             // Update discussion counter for affected categories
             $this->UpdateDiscussionCount($CategoryID);
             if ($StoredCategoryID) {
                 $this->UpdateDiscussionCount($StoredCategoryID);
             }
             // Fire an event that the discussion was saved.
             $this->EventArguments['FormPostValues'] = $FormPostValues;
             $this->EventArguments['Fields'] = $Fields;
             $this->EventArguments['DiscussionID'] = $DiscussionID;
             $this->FireEvent('AfterSaveDiscussion');
         }
     }
     return $DiscussionID;
 }
 public function Save($FormPostValues)
 {
     $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);
     // 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
         $MessageID = $this->SQL->Insert($this->Name, $Fields);
         $ConversationID = ArrayValue('ConversationID', $Fields, 0);
         // Update the conversation's DateUpdated field
         $this->SQL->Update('Conversation')->Set('DateUpdated', Gdn_Format::ToDateTime())->Set('UpdateUserID', $Session->UserID)->Where('ConversationID', $ConversationID)->Put();
         // NOTE: INCREMENTING COUNTS INSTEAD OF GETTING ACTUAL COUNTS COULD
         // BECOME A PROBLEM. WATCH FOR IT.
         // Update the message counts for all users in the conversation
         $this->SQL->Update('UserConversation')->Set('CountMessages', 'CountMessages + 1', FALSE)->Where('ConversationID', $ConversationID)->Put();
         $this->SQL->Update('UserConversation')->Set('CountNewMessages', 'CountNewMessages + 1', FALSE)->Where('ConversationID', $ConversationID)->Where('UserID <>', $Session->UserID)->Put();
         // Update the userconversation records to reflect the most recently
         // added message for all users other than the one that added the
         // message (otherwise they would see their name/message on the
         // conversation list instead of the person they are conversing with).
         $this->SQL->Update('UserConversation')->Set('LastMessageID', $MessageID)->Where('ConversationID', $ConversationID)->Where('UserID <>', $Session->UserID)->Put();
         // Update the CountUnreadConversations count on each user related to the discussion.
         // And notify the users of the new message
         $UnreadData = $this->SQL->Select('c.UserID')->Select('c2.CountNewMessages', 'count', 'CountUnreadConversations')->From('UserConversation c')->Join('UserConversation c2', 'c.UserID = c2.UserID')->Where('c2.CountNewMessages >', 0)->Where('c.ConversationID', $ConversationID)->Where('c.UserID <>', $Session->UserID)->GroupBy('c.UserID')->Get();
         $ActivityModel = new ActivityModel();
         foreach ($UnreadData->Result() as $User) {
             // Update the CountUnreadConversations count on each user related to the discussion.
             $this->SQL->Update('User')->Set('CountUnreadConversations', $User->CountUnreadConversations)->Where('UserID', $User->UserID)->Put();
             // And notify the users of the new message
             $ActivityID = $ActivityModel->Add($Session->UserID, 'ConversationMessage', '', $User->UserID, '', '/messages/' . $ConversationID . '#' . $MessageID, FALSE);
             $Story = ArrayValue('Body', $Fields, '');
             $ActivityModel->SendNotification($ActivityID, $Story);
         }
     }
     return $MessageID;
 }