CommentModel::save2 PHP Méthode

save2() public méthode

Updates unread comment totals, bookmarks, and activity. Sends notifications.
Since: 2.0.0
public save2 ( array $CommentID, integer $Insert, boolean $CheckExisting = true, boolean $IncUser = false )
$CommentID array Unique ID for this comment.
$Insert integer Used as a boolean for whether this is a new comment.
$CheckExisting boolean Not used.
$IncUser boolean Whether or not to just increment the user's comment count rather than recalculate it.
    public function save2($CommentID, $Insert, $CheckExisting = true, $IncUser = false)
    {
        $Session = Gdn::session();
        $discussionModel = new DiscussionModel();
        // Load comment data
        $Fields = $this->getID($CommentID, DATASET_TYPE_ARRAY);
        // Clear any session stashes related to this discussion
        $DiscussionModel = new DiscussionModel();
        $DiscussionID = val('DiscussionID', $Fields);
        $Discussion = $DiscussionModel->getID($DiscussionID);
        $Session->setPublicStash('CommentForForeignID_' . GetValue('ForeignID', $Discussion), null);
        // 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 (Gdn::controller()->deliveryType() === DELIVERY_TYPE_ALL && $Fields['InsertUserID'] != $Session->UserID) {
            return;
        }
        // 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.
        $this->UpdateUser($Fields['InsertUserID'], $IncUser && $Insert);
        // Mark the user as participated.
        $this->SQL->replace('UserDiscussion', array('Participated' => 1), array('DiscussionID' => $DiscussionID, 'UserID' => val('InsertUserID', $Fields)));
        if ($Insert) {
            // UPDATE COUNT AND LAST COMMENT ON CATEGORY TABLE
            if ($Discussion->CategoryID > 0) {
                $Category = CategoryModel::categories($Discussion->CategoryID);
                if ($Category) {
                    $CountComments = val('CountComments', $Category, 0) + 1;
                    if ($CountComments < self::COMMENT_THRESHOLD_SMALL || $CountComments < self::COMMENT_THRESHOLD_LARGE && $CountComments % self::COUNT_RECALC_MOD == 0) {
                        $CountComments = $this->SQL->select('CountComments', 'sum', 'CountComments')->from('Discussion')->where('CategoryID', $Discussion->CategoryID)->get()->firstRow()->CountComments;
                    }
                }
                $CategoryModel = new CategoryModel();
                $CategoryModel->setField($Discussion->CategoryID, array('LastDiscussionID' => $DiscussionID, 'LastCommentID' => $CommentID, 'CountComments' => $CountComments, 'LastDateInserted' => $Fields['DateInserted']));
                // Update the cache.
                $CategoryCache = array('LastTitle' => $Discussion->Name, 'LastUserID' => $Fields['InsertUserID'], 'LastUrl' => DiscussionUrl($Discussion) . '#latest');
                CategoryModel::SetCache($Discussion->CategoryID, $CategoryCache);
            }
            // Prepare the notification queue.
            $ActivityModel = new ActivityModel();
            $HeadlineFormat = t('HeadlineFormat.Comment', '{ActivityUserID,user} commented on <a href="{Url,html}">{Data.Name,text}</a>');
            $Category = CategoryModel::categories($Discussion->CategoryID);
            $Activity = array('ActivityType' => 'Comment', 'ActivityUserID' => $Fields['InsertUserID'], 'HeadlineFormat' => $HeadlineFormat, 'RecordType' => 'Comment', 'RecordID' => $CommentID, 'Route' => "/discussion/comment/{$CommentID}#Comment_{$CommentID}", 'Data' => array('Name' => $Discussion->Name, 'Category' => val('Name', $Category)));
            // Allow simple fulltext notifications
            if (c('Vanilla.Activity.ShowCommentBody', false)) {
                $Activity['Story'] = val('Body', $Fields);
                $Activity['Format'] = val('Format', $Fields);
            }
            // Pass generic activity to events.
            $this->EventArguments['Activity'] = $Activity;
            // Notify users who have bookmarked the discussion.
            $BookmarkData = $DiscussionModel->GetBookmarkUsers($DiscussionID);
            foreach ($BookmarkData->result() as $Bookmark) {
                // Check user can still see the discussion.
                if (!$discussionModel->canView($Discussion, $Bookmark->UserID)) {
                    continue;
                }
                $Activity['NotifyUserID'] = $Bookmark->UserID;
                $Activity['Data']['Reason'] = 'bookmark';
                $ActivityModel->Queue($Activity, 'BookmarkComment', array('CheckRecord' => true));
            }
            // Notify users who have participated in the discussion.
            $ParticipatedData = $DiscussionModel->GetParticipatedUsers($DiscussionID);
            foreach ($ParticipatedData->result() as $UserRow) {
                if (!$discussionModel->canView($Discussion, $UserRow->UserID)) {
                    continue;
                }
                $Activity['NotifyUserID'] = $UserRow->UserID;
                $Activity['Data']['Reason'] = 'participated';
                $ActivityModel->Queue($Activity, 'ParticipateComment', array('CheckRecord' => true));
            }
            // Record user-comment activity.
            if ($Discussion != false) {
                $InsertUserID = val('InsertUserID', $Discussion);
                // Check user can still see the discussion.
                if ($discussionModel->canView($Discussion, $InsertUserID)) {
                    $Activity['NotifyUserID'] = $InsertUserID;
                    $Activity['Data']['Reason'] = 'mine';
                    $ActivityModel->Queue($Activity, 'DiscussionComment');
                }
            }
            // Record advanced notifications.
            if ($Discussion !== false) {
                $Activity['Data']['Reason'] = 'advanced';
                $this->RecordAdvancedNotications($ActivityModel, $Activity, $Discussion);
            }
            // Notify any users who were mentioned in the comment.
            $Usernames = GetMentions($Fields['Body']);
            $userModel = Gdn::userModel();
            foreach ($Usernames as $i => $Username) {
                $User = $userModel->GetByUsername($Username);
                if (!$User) {
                    unset($Usernames[$i]);
                    continue;
                }
                // Check user can still see the discussion.
                if (!$discussionModel->canView($Discussion, $User->UserID)) {
                    continue;
                }
                $HeadlineFormatBak = $Activity['HeadlineFormat'];
                $Activity['HeadlineFormat'] = t('HeadlineFormat.Mention', '{ActivityUserID,user} mentioned you in <a href="{Url,html}">{Data.Name,text}</a>');
                $Activity['NotifyUserID'] = $User->UserID;
                $Activity['Data']['Reason'] = 'mention';
                $ActivityModel->Queue($Activity, 'Mention');
                $Activity['HeadlineFormat'] = $HeadlineFormatBak;
            }
            unset($Activity['Data']['Reason']);
            // Throw an event for users to add their own events.
            $this->EventArguments['Comment'] = $Fields;
            $this->EventArguments['Discussion'] = $Discussion;
            $this->EventArguments['NotifiedUsers'] = array_keys(ActivityModel::$Queue);
            $this->EventArguments['MentionedUsers'] = $Usernames;
            $this->EventArguments['ActivityModel'] = $ActivityModel;
            $this->fireEvent('BeforeNotification');
            // Send all notifications.
            $ActivityModel->SaveQueue();
        }
    }

Usage Example

 /**
  *
  *
  * @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;
 }