/**
  * Re-fetch a discussion's content based on its foreign url.
  * @param type $DiscussionID
  */
 public function RefetchPageInfo($DiscussionID)
 {
     // Make sure we are posting back.
     if (!$this->Request->IsPostBack()) {
         throw PermissionException('Javascript');
     }
     // Grab the discussion.
     $Discussion = $this->DiscussionModel->GetID($DiscussionID);
     if (!$Discussion) {
         throw NotFoundException('Discussion');
     }
     // Make sure the user has permission to edit this discussion.
     $this->Permission('Vanilla.Discussions.Edit', TRUE, 'Category', $Discussion->PermissionCategoryID);
     $ForeignUrl = GetValueR('Attributes.ForeignUrl', $Discussion);
     if (!$ForeignUrl) {
         throw new Gdn_UserException(T("This discussion isn't associated with a url."));
     }
     $Stub = $this->DiscussionModel->FetchPageInfo($ForeignUrl, TRUE);
     // Save the stub.
     $this->DiscussionModel->SetField($DiscussionID, (array) $Stub);
     // Send some of the stuff back.
     if (isset($Stub['Name'])) {
         $this->JsonTarget('.PageTitle h1', Gdn_Format::Text($Stub['Name']));
     }
     if (isset($Stub['Body'])) {
         $this->JsonTarget("#Discussion_{$DiscussionID} .Message", Gdn_Format::To($Stub['Body'], $Stub['Format']));
     }
     $this->InformMessage('The page was successfully fetched.');
     $this->Render('Blank', 'Utility', 'Dashboard');
 }
 /**
  * Add a method to the ModerationController to handle splitting comments out to a new discussion.
  */
 public function ModerationController_SplitComments_Create($Sender)
 {
     $Session = Gdn::Session();
     $Sender->Form = new Gdn_Form();
     $Sender->Title(T('Split Comments'));
     $Sender->Category = FALSE;
     $DiscussionID = GetValue('0', $Sender->RequestArgs, '');
     if (!is_numeric($DiscussionID)) {
         return;
     }
     $DiscussionModel = new DiscussionModel();
     $Discussion = $DiscussionModel->GetID($DiscussionID);
     if (!$Discussion) {
         return;
     }
     // Verify that the user has permission to perform the split
     $Sender->Permission('Vanilla.Discussions.Edit', TRUE, 'Category', $Discussion->PermissionCategoryID);
     $CheckedComments = Gdn::UserModel()->GetAttribute($Session->User->UserID, 'CheckedComments', array());
     if (!is_array($CheckedComments)) {
         $CheckedComments = array();
     }
     $CommentIDs = array();
     foreach ($CheckedComments as $DiscID => $Comments) {
         foreach ($Comments as $Comment) {
             if ($DiscID == $DiscussionID) {
                 $CommentIDs[] = str_replace('Comment_', '', $Comment);
             }
         }
     }
     // Load category data.
     $Sender->ShowCategorySelector = (bool) C('Vanilla.Categories.Use');
     $CountCheckedComments = count($CommentIDs);
     $Sender->SetData('CountCheckedComments', $CountCheckedComments);
     // Perform the split
     if ($Sender->Form->AuthenticatedPostBack()) {
         // Create a new discussion record
         $Data = $Sender->Form->FormValues();
         $Data['Body'] = sprintf(T('This discussion was created from comments split from: %s.'), Anchor(Gdn_Format::Text($Discussion->Name), 'discussion/' . $Discussion->DiscussionID . '/' . Gdn_Format::Url($Discussion->Name) . '/'));
         $Data['Format'] = 'Html';
         $NewDiscussionID = $DiscussionModel->Save($Data);
         $Sender->Form->SetValidationResults($DiscussionModel->ValidationResults());
         if ($Sender->Form->ErrorCount() == 0 && $NewDiscussionID > 0) {
             // Re-assign the comments to the new discussion record
             $DiscussionModel->SQL->Update('Comment')->Set('DiscussionID', $NewDiscussionID)->WhereIn('CommentID', $CommentIDs)->Put();
             // Update counts on both discussions
             $CommentModel = new CommentModel();
             $CommentModel->UpdateCommentCount($DiscussionID);
             //            $CommentModel->UpdateUserCommentCounts($DiscussionID);
             $CommentModel->UpdateCommentCount($NewDiscussionID);
             // Clear selections
             unset($CheckedComments[$DiscussionID]);
             Gdn::UserModel()->SaveAttribute($Session->UserID, 'CheckedComments', $CheckedComments);
             ModerationController::InformCheckedComments($Sender);
             $Sender->RedirectUrl = Url('discussion/' . $NewDiscussionID . '/' . Gdn_Format::Url($Data['Name']));
         }
     } else {
         $Sender->Form->SetValue('CategoryID', GetValue('CategoryID', $Discussion));
     }
     $Sender->Render($this->GetView('splitcomments.php'));
 }
 public function NotifyNewDiscussion($DiscussionID)
 {
     if (!C('Vanilla.QueueNotifications')) {
         throw ForbiddenException('NotifyNewDiscussion');
     }
     if (!$this->Request->IsPostBack()) {
         throw ForbiddenException('GET');
     }
     // Grab the discussion.
     $Discussion = $this->DiscussionModel->GetID($DiscussionID);
     if (!$Discussion) {
         throw NotFoundException('Discussion');
     }
     if (GetValue('Notified', $Discussion) != ActivityModel::SENT_PENDING) {
         die('Not pending');
     }
     // Mark the notification as in progress.
     $this->DiscussionModel->SetField($DiscussionID, 'Notified', ActivityModel::SENT_INPROGRESS);
     $HeadlineFormat = T($Code, '{ActivityUserID,user} started a new discussion: <a href="{Url,html}">{Data.Name,text}</a>');
     $Category = CategoryModel::Categories(GetValue('CategoryID', $Discussion));
     $Activity = array('ActivityType' => 'Discussion', 'ActivityUserID' => $Discussion->InsertUserID, 'HeadlineFormat' => $HeadlineFormat, 'RecordType' => 'Discussion', 'RecordID' => $DiscussionID, 'Route' => DiscussionUrl($Discussion), 'Data' => array('Name' => $Discussion->Name, 'Category' => GetValue('Name', $Category)));
     $ActivityModel = new ActivityModel();
     $this->DiscussionModel->NotifyNewDiscussion($Discussion, $ActivityModel, $Activity);
     $ActivityModel->SaveQueue();
     $this->DiscussionModel->SetField($DiscussionID, 'Notified', ActivityModel::SENT_OK);
     die('OK');
 }
 public function Award($Sender, $User, $Criteria)
 {
     $NecroDate = strtotime($Criteria->Duration . ' ' . $Criteria->Period . ' ago');
     // Get the last comment date from the parent discussion
     $Args = $Sender->EventArguments;
     $DiscussionID = $Args['FormPostValues']['DiscussionID'];
     $DiscussionModel = new DiscussionModel();
     $Discussion = $DiscussionModel->GetID($DiscussionID);
     $LastCommentDate = strtotime($Discussion->DateLastComment);
     if ($LastCommentDate < $NecroDate) {
         return TRUE;
     } else {
         return FALSE;
     }
 }
 public function DiscussionController_AutoExpire_Create($Sender, $Args)
 {
     $DiscussionID = intval($Args[0]);
     $DiscussionModel = new DiscussionModel();
     $Discussion = $DiscussionModel->GetID($DiscussionID);
     if (!Gdn::Session()->CheckPermission('Vanilla.Discussions.Close', TRUE, 'Category', $Discussion->PermissionCategoryID)) {
         throw PermissionException('Vanilla.Discussions.Close');
     }
     if (strtolower($Args[1]) == 'reset') {
         Gdn::SQL()->Put('Discussion', array('AutoExpire' => 1, 'Closed' => 0, 'DateReOpened' => Gdn_Format::ToDateTime()), array('DiscussionID' => $DiscussionID));
     } else {
         $Expire = strtolower($Args[1]) == 'on' ? 1 : 0;
         Gdn::SQL()->Put('Discussion', array('AutoExpire' => $Expire), array('DiscussionID' => $DiscussionID));
     }
     Redirect('discussion/' . $DiscussionID . '/' . Gdn_Format::Url($Discussion->Name));
 }
    protected function AddReplyButton($Sender)
    {
        if (!Gdn::Session()->UserID) {
            return;
        }
        if (isset($Sender->EventArguments['Comment'])) {
            $Model = new CommentModel();
            $Data = $Model->GetID($Sender->EventArguments['Comment']->CommentID);
        } else {
            $Model = new DiscussionModel();
            $Data = $Model->GetID($Sender->Data['Discussion']->DiscussionID);
        }
        $ReplyURL = "#" . "{$Data->InsertName}";
        $ReplyText = T('Reply');
        echo <<<QUOTE
      <span class="CommentReply"><a href="{$ReplyURL}">{$ReplyText}</a></span>
QUOTE;
    }
 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;
 }
 public function CommentModel_AfterSaveComment_Handler($Sender, $Args)
 {
     if (!$this->SocialSharing()) {
         return;
     }
     if (!$this->AccessToken()) {
         return;
     }
     $Share = GetValueR('FormPostValues.ShareTwitter', $Args);
     if ($Share && $this->AccessToken()) {
         $Row = $Args['FormPostValues'];
         $DiscussionModel = new DiscussionModel();
         $Discussion = $DiscussionModel->GetID(GetValue('DiscussionID', $Row));
         if (!$Discussion) {
             return;
         }
         $Url = DiscussionUrl($Discussion, '', TRUE);
         $Message = SliceTwitter(Gdn_Format::PlainText($Row['Body'], $Row['Format'])) . ' ' . $Url;
         $R = $this->API('/statuses/update.json', array('status' => $Message), 'POST');
         //         decho($R);
         //         die();
         //      } else {
         //         die("$Share ".$this->AccessToken());
     }
 }
 /**
  * Checks role permissions as well as category permissions
  * and changes InsertUserID to IncognitoUserID
  *
  * @param VanillaController $Sender    Either CommentController or DiscussionController
  *
  */
 private function _HideUser($Sender)
 {
     $Session = Gdn::Session();
     // return if checkbox not send or missing role permissions
     if ($Sender->EventArguments['FormPostValues']['Incognito'] !== '1' || !$Session->CheckPermission('Plugins.Incognito.Allow')) {
         return;
     }
     if (get_class($Sender) == 'CommentModel') {
         // get CategoryID of comment
         $DiscussionModel = new DiscussionModel();
         $DiscussionID = $Sender->EventArguments['FormPostValues']['DiscussionID'];
         $Discussion = $DiscussionModel->GetID($DiscussionID);
         $CategoryID = $Discussion->CategoryID;
         $PostType = 'Comments';
     } else {
         // ... or of discussion
         $CategoryID = $Sender->EventArguments['FormPostValues']['CategoryID'];
         $PostType = 'Discussions';
     }
     // get PermissionCategoryID of CategoryID
     $CategoryModel = new CategoryModel();
     $Category = $CategoryModel->GetID($CategoryID);
     $PermissionCategoryID = $Category->PermissionCategoryID;
     // check for permissions and change InsertUserID to IncognitoUserID...
     if ($Session->CheckPermission(array('Vanilla.Comments.Add', "Vanilla.{$PostType}.Incognito"), TRUE, 'Category', $PermissionCategoryID)) {
         $IncognitoUserID = C('Plugins.Incognito.UserID', Gdn::UserModel()->GetSystemUserID());
         $Sender->EventArguments['FormPostValues']['InsertUserID'] = $IncognitoUserID;
     } else {
         // ... or stop with error message if no permissions
         $Sender->Validation->AddValidationResult('CategoryID', 'You do not have permission to Post anonymously in this category');
     }
 }
 /**
  * Insert or update meta data about the comment.
  * 
  * Updates unread comment totals, bookmarks, and activity. Sends notifications.
  * 
  * @since 2.0.0
  * @access public
  *
  * @param array $CommentID Unique ID for this comment.
  * @param int $Insert Used as a boolean for whether this is a new comment.
  * @param bool $CheckExisting Not used.
  * @param bool $IncUser 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();
     $UserModel = Gdn::UserModel();
     // Load comment data
     $Fields = $this->GetID($CommentID, DATASET_TYPE_ARRAY);
     // Clear any session stashes related to this discussion
     $DiscussionModel = new DiscussionModel();
     $DiscussionID = GetValue('DiscussionID', $Fields);
     $Discussion = $DiscussionModel->GetID($DiscussionID);
     $Session->Stash('CommentForForeignID_' . GetValue('ForeignID', $Discussion));
     // 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;
     }
     // 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($Session->UserID, $IncUser && $Insert);
     if ($Insert) {
         // UPDATE COUNT AND LAST COMMENT ON CATEGORY TABLE
         if ($Discussion->CategoryID > 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.
             if ($DiscussionID && Gdn::Cache()->ActiveEnabled()) {
                 $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' => GetValue('Name', $Category)));
         // Allow simple fulltext notifications
         if (C('Vanilla.Activity.ShowCommentBody', FALSE)) {
             $Activity['Story'] = GetValue('Body', $Fields);
         }
         // Notify users who have bookmarked the discussion.
         $BookmarkData = $DiscussionModel->GetBookmarkUsers($DiscussionID);
         foreach ($BookmarkData->Result() as $Bookmark) {
             // Check user can still see the discussion.
             if (!$UserModel->GetCategoryViewPermission($Bookmark->UserID, $Discussion->CategoryID)) {
                 continue;
             }
             $Activity['NotifyUserID'] = $Bookmark->UserID;
             $ActivityModel->Queue($Activity, 'BookmarkComment', array('CheckRecord' => TRUE));
         }
         // Record user-comment activity.
         if ($Discussion != FALSE) {
             $Activity['NotifyUserID'] = GetValue('InsertUserID', $Discussion);
             $ActivityModel->Queue($Activity, 'DiscussionComment');
         }
         // Record advanced notifications.
         if ($Discussion !== FALSE) {
             $this->RecordAdvancedNotications($ActivityModel, $Activity, $Discussion);
         }
         // Notify any users who were mentioned in the comment.
         $Usernames = GetMentions($Fields['Body']);
         $NotifiedUsers = array();
         foreach ($Usernames as $i => $Username) {
             $User = $UserModel->GetByUsername($Username);
             if (!$User) {
                 unset($Usernames[$i]);
                 continue;
             }
             // Check user can still see the discussion.
             if (!$UserModel->GetCategoryViewPermission($User->UserID, $Discussion->CategoryID)) {
                 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;
             $ActivityModel->Queue($Activity, 'Mention');
             $Activity['HeadlineFormat'] = $HeadlineFormatBak;
         }
         // 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();
     }
 }
Exemple #11
0
 public function Gdn_Statistics_Tick_Handler($Sender, $Args)
 {
     $Path = GetValue('Path', $Args);
     if (preg_match('`discussion\\/(\\d+)`i', $Path, $Matches)) {
         $DiscussionID = $Matches[1];
     } elseif (preg_match('`discussion\\/comment\\/(\\d+)`i', $Path, $Matches)) {
         $CommentID = $Matches[1];
         $CommentModel = new CommentModel();
         $Comment = $CommentModel->GetID($CommentID);
         $DiscussionID = GetValue('DiscussionID', $Comment);
     }
     if (isset($DiscussionID)) {
         $DiscussionModel = new DiscussionModel();
         $Discussion = $DiscussionModel->GetID($DiscussionID);
         $DiscussionModel->AddView($DiscussionID, GetValue('CountViews', $Discussion));
     }
 }
    protected function FormatQuote($Type, $ID, &$QuoteData, $Format = FALSE)
    {
        if (!$Format) {
            $Format = C('Garden.InputFormatter');
        }
        $Type = strtolower($Type);
        $Model = FALSE;
        switch ($Type) {
            case 'comment':
                $Model = new CommentModel();
                break;
            case 'discussion':
                $Model = new DiscussionModel();
                break;
            default:
                break;
        }
        //$QuoteData = array();
        if ($Model) {
            $Data = $Model->GetID($ID);
            $NewFormat = $Format;
            if ($NewFormat == 'Wysiwyg') {
                $NewFormat = 'Html';
            }
            $QuoteFormat = $Data->Format;
            if ($QuoteFormat == 'Wysiwyg') {
                $QuoteFormat = 'Html';
            }
            // Perform transcoding if possible
            $NewBody = $Data->Body;
            if ($QuoteFormat != $NewFormat) {
                if (in_array($NewFormat, array('Html', 'Wysiwyg'))) {
                    $NewBody = Gdn_Format::To($NewBody, $QuoteFormat);
                } elseif ($QuoteFormat == 'Html' && $NewFormat == 'BBCode') {
                    $NewBody = Gdn_Format::Text($NewBody);
                } elseif ($QuoteFormat == 'Text' && $NewFormat == 'BBCode') {
                    $NewBody = Gdn_Format::Text($NewBody);
                } else {
                    $NewBody = Gdn_Format::PlainText($NewBody, $QuoteFormat);
                }
                if (!in_array($NewFormat, array('Html', 'Wysiwyg'))) {
                    Gdn::Controller()->InformMessage(sprintf(T('The quote had to be converted from %s to %s.', 'The quote had to be converted from %s to %s. Some formatting may have been lost.'), htmlspecialchars($QuoteFormat), htmlspecialchars($NewFormat)));
                }
            }
            $Data->Body = $NewBody;
            // Format the quote according to the format.
            switch ($Format) {
                case 'Html':
                    // HTML
                    $Quote = '<blockquote class="Quote" rel="' . htmlspecialchars($Data->InsertName) . '">' . $Data->Body . '</blockquote>' . "\n";
                    break;
                case 'BBCode':
                    $Author = htmlspecialchars($Data->InsertName);
                    if ($ID) {
                        $IDString = ';' . htmlspecialchars($ID);
                    }
                    $QuoteBody = $Data->Body;
                    // TODO: Strip inner quotes...
                    //                  $QuoteBody = trim(preg_replace('`(\[quote.*/quote\])`si', '', $QuoteBody));
                    $Quote = <<<BQ
[quote="{$Author}{$IDString}"]{$QuoteBody}[/quote]

BQ;
                    break;
                case 'Markdown':
                case 'Display':
                case 'Text':
                    $QuoteBody = $Data->Body;
                    // Strip inner quotes and mentions...
                    $QuoteBody = self::_StripMarkdownQuotes($QuoteBody);
                    $QuoteBody = self::_StripMentions($QuoteBody);
                    $Quote = '> ' . sprintf(T('%s said:'), '@' . $Data->InsertName) . "\n" . '> ' . str_replace("\n", "\n> ", $QuoteBody);
                    break;
                case 'Wysiwyg':
                    $Attribution = sprintf(T('%s said:'), UserAnchor($Data, NULL, array('Px' => 'Insert')));
                    $QuoteBody = $Data->Body;
                    // TODO: Strip inner quotes...
                    //                  $QuoteBody = trim(preg_replace('`(<blockquote.*/blockquote>)`si', '', $QuoteBody));
                    $Quote = <<<BLOCKQUOTE
<blockquote class="Quote">
  <div class="QuoteAuthor">{$Attribution}</div>
  <div class="QuoteText">{$QuoteBody}</div>
</blockquote>

BLOCKQUOTE;
                    break;
            }
            $QuoteData = array_merge($QuoteData, array('status' => 'success', 'body' => $Quote, 'format' => $Format, 'authorid' => $Data->InsertUserID, 'authorname' => $Data->InsertName, 'type' => $Type, 'typeid' => $ID));
        }
    }
 function GetRecord($RecordType, $ID, $ThrowError = FALSE)
 {
     $Row = FALSE;
     switch (strtolower($RecordType)) {
         case 'discussion':
             $Model = new DiscussionModel();
             $Row = $Model->GetID($ID);
             $Row->Url = DiscussionUrl($Row);
             $Row->ShareUrl = $Row->Url;
             if ($Row) {
                 return (array) $Row;
             }
             break;
         case 'comment':
             $Model = new CommentModel();
             $Row = $Model->GetID($ID, DATASET_TYPE_ARRAY);
             if ($Row) {
                 $Row['Url'] = Url("/discussion/comment/{$ID}#Comment_{$ID}", TRUE);
                 $Model = new DiscussionModel();
                 $Discussion = $Model->GetID($Row['DiscussionID']);
                 if ($Discussion) {
                     $Discussion->Url = DiscussionUrl($Discussion);
                     $Row['ShareUrl'] = $Discussion->Url;
                     $Row['Name'] = $Discussion->Name;
                     $Row['Discussion'] = (array) $Discussion;
                 }
                 return $Row;
             }
             break;
         case 'activity':
             $Model = new ActivityModel();
             $Row = $Model->GetID($ID, DATASET_TYPE_ARRAY);
             if ($Row) {
                 $Row['Name'] = FormatString($Row['HeadlineFormat'], $Row);
                 $Row['Body'] = $Row['Story'];
                 return $Row;
             }
         default:
             throw new Gdn_UserException(sprintf("I don't know what a %s is.", strtolower($RecordType)));
     }
     if ($ThrowError) {
         throw NotFoundException($RecordType);
     } else {
         return FALSE;
     }
 }
 public function Controller_Delete($Sender)
 {
     $Session = Gdn::Session();
     $DPModel = new DiscussionPollsModel();
     $DiscussionModel = new DiscussionModel();
     $Poll = $DPModel->Get($Sender->RequestArgs[1]);
     $Discussion = $DiscussionModel->GetID($Poll->DiscussionID);
     $PollOwnerID = $Discussion->InsertUserID;
     if ($Session->CheckPermission('Plugins.DiscussionPolls.Manage') || $PollOwnerID == $Session->UserID) {
         $DPModel = new DiscussionPollsModel();
         $DPModel->Delete($Sender->RequestArgs[1]);
         $Result = 'Removed poll with id ' . $Sender->RequestArgs[1];
         if ($Sender->DeliveryType() == DELIVERY_TYPE_VIEW) {
             $Data = array('html' => $Result);
             echo json_encode($Data);
         } else {
             $Sender->SetData('PollString', $Result);
             $Sender->Render($this->ThemView('poll'));
         }
     } else {
         // throw permission exception
         throw PermissionException();
     }
 }
Exemple #15
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);
 }
Exemple #16
0
 public function DiscussionController_CommentOptions_Handler($Sender)
 {
     $Session = Gdn::Session();
     $User = $Session->User;
     $UID = $User->UserID;
     $DiscussionModel = new DiscussionModel();
     $CommentModel = new CommentModel();
     $Discussion = $DiscussionModel->GetID($DiscussionID);
     if ($Sender->EventArguments['Type'] == 'Discussion') {
         $DiscussionID = $Sender->EventArguments['Discussion']->DiscussionID;
         if ($Sender->Data['Comments'] instanceof Gdn_DataSet) {
             $this->LikeModel->PreloadLikes($Sender->Data['Comments']);
         }
         $ID = $DiscussionID;
         $Model = new DiscussionModel();
         $Data = $Model->GetID($ID);
         $Likes = $this->LikeModel->GetDiscussionLikes($ID);
         $Url = $DiscussionID;
     } else {
         $DiscussionID = $Sender->EventArguments['Object']->DiscussionID;
         $ID = $Sender->EventArguments['Object']->CommentID;
         $Model = new CommentModel();
         $Data = $Model->GetID($ID);
         $Likes = $this->LikeModel->GetCommentLikes($ID);
         $Url = $DiscussionID . '/comment/' . $ID;
     }
     $InsertID = $Data->InsertUserID;
     if ($InsertID == $UID) {
         $Self = TRUE;
     } else {
         $Self = FALSE;
     }
     // Check for permission.
     if (!Gdn::Session()->UserID) {
         $Self = TRUE;
     }
     if (!CheckPermission('Plugins.LikeThis.AllowedToLike')) {
         $Self = TRUE;
     }
     $LikeDisplay = $this->FormatLikes($Likes, $Url, $UID, $Self);
     echo '<span class="Like">' . $LikeDisplay . '</span>';
 }
Exemple #17
0
 public function RecordActivity($DiscussionID, $ActivityUserID, $CommentID)
 {
     // Get the author of the discussion
     $DiscussionModel = new DiscussionModel();
     $Discussion = $DiscussionModel->GetID($DiscussionID);
     if ($Discussion->InsertUserID != $ActivityUserID) {
         AddActivity($ActivityUserID, 'DiscussionComment', '', $Discussion->InsertUserID, 'discussion/comment/' . $CommentID . '/#Comment_' . $CommentID);
     }
 }
   /**
    * Increment/decrement discussion scores
    */
   public function DiscussionController_VoteDiscussion_Create($Sender) {
		if (!C('Plugins.Voting.Enabled'))
			return;

      $DiscussionID = GetValue(0, $Sender->RequestArgs, 0);
      $TransientKey = GetValue(1, $Sender->RequestArgs);
      $VoteType = FALSE;
      if ($TransientKey == 'voteup' || $TransientKey == 'votedown') {
         $VoteType = $TransientKey;
         $TransientKey = GetValue(2, $Sender->RequestArgs);
      }
      $Session = Gdn::Session();
      $NewUserVote = 0;
      $Total = 0;
      if ($Session->IsValid() && $Session->ValidateTransientKey($TransientKey) && $DiscussionID > 0) {
         $DiscussionModel = new DiscussionModel();
         $OldUserVote = $DiscussionModel->GetUserScore($DiscussionID, $Session->UserID);

         if ($VoteType == 'voteup')
            $NewUserVote = 1;
         else if ($VoteType == 'votedown')
            $NewUserVote = -1;
         else
            $NewUserVote = $OldUserVote == 1 ? -1 : 1;
         
         $FinalVote = intval($OldUserVote) + intval($NewUserVote);
         // Allow admins to vote unlimited.
         $AllowVote = $Session->CheckPermission('Vanilla.Comments.Edit');
         // Only allow users to vote up or down by 1.
         if (!$AllowVote)
            $AllowVote = $FinalVote > -2 && $FinalVote < 2;
         
         if ($AllowVote) {
            $Total = $DiscussionModel->SetUserScore($DiscussionID, $Session->UserID, $FinalVote);
         } else {
				$Discussion = $DiscussionModel->GetID($DiscussionID);
				$Total = GetValue('Score', $Discussion, 0);
				$FinalVote = $OldUserVote;
			}
      }
      $Sender->DeliveryType(DELIVERY_TYPE_BOOL);
      $Sender->SetJson('TotalScore', $Total);
      $Sender->SetJson('FinalVote', $FinalVote);
      $Sender->Render();
   }
 function GetRecord($RecordType, $ID)
 {
     switch (strtolower($RecordType)) {
         case 'discussion':
             $Model = new DiscussionModel();
             $Row = $Model->GetID($ID);
             $Row->Url = DiscussionUrl($Row);
             $Row->ShareUrl = $Row->Url;
             return (array) $Row;
         case 'comment':
             $Model = new CommentModel();
             $Row = $Model->GetID($ID, DATASET_TYPE_ARRAY);
             $Row['Url'] = Url("/discussion/comment/{$ID}#Comment_{$ID}", TRUE);
             $Model = new DiscussionModel();
             $Discussion = $Model->GetID($Row['DiscussionID']);
             $Discussion->Url = DiscussionUrl($Discussion);
             $Row['ShareUrl'] = $Discussion->Url;
             $Row['Name'] = $Discussion->Name;
             $Row['Discussion'] = (array) $Discussion;
             return $Row;
         default:
             throw new Gdn_UserException(sprintf("I don't know what a %s is.", strtolower($RecordType)));
     }
 }
 /**
  *
  *
  * @param $Filename
  * @param $Get
  * @return bool|string
  */
 public function filenameRedirect($Filename, $Get)
 {
     trace(['Filename' => $Filename, 'Get' => $Get], 'Testing');
     $Filename = strtolower($Filename);
     array_change_key_case($Get);
     if (!isset(self::$Files[$Filename])) {
         return false;
     }
     $Row = self::$Files[$Filename];
     if (is_callable($Row)) {
         // Use a callback to determine the translation.
         $Row = call_user_func_array($Row, [&$Get]);
     }
     trace($Get, 'New Get');
     // Translate all of the get parameters into new parameters.
     $Vars = array();
     foreach ($Get as $Key => $Value) {
         if (!isset($Row[$Key])) {
             continue;
         }
         $Opts = (array) $Row[$Key];
         if (isset($Opts['Filter'])) {
             // Call the filter function to change the value.
             $R = call_user_func($Opts['Filter'], $Value, $Opts[0]);
             if (is_array($R)) {
                 if (isset($R[0])) {
                     // The filter can change the column name too.
                     $Opts[0] = $R[0];
                     $Value = $R[1];
                 } else {
                     // The filter can return return other variables too.
                     $Vars = array_merge($Vars, $R);
                     $Value = null;
                 }
             } else {
                 $Value = $R;
             }
         }
         if ($Value !== null) {
             $Vars[$Opts[0]] = $Value;
         }
     }
     trace($Vars, 'Translated Arguments');
     // Now let's see what kind of record we have.
     // We'll check the various primary keys in order of importance.
     $Result = false;
     if (isset($Vars['CommentID'])) {
         trace("Looking up comment {$Vars['CommentID']}.");
         $CommentModel = new CommentModel();
         // If a legacy slug is provided (assigned during a merge), attempt to lookup the comment using it
         if (isset($Get['legacy']) && Gdn::Structure()->Table('Comment')->ColumnExists('ForeignID')) {
             $Comment = $CommentModel->GetWhere(['ForeignID' => $Get['legacy'] . '-' . $Vars['CommentID']])->FirstRow();
         } else {
             $Comment = $CommentModel->GetID($Vars['CommentID']);
         }
         if ($Comment) {
             $Result = CommentUrl($Comment, '//');
         }
     } elseif (isset($Vars['DiscussionID'])) {
         trace("Looking up discussion {$Vars['DiscussionID']}.");
         $DiscussionModel = new DiscussionModel();
         $DiscussionID = $Vars['DiscussionID'];
         $Discussion = false;
         if (is_numeric($DiscussionID)) {
             // If a legacy slug is provided (assigned during a merge), attempt to lookup the discussion using it
             if (isset($Get['legacy']) && Gdn::Structure()->Table('Discussion')->ColumnExists('ForeignID')) {
                 $Discussion = $DiscussionModel->GetWhere(['ForeignID' => $Get['legacy'] . '-' . $DiscussionID])->FirstRow();
             } else {
                 $Discussion = $DiscussionModel->GetID($Vars['DiscussionID']);
             }
         } else {
             // This is a slug style discussion ID. Let's see if there is a UrlCode column in the discussion table.
             $DiscussionModel->DefineSchema();
             if ($DiscussionModel->Schema->FieldExists('Discussion', 'UrlCode')) {
                 $Discussion = $DiscussionModel->GetWhere(['UrlCode' => $DiscussionID])->FirstRow();
             }
         }
         if ($Discussion) {
             $Result = DiscussionUrl($Discussion, self::pageNumber($Vars, 'Vanilla.Comments.PerPage'), '//');
         }
     } elseif (isset($Vars['UserID'])) {
         trace("Looking up user {$Vars['UserID']}.");
         $User = Gdn::UserModel()->GetID($Vars['UserID']);
         if ($User) {
             $Result = Url(UserUrl($User), '//');
         }
     } elseif (isset($Vars['TagID'])) {
         $Tag = TagModel::instance()->GetID($Vars['TagID']);
         if ($Tag) {
             $Result = TagUrl($Tag, self::pageNumber($Vars, 'Vanilla.Discussions.PerPage'), '//');
         }
     } elseif (isset($Vars['CategoryID'])) {
         trace("Looking up category {$Vars['CategoryID']}.");
         // If a legacy slug is provided (assigned during a merge), attempt to lookup the category ID based on it
         if (isset($Get['legacy']) && Gdn::Structure()->Table('Category')->ColumnExists('ForeignID')) {
             $CategoryModel = new CategoryModel();
             $Category = $CategoryModel->GetWhere(['ForeignID' => $Get['legacy'] . '-' . $Vars['CategoryID']])->FirstRow();
         } else {
             $Category = CategoryModel::Categories($Vars['CategoryID']);
         }
         if ($Category) {
             $Result = categoryUrl($Category, self::pageNumber($Vars, 'Vanilla.Discussions.PerPage'), '//');
         }
     } elseif (isset($Vars['CategoryCode'])) {
         trace("Looking up category {$Vars['CategoryCode']}.");
         $category = CategoryModel::instance()->getByCode($Vars['CategoryCode']);
         if ($category) {
             $pageNumber = self::pageNumber($Vars, 'Vanilla.Discussions.PerPage');
             if ($pageNumber > 1) {
                 $pageParam = '?Page=' . $pageNumber;
             } else {
                 $pageParam = null;
             }
             $Result = categoryUrl($category, '', '//') . $pageParam;
         }
     }
     return $Result;
 }
 protected function FormatQuote($Type, $ID, &$QuoteData)
 {
     $Type = strtolower($Type);
     $Model = FALSE;
     switch ($Type) {
         case 'comment':
             $Model = new CommentModel();
             break;
         case 'discussion':
             $Model = new DiscussionModel();
             break;
         default:
             break;
     }
     //$QuoteData = array();
     if ($Model) {
         $Data = $Model->GetID($ID);
         $NewFormat = C('Garden.InputFormatter');
         $QuoteFormat = $Data->Format;
         // Perform transcoding if possible
         $NewBody = $Data->Body;
         if ($QuoteFormat != $NewFormat) {
             if ($QuoteFormat == 'BBCode' && $NewFormat == 'Html') {
                 $NewBody = Gdn_Format::BBCode($NewBody);
             } elseif ($QuoteFormat == 'Text' && $NewFormat == 'Html') {
                 $NewBody = Gdn_Format::Text($NewBody);
             } elseif ($QuoteFormat == 'Html' && $NewFormat == 'BBCode') {
                 $NewBody = Gdn_Format::Text($NewBody);
             } elseif ($QuoteFormat == 'Text' && $NewFormat == 'BBCode') {
                 $NewBody = Gdn_Format::Text($NewBody);
             } else {
                 $NewBody = Gdn_Format::PlainText($NewBody, $QuoteFormat);
             }
             Gdn::Controller()->InformMessage(sprintf(T('The quote had to be converted from %s to %s.', 'The quote had to be converted from %s to %s. Some formatting may have been lost.'), $QuoteFormat, $NewFormat));
         }
         $Data->Body = $NewBody;
         $QuoteData = array_merge($QuoteData, array('status' => 'success', 'body' => $Data->Body, 'format' => C('Garden.InputFormatter'), 'authorid' => $Data->InsertUserID, 'authorname' => $Data->InsertName, 'type' => $Type, 'typeid' => $ID));
     }
 }
Exemple #22
0
 protected function FormatQuote($Type, $ID, &$QuoteData)
 {
     $Model = FALSE;
     switch (strtolower($Type)) {
         case 'comment':
             $Model = new CommentModel();
             break;
         case 'discussion':
             $Model = new DiscussionModel();
             break;
         default:
             break;
     }
     //$QuoteData = array();
     if ($Model !== FALSE) {
         $Data = $Model->GetID($ID);
         $NewFormat = C('Garden.InputFormatter');
         $QuoteFormat = $Data->Format;
         $QuoteData = array_merge($QuoteData, array('status' => 'success', 'body' => $Data->Body, 'format' => C('Garden.InputFormatter'), 'authorid' => $Data->InsertUserID, 'authorname' => $Data->InsertName));
         // Perform transcoding if possible
         $NewBody = $Data->Body;
         if ($QuoteFormat != $NewFormat) {
             if ($QuoteFormat == 'BBCode' && $NewFormat == 'Html') {
                 $NewBody = Gdn_Format::BBCode($NewBody);
             } elseif ($QuoteFormat == 'Text' && $NewFormat == 'Html') {
                 $NewBody = Gdn_Format::Text($NewBody);
             } elseif ($QuoteFormat == 'Html' && $NewFormat == 'BBCode') {
                 $NewBody = Gdn_Format::Text($NewBody);
             } elseif ($QuoteFormat == 'Text' && $NewFormat == 'BBCode') {
                 $NewBody = Gdn_Format::Text($NewBody);
             }
         }
         $Data->Body = $NewBody;
     }
 }
Exemple #23
0
 /**
  * Insert or update meta data about the comment.
  * 
  * Updates unread comment totals, bookmarks, and activity. Sends notifications.
  * 
  * @since 2.0.0
  * @access public
  *
  * @param array $CommentID Unique ID for this comment.
  * @param int $Insert Used as a boolean for whether this is a new comment.
  * @param bool $CheckExisting Not used.
  * @param bool $IncUser 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();
     // Load comment data
     $Fields = $this->GetID($CommentID, DATASET_TYPE_ARRAY);
     // Clear any session stashes related to this discussion
     $Session->Stash('CommentForDiscussionID_' . GetValue('DiscussionID', $Fields));
     // 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;
     }
     // 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, $IncUser && $Insert);
     if ($Insert) {
         $DiscussionModel = new DiscussionModel();
         $DiscussionID = GetValue('DiscussionID', $Fields);
         $Discussion = $DiscussionModel->GetID($DiscussionID);
         // UPDATE COUNT AND LAST COMMENT ON CATEGORY TABLE
         if ($Discussion->CategoryID > 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' => $Discussion->DiscussionID, 'LastCommentID' => $Discussion->LastCommentID, 'CountComments' => $CountComments));
             // Update the cache.
             if ($DiscussionID && Gdn::Cache()->ActiveEnabled()) {
                 $CategoryCache = array('LastDiscussionID' => $DiscussionID, 'LastCommentID' => $CommentID, 'LastTitle' => $Discussion->Name, 'LastUserID' => $Fields['InsertUserID'], 'LastDateInserted' => $Fields['DateInserted'], 'LastUrl' => "/discussion/comment/{$CommentID}#Comment_{$CommentID}");
                 CategoryModel::SetCache($Discussion->CategoryID, $CategoryCache);
             }
         }
         // Prepare the notification queue.
         $ActivityModel = new ActivityModel();
         $ActivityModel->ClearNotificationQueue();
         // Notify any users who were mentioned in the comment.
         $Usernames = GetMentions($Fields['Body']);
         $UserModel = Gdn::UserModel();
         $Story = '[' . $Discussion->Name . "]\n" . ArrayValue('Body', $Fields, '');
         $NotifiedUsers = array();
         foreach ($Usernames as $Username) {
             $User = $UserModel->GetByUsername($Username);
             // Check user can still see the discussion.
             $UserMayView = $UserModel->GetCategoryViewPermission($User->UserID, $Discussion->CategoryID);
             if ($User && $User->UserID != $Session->UserID && $UserMayView) {
                 $NotifiedUsers[] = $User->UserID;
                 $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->QueueNotification($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) {
                 continue;
             }
             // Check user can still see the discussion.
             $UserMayView = $UserModel->GetCategoryViewPermission($Bookmark->UserID, $Discussion->CategoryID);
             if ($UserMayView) {
                 $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->QueueNotification($ActivityID, $Story);
             }
         }
         // Record user-comment activity.
         if ($Discussion !== FALSE && !in_array($Session->UserID, $NotifiedUsers)) {
             $ActivityID = $this->RecordActivity($ActivityModel, $Discussion, $Session->UserID, $CommentID, FALSE);
             if ($ActivityID) {
                 $ActivityModel->QueueNotification($ActivityID, $Story);
                 $NotifiedUsers[] = $Session->UserID;
             }
         }
         // Record advanced notifications.
         if ($Discussion !== FALSE) {
             $this->RecordAdvancedNotications($ActivityModel, $Discussion, $Fields, $NotifiedUsers);
         }
         // Throw an event for users to add their own events.
         $this->EventArguments['Comment'] = $Fields;
         $this->EventArguments['Discussion'] = $Discussion;
         $this->EventArguments['NotifiedUsers'] = $NotifiedUsers;
         $this->EventArguments['ActivityModel'] = $ActivityModel;
         $this->FireEvent('BeforeNotification');
         // Send all notifications.
         $ActivityModel->SendNotificationQueue();
     }
 }
 public function CommentModel_AfterSaveComment_Handler($Sender, $Args)
 {
     if (!$this->SocialSharing()) {
         return;
     }
     if (!$this->AccessToken()) {
         return;
     }
     $ShareFacebook = GetValueR('FormPostValues.ShareFacebook', $Args);
     if ($ShareFacebook) {
         $Row = $Args['FormPostValues'];
         $DiscussionModel = new DiscussionModel();
         $Discussion = $DiscussionModel->GetID(GetValue('DiscussionID', $Row));
         if (!$Discussion) {
             die('no discussion');
         }
         $Url = DiscussionUrl($Discussion, '', TRUE);
         $Message = SliceParagraph(Gdn_Format::PlainText($Row['Body'], $Row['Format']), 160);
         if ($this->AccessToken()) {
             $R = $this->API('/me/feed', array('link' => $Url, 'message' => $Message));
         }
     }
 }
 /**
  * Write the accept/reject buttons.
  * @staticvar null $DiscussionModel
  * @staticvar boolean $InformMessage
  * @param type $Sender
  * @param type $Args
  * @return type
  */
 public function DiscussionController_AfterCommentBody_Handler($Sender, $Args)
 {
     $Discussion = $Sender->Data('Discussion');
     $Comment = GetValue('Comment', $Args);
     if (!$Comment) {
         return;
     }
     $CommentID = GetValue('CommentID', $Comment);
     if (!is_numeric($CommentID)) {
         return;
     }
     if (!$Discussion) {
         static $DiscussionModel = NULL;
         if ($DiscussionModel === NULL) {
             $DiscussionModel = new DiscussionModel();
         }
         $Discussion = $DiscussionModel->GetID(GetValue('DiscussionID', $Comment));
     }
     if (!$Discussion || strtolower(GetValue('Type', $Discussion)) != 'question') {
         return;
     }
     // Check permissions.
     $CanAccept = Gdn::Session()->CheckPermission('Garden.Moderation.Manage');
     $CanAccept |= Gdn::Session()->UserID == GetValue('InsertUserID', $Discussion) && Gdn::Session()->UserID != GetValue('InsertUserID', $Comment);
     if (!$CanAccept) {
         return;
     }
     $QnA = GetValue('QnA', $Comment);
     if ($QnA) {
         return;
     }
     // Write the links.
     //      $Types = GetValue('ReactionTypes', $Sender->EventArguments);
     //      if ($Types)
     //         echo Bullet();
     $Query = http_build_query(array('commentid' => $CommentID, 'tkey' => Gdn::Session()->TransientKey()));
     echo '<div class="ActionBlock QnA-Feedback">';
     //      echo '<span class="FeedbackLabel">'.T('Feedback').'</span>';
     echo '<span class="DidThisAnswer">' . T('Did this answer the question?') . '</span> ';
     echo '<span class="QnA-YesNo">';
     echo Anchor(T('Yes'), '/discussion/qna/accept?' . $Query, array('class' => 'React QnA-Yes', 'title' => T('Accept this answer.')));
     echo ' ' . Bullet() . ' ';
     echo Anchor(T('No'), '/discussion/qna/reject?' . $Query, array('class' => 'React QnA-No', 'title' => T('Reject this answer.')));
     echo '</span>';
     echo '</div>';
     //      static $InformMessage = TRUE;
     //
     //      if ($InformMessage && Gdn::Session()->UserID == GetValue('InsertUserID', $Discussion) && in_array(GetValue('QnA', $Discussion), array('', 'Answered'))) {
     //         $Sender->InformMessage(T('Click accept or reject beside an answer.'), 'Dismissable');
     //         $InformMessage = FALSE;
     //      }
 }
 /**
  * Increment/decrement discussion scores
  */
 public function DiscussionController_VoteDiscussion_Create($Sender)
 {
     //		if (!C('Plugins.Voting.Enabled'))
     //			return;
     $DiscussionID = GetValue(0, $Sender->RequestArgs, 0);
     $TransientKey = GetValue(1, $Sender->RequestArgs);
     $VoteType = FALSE;
     if ($TransientKey == 'voteup' || $TransientKey == 'votedown') {
         $VoteType = $TransientKey;
         $TransientKey = GetValue(2, $Sender->RequestArgs);
     }
     $Session = Gdn::Session();
     $NewUserVote = 0;
     $Total = 0;
     if ($Session->IsValid() && $Session->ValidateTransientKey($TransientKey) && $DiscussionID > 0) {
         $DiscussionModel = new DiscussionModel();
         $OldUserVote = $DiscussionModel->GetUserScore($DiscussionID, $Session->UserID);
         if ($VoteType == 'voteup') {
             $NewUserVote = 1;
         } else {
             if ($VoteType == 'votedown') {
                 $NewUserVote = -1;
             } else {
                 $NewUserVote = $OldUserVote == 1 ? -1 : 1;
             }
         }
         $FinalVote = intval($OldUserVote) + intval($NewUserVote);
         // Allow admins to vote unlimited.
         $AllowVote = $Session->CheckPermission('Garden.Moderation.Manage');
         // Only allow users to vote up or down by 1.
         if (!$AllowVote) {
             $AllowVote = $FinalVote > -2 && $FinalVote < 2;
         }
         if ($AllowVote) {
             $Total = $DiscussionModel->SetUserScore($DiscussionID, $Session->UserID, $FinalVote);
         } else {
             $Discussion = $DiscussionModel->GetID($DiscussionID);
             $Total = GetValue('Score', $Discussion, 0);
             $FinalVote = $OldUserVote;
         }
         // Move the comment into or out of moderation.
         if (class_exists('LogModel')) {
             $Moderate = FALSE;
             if ($Total <= C('Plugins.Voting.ModThreshold1', -10)) {
                 $LogOptions = array('GroupBy' => array('RecordID'));
                 // Get the comment row.
                 if (isset($Discussion)) {
                     $Data = (array) $Discussion;
                 } else {
                     $Data = (array) $DiscussionModel->GetID($DiscussionID);
                 }
                 if ($Data) {
                     // Get the users that voted the comment down.
                     $OtherUserIDs = $DiscussionModel->SQL->Select('UserID')->From('UserComment')->Where('CommentID', $DiscussionID)->Where('Score <', 0)->Get()->ResultArray();
                     $OtherUserIDs = array_column($OtherUserIDs, 'UserID');
                     $LogOptions['OtherUserIDs'] = $OtherUserIDs;
                     // Add the comment to moderation.
                     if ($Total > C('Plugins.Voting.ModThreshold2', -20)) {
                         LogModel::Insert('Moderate', 'Discussion', $Data, $LogOptions);
                     }
                 }
                 $Moderate = TRUE;
             }
             if ($Total <= C('Plugins.Voting.ModThreshold2', -20)) {
                 // Remove the comment.
                 $DiscussionModel->Delete($DiscussionID, array('Log' => 'Moderate'));
                 $Sender->InformMessage(sprintf(T('The %s has been removed for moderation.'), T('discussion')));
             } elseif ($Moderate) {
                 $Sender->InformMessage(sprintf(T('The %s has been flagged for moderation.'), T('discussion')));
             }
         }
     }
     $Sender->DeliveryType(DELIVERY_TYPE_BOOL);
     $Sender->SetJson('TotalScore', $Total);
     $Sender->SetJson('FinalVote', $FinalVote);
     $Sender->Render();
 }
 /**
  * Handle flagging process in a discussion.
  */
 public function DiscussionController_Flag_Create($Sender)
 {
     if (!C('Plugins.Flagging.Enabled')) {
         return;
     }
     // Signed in users only.
     if (!($UserID = Gdn::Session()->UserID)) {
         return;
     }
     $UserName = Gdn::Session()->User->Name;
     $Arguments = $Sender->RequestArgs;
     if (sizeof($Arguments) != 5) {
         return;
     }
     list($Context, $ElementID, $ElementAuthorID, $ElementAuthor, $EncodedURL) = $Arguments;
     $URL = base64_decode(str_replace('-', '=', $EncodedURL));
     $Sender->SetData('Plugin.Flagging.Data', array('Context' => $Context, 'ElementID' => $ElementID, 'ElementAuthorID' => $ElementAuthorID, 'ElementAuthor' => $ElementAuthor, 'URL' => $URL, 'UserID' => $UserID, 'UserName' => $UserName));
     if ($Sender->Form->AuthenticatedPostBack()) {
         $SQL = Gdn::SQL();
         $Comment = $Sender->Form->GetValue('Plugin.Flagging.Reason');
         $Sender->SetData('Plugin.Flagging.Reason', $Comment);
         $CreateDiscussion = C('Plugins.Flagging.UseDiscussions');
         if ($CreateDiscussion) {
             // Category
             $CategoryID = C('Plugins.Flagging.CategoryID');
             // New discussion name
             if ($Context == 'comment') {
                 $Result = $SQL->Select('d.Name')->Select('c.Body')->From('Comment c')->Join('Discussion d', 'd.DiscussionID = c.DiscussionID', 'left')->Where('c.CommentID', $ElementID)->Get()->FirstRow();
             } elseif ($Context == 'discussion') {
                 $DiscussionModel = new DiscussionModel();
                 $Result = $DiscussionModel->GetID($ElementID);
             }
             $DiscussionName = GetValue('Name', $Result);
             $PrefixedDiscussionName = T('FlagPrefix', 'FLAG: ') . $DiscussionName;
             // Prep data for the template
             $Sender->SetData('Plugin.Flagging.Report', array('DiscussionName' => $DiscussionName, 'FlaggedContent' => GetValue('Body', $Result)));
             // Assume no discussion exists
             $this->DiscussionID = NULL;
             // Get discussion ID if already flagged
             $FlagResult = Gdn::SQL()->Select('DiscussionID')->From('Flag fl')->Where('ForeignType', $Context)->Where('ForeignID', $ElementID)->Get()->FirstRow();
             if ($FlagResult) {
                 // New comment in existing discussion
                 $DiscussionID = $FlagResult->DiscussionID;
                 $ReportBody = $Sender->FetchView($this->GetView('reportcomment.php'));
                 $SQL->Insert('Comment', array('DiscussionID' => $DiscussionID, 'InsertUserID' => $UserID, 'Body' => $ReportBody, 'Format' => 'Html', 'DateInserted' => date('Y-m-d H:i:s')));
                 $CommentModel = new CommentModel();
                 $CommentModel->UpdateCommentCount($DiscussionID);
             } else {
                 // New discussion body
                 $ReportBody = $Sender->FetchView($this->GetView('report.php'));
                 $DiscussionID = $SQL->Insert('Discussion', array('InsertUserID' => $UserID, 'UpdateUserID' => $UserID, 'CategoryID' => $CategoryID, 'Name' => $PrefixedDiscussionName, 'Body' => $ReportBody, 'Format' => 'Html', 'CountComments' => 1, 'DateInserted' => date('Y-m-d H:i:s'), 'DateUpdated' => date('Y-m-d H:i:s'), 'DateLastComment' => date('Y-m-d H:i:s')));
                 // Update discussion count
                 $DiscussionModel = new DiscussionModel();
                 $DiscussionModel->UpdateDiscussionCount($CategoryID);
             }
         }
         try {
             // Insert the flag
             $SQL->Insert('Flag', array('DiscussionID' => $DiscussionID, 'InsertUserID' => $UserID, 'InsertName' => $UserName, 'AuthorID' => $ElementAuthorID, 'AuthorName' => $ElementAuthor, 'ForeignURL' => $URL, 'ForeignID' => $ElementID, 'ForeignType' => $Context, 'Comment' => $Comment, 'DateInserted' => date('Y-m-d H:i:s')));
         } catch (Exception $e) {
         }
         // Notify users with permission who've chosen to be notified
         if (!$FlagResult) {
             // Only send if this is first time it's being flagged.
             $Sender->SetData('Plugin.Flagging.DiscussionID', $DiscussionID);
             $Subject = isset($PrefixedDiscussionName) ? $PrefixedDiscussionName : T('FlagDiscussion', 'A discussion was flagged');
             $EmailBody = $Sender->FetchView($this->GetView('reportemail.php'));
             $NotifyUsers = C('Plugins.Flagging.NotifyUsers', array());
             // Send emails
             $UserModel = new UserModel();
             foreach ($NotifyUsers as $UserID) {
                 $User = $UserModel->GetID($UserID);
                 $Email = new Gdn_Email();
                 $Email->To($User->Email)->Subject(sprintf(T('[%1$s] %2$s'), Gdn::Config('Garden.Title'), $Subject))->Message($EmailBody)->Send();
             }
         }
         $Sender->InformMessage(T('FlagSent', "Your complaint has been registered."));
     }
     $Sender->Render($this->GetView('flag.php'));
 }
 /**
  * Form to confirm that the administrator wants to delete the selected
  * comments (and has permission to do so).
  */
 public function ConfirmCommentDeletes($DiscussionID = '')
 {
     $Session = Gdn::Session();
     $this->Form = new Gdn_Form();
     $DiscussionModel = new DiscussionModel();
     $Discussion = $DiscussionModel->GetID($DiscussionID);
     if (!$Discussion) {
         return;
     }
     // Verify that the user has permission to perform the delete
     $PermissionCategory = CategoryModel::Categories($Discussion->CategoryID);
     $this->Permission('Vanilla.Comments.Delete', TRUE, 'Category', GetValue('PermissionCategoryID', $PermissionCategory));
     $this->Title(T('Confirm'));
     $CheckedComments = Gdn::UserModel()->GetAttribute($Session->User->UserID, 'CheckedComments', array());
     if (!is_array($CheckedComments)) {
         $CheckedComments = array();
     }
     $CommentIDs = array();
     $DiscussionIDs = array();
     foreach ($CheckedComments as $DiscID => $Comments) {
         foreach ($Comments as $Comment) {
             if (substr($Comment, 0, 11) == 'Discussion_') {
                 $DiscussionIDs[] = str_replace('Discussion_', '', $Comment);
             } else {
                 if ($DiscID == $DiscussionID) {
                     $CommentIDs[] = str_replace('Comment_', '', $Comment);
                 }
             }
         }
     }
     $CountCheckedComments = count($CommentIDs);
     $this->SetData('CountCheckedComments', $CountCheckedComments);
     if ($this->Form->AuthenticatedPostBack()) {
         // Delete the selected comments
         $CommentModel = new CommentModel();
         foreach ($CommentIDs as $CommentID) {
             $CommentModel->Delete($CommentID);
         }
         // Clear selections
         unset($CheckedComments[$DiscussionID]);
         Gdn::UserModel()->SaveAttribute($Session->UserID, 'CheckedComments', $CheckedComments);
         ModerationController::InformCheckedComments($this);
         $this->RedirectUrl = 'discussions';
     }
     $this->Render();
 }
 /**
  * @param PostController $Sender
  * @param array $Args
  * @return mixed
  */
 public function PostController_Comment_Create($Sender, $Args = array())
 {
     if ($Sender->Form->AuthenticatedPostBack()) {
         $Sender->Form->SetModel($Sender->CommentModel);
         // Grab the discussion for use later.
         $DiscussionID = $Sender->Form->GetFormValue('DiscussionID');
         $DiscussionModel = new DiscussionModel();
         $Discussion = $DiscussionModel->GetID($DiscussionID);
         // Check to see if the discussion is supposed to be in private...
         $WhisperConversationID = GetValueR('Attributes.WhisperConversationID', $Discussion);
         if ($WhisperConversationID === TRUE) {
             // There isn't a conversation so we want to create one.
             $Sender->Form->SetFormValue('Whisper', TRUE);
             $WhisperUserIDs = GetValueR('Attributes.WhisperUserIDs', $Discussion);
             $Sender->Form->SetFormValue('RecipientUserID', $WhisperUserIDs);
         } elseif ($WhisperConversationID) {
             // There is already a conversation.
             $Sender->Form->SetFormValue('Whisper', TRUE);
             $Sender->Form->SetFormValue('ConversationID', $WhisperConversationID);
         }
         $Whisper = $Sender->Form->GetFormValue('Whisper') && GetIncomingValue('Type') != 'Draft';
         $WhisperTo = trim($Sender->Form->GetFormValue('To'));
         $ConversationID = $Sender->Form->GetFormValue('ConversationID');
         // If this isn't a whisper then post as normal.
         if (!$Whisper) {
             return call_user_func_array(array($Sender, 'Comment'), $Args);
         }
         $ConversationModel = new ConversationModel();
         $ConversationMessageModel = new ConversationMessageModel();
         if ($ConversationID > 0) {
             $Sender->Form->SetModel($ConversationMessageModel);
         } else {
             // We have to remove the blank conversation ID or else the model won't validate.
             $FormValues = $Sender->Form->FormValues();
             unset($FormValues['ConversationID']);
             $FormValues['Subject'] = GetValue('Name', $Discussion);
             $Sender->Form->FormValues($FormValues);
             $Sender->Form->SetModel($ConversationModel);
             $ConversationModel->Validation->ApplyRule('DiscussionID', 'Required');
         }
         $ID = $Sender->Form->Save($ConversationMessageModel);
         if ($Sender->Form->ErrorCount() > 0) {
             $Sender->ErrorMessage($Sender->Form->Errors());
         } else {
             if ($WhisperConversationID === TRUE) {
                 $Discussion->Attributes['WhisperConversationID'] = $ID;
                 $DiscussionModel->SetProperty($DiscussionID, 'Attributes', serialize($Discussion->Attributes));
             }
             $LastCommentID = GetValue('LastCommentID', $Discussion);
             $MessageID = GetValue('LastMessageID', $ConversationMessageModel, FALSE);
             // Randomize the querystring to force the browser to refresh.
             $Rand = mt_rand(10000, 99999);
             if ($LastCommentID) {
                 // Link to the last comment.
                 $HashID = $MessageID ? 'w' . $MessageID : $LastCommentID;
                 $Sender->RedirectUrl = Url("discussion/comment/{$LastCommentID}?rand={$Rand}#Comment_{$HashID}", TRUE);
             } else {
                 // Link to the discussion.
                 $Hash = $MessageID ? "Comment_w{$MessageID}" : 'Item_1';
                 $Name = rawurlencode(GetValue('Name', $Discussion, 'x'));
                 $Sender->RedirectUrl = Url("discussion/{$DiscussionID}/{$Name}?rand={$Rand}#{$Hash}", TRUE);
             }
         }
         $Sender->Render();
     } else {
         return call_user_func_array(array($Sender, 'Comment'), $Args);
     }
 }
   /**
    * Add a method to the ModerationController to handle splitting comments out to a new discussion.
    */
   public function ModerationController_SplitComments_Create($Sender) {
      $Session = Gdn::Session();
      $Sender->Form = new Gdn_Form();
      $Sender->Title(T('Split Comments'));
      $Sender->Category = FALSE;

      $DiscussionID = GetValue('0', $Sender->RequestArgs, '');
      if (!is_numeric($DiscussionID))
         return;
      
      $DiscussionModel = new DiscussionModel();
      $Discussion = $DiscussionModel->GetID($DiscussionID);
      if (!$Discussion)
         return;
      
      // Verify that the user has permission to perform the split
      $Sender->Permission('Vanilla.Discussion.Edit', TRUE, 'Category', $Discussion->CategoryID);
      
      $CheckedComments = Gdn::UserModel()->GetAttribute($Session->User->UserID, 'CheckedComments', array());
      if (!is_array($CheckedComments))
         $CheckedComments = array();
       
      $CommentIDs = array();
      foreach ($CheckedComments as $DiscID => $Comments) {
         foreach ($Comments as $Comment) {
            if (substr($Comment, 0, 8) == 'Comment_' && $DiscID == $DiscussionID)
               $CommentIDs[] = str_replace('Comment_', '', $Comment);
         }
      }
      // Load category data
      $Sender->ShowCategorySelector = (bool)C('Vanilla.Categories.Use');
      if ($Sender->ShowCategorySelector) {
         $CategoryModel = new CategoryModel();
         $CategoryData = $CategoryModel->GetFull('', 'Vanilla.Discussions.Add');
         $aCategoryData = array();
         foreach ($CategoryData->Result() as $Category) {
            if ($Category->CategoryID <= 0)
               continue;
            
            if ($Discussion->CategoryID == $Category->CategoryID)
               $Sender->Category = $Category;
            
            $CategoryName = $Category->Name;   
            if ($Category->Depth > 1) {
               $CategoryName = '↳ '.$CategoryName;
               $CategoryName = str_pad($CategoryName, strlen($CategoryName) + $Category->Depth - 2, ' ', STR_PAD_LEFT);
               $CategoryName = str_replace(' ', '&#160;', $CategoryName);
            }
            $aCategoryData[$Category->CategoryID] = $CategoryName;
            $Sender->EventArguments['aCategoryData'] = &$aCategoryData;
				$Sender->EventArguments['Category'] = &$Category;
				$Sender->FireEvent('AfterCategoryItem');
         }
         $Sender->CategoryData = $aCategoryData;
      }
      
      $CountCheckedComments = count($CommentIDs);
      $Sender->SetData('CountCheckedComments', $CountCheckedComments);
      // Perform the split
      if ($Sender->Form->AuthenticatedPostBack()) {
         // Create a new discussion record
         $Data = $Sender->Form->FormValues();
         $Data['Body'] = sprintf(T('This discussion was created from comments split from: %s.'), Anchor(Gdn_Format::Text($Discussion->Name), 'discussion/'.$Discussion->DiscussionID.'/'.Gdn_Format::Url($Discussion->Name).'/'));
         $NewDiscussionID = $DiscussionModel->Save($Data);
         $Sender->Form->SetValidationResults($DiscussionModel->ValidationResults());
         
         if ($Sender->Form->ErrorCount() == 0 && $NewDiscussionID > 0) {
            // Re-assign the comments to the new discussion record
            $DiscussionModel->SQL
               ->Update('Comment')
               ->Set('DiscussionID', $NewDiscussionID)
               ->WhereIn('CommentID', $CommentIDs)
               ->Put();
            
            // Update counts on both discussions
            $CommentModel = new CommentModel();
            $CommentModel->UpdateCommentCount($DiscussionID);
            $CommentModel->UpdateUserCommentCounts($DiscussionID);
            $CommentModel->UpdateCommentCount($NewDiscussionID);
   
            // Clear selections
            unset($CheckedComments[$DiscussionID]);
            Gdn::UserModel()->SaveAttribute($Session->UserID, 'CheckedComments', $CheckedComments);
            ModerationController::InformCheckedComments($Sender);
            $Sender->RedirectUrl = Url('discussion/'.$NewDiscussionID.'/'.Gdn_Format::Url($Data['Name']));
         }
      }
      
      $Sender->Render($this->GetView('splitcomments.php'));
   }