/**
  * 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'));
 }
 /**
  * Create or update a discussion.
  *
  * @since 2.0.0
  * @access public
  *
  * @param int $CategoryID Unique ID of the category to add the discussion to.
  */
 public function Discussion($CategoryUrlCode = '')
 {
     // Override CategoryID if categories are disabled
     $UseCategories = $this->ShowCategorySelector = (bool) C('Vanilla.Categories.Use');
     if (!$UseCategories) {
         $CategoryUrlCode = '';
     }
     // Setup head
     $this->AddJsFile('jquery.autosize.min.js');
     $this->AddJsFile('post.js');
     $this->AddJsFile('autosave.js');
     $Session = Gdn::Session();
     Gdn_Theme::Section('PostDiscussion');
     // Set discussion, draft, and category data
     $DiscussionID = isset($this->Discussion) ? $this->Discussion->DiscussionID : '';
     $DraftID = isset($this->Draft) ? $this->Draft->DraftID : 0;
     $Category = FALSE;
     if (isset($this->Discussion)) {
         $this->CategoryID = $this->Discussion->CategoryID;
         $Category = CategoryModel::Categories($this->CategoryID);
     } else {
         if ($CategoryUrlCode != '') {
             $CategoryModel = new CategoryModel();
             $Category = $CategoryModel->GetByCode($CategoryUrlCode);
             $this->CategoryID = $Category->CategoryID;
         }
     }
     if ($Category) {
         $this->Category = (object) $Category;
         $this->SetData('Category', $Category);
     } else {
         $this->CategoryID = 0;
         $this->Category = NULL;
     }
     $CategoryData = $UseCategories ? CategoryModel::Categories() : FALSE;
     // Check permission
     if (isset($this->Discussion)) {
         // Permission to edit
         if ($this->Discussion->InsertUserID != $Session->UserID) {
             $this->Permission('Vanilla.Discussions.Edit', TRUE, 'Category', $this->Category->PermissionCategoryID);
         }
         // Make sure that content can (still) be edited.
         $EditContentTimeout = C('Garden.EditContentTimeout', -1);
         $CanEdit = $EditContentTimeout == -1 || strtotime($this->Discussion->DateInserted) + $EditContentTimeout > time();
         if (!$CanEdit) {
             $this->Permission('Vanilla.Discussions.Edit', TRUE, 'Category', $this->Category->PermissionCategoryID);
         }
         // Make sure only moderators can edit closed things
         if ($this->Discussion->Closed) {
             $this->Permission('Vanilla.Discussions.Edit', TRUE, 'Category', $this->Category->PermissionCategoryID);
         }
         $this->Form->SetFormValue('DiscussionID', $this->Discussion->DiscussionID);
         $this->Title(T('Edit Discussion'));
         if ($this->Discussion->Type) {
             $this->SetData('Type', $this->Discussion->Type);
         } else {
             $this->SetData('Type', 'Discussion');
         }
     } else {
         // Permission to add
         $this->Permission('Vanilla.Discussions.Add');
         $this->Title(T('New Discussion'));
     }
     TouchValue('Type', $this->Data, 'Discussion');
     // See if we should hide the category dropdown.
     $AllowedCategories = CategoryModel::GetByPermission('Discussions.Add', $this->Form->GetValue('CategoryID', $this->CategoryID), array('Archived' => 0, 'AllowDiscussions' => 1), array('AllowedDiscussionTypes' => $this->Data['Type']));
     if (count($AllowedCategories) == 1) {
         $AllowedCategory = array_pop($AllowedCategories);
         $this->ShowCategorySelector = FALSE;
         $this->Form->AddHidden('CategoryID', $AllowedCategory['CategoryID']);
         if ($this->Form->IsPostBack() && !$this->Form->GetFormValue('CategoryID')) {
             $this->Form->SetFormValue('CategoryID', $AllowedCategory['CategoryID']);
         }
     }
     // Set the model on the form
     $this->Form->SetModel($this->DiscussionModel);
     if ($this->Form->IsPostBack() == FALSE) {
         // Prep form with current data for editing
         if (isset($this->Discussion)) {
             $this->Form->SetData($this->Discussion);
         } elseif (isset($this->Draft)) {
             $this->Form->SetData($this->Draft);
         } else {
             if ($this->Category !== NULL) {
                 $this->Form->SetData(array('CategoryID' => $this->Category->CategoryID));
             }
             $this->PopulateForm($this->Form);
         }
     } else {
         // Form was submitted
         // Save as a draft?
         $FormValues = $this->Form->FormValues();
         $FormValues = $this->DiscussionModel->FilterForm($FormValues);
         $this->DeliveryType(GetIncomingValue('DeliveryType', $this->_DeliveryType));
         if ($DraftID == 0) {
             $DraftID = $this->Form->GetFormValue('DraftID', 0);
         }
         $Draft = $this->Form->ButtonExists('Save Draft') ? TRUE : FALSE;
         $Preview = $this->Form->ButtonExists('Preview') ? TRUE : FALSE;
         if (!$Preview) {
             if (!is_object($this->Category) && is_array($CategoryData) && isset($FormValues['CategoryID'])) {
                 $this->Category = GetValue($FormValues['CategoryID'], $CategoryData);
             }
             if (is_object($this->Category)) {
                 // Check category permissions.
                 if ($this->Form->GetFormValue('Announce', '') && !$Session->CheckPermission('Vanilla.Discussions.Announce', TRUE, 'Category', $this->Category->PermissionCategoryID)) {
                     $this->Form->AddError('You do not have permission to announce in this category', 'Announce');
                 }
                 if ($this->Form->GetFormValue('Close', '') && !$Session->CheckPermission('Vanilla.Discussions.Close', TRUE, 'Category', $this->Category->PermissionCategoryID)) {
                     $this->Form->AddError('You do not have permission to close in this category', 'Close');
                 }
                 if ($this->Form->GetFormValue('Sink', '') && !$Session->CheckPermission('Vanilla.Discussions.Sink', TRUE, 'Category', $this->Category->PermissionCategoryID)) {
                     $this->Form->AddError('You do not have permission to sink in this category', 'Sink');
                 }
                 if (!isset($this->Discussion) && (!$Session->CheckPermission('Vanilla.Discussions.Add', TRUE, 'Category', $this->Category->PermissionCategoryID) || !$this->Category->AllowDiscussions)) {
                     $this->Form->AddError('You do not have permission to start discussions in this category', 'CategoryID');
                 }
             }
             // Make sure that the title will not be invisible after rendering
             $Name = trim($this->Form->GetFormValue('Name', ''));
             if ($Name != '' && Gdn_Format::Text($Name) == '') {
                 $this->Form->AddError(T('You have entered an invalid discussion title'), 'Name');
             } else {
                 // Trim the name.
                 $FormValues['Name'] = $Name;
                 $this->Form->SetFormValue('Name', $Name);
             }
             if ($this->Form->ErrorCount() == 0) {
                 if ($Draft) {
                     $DraftID = $this->DraftModel->Save($FormValues);
                     $this->Form->SetValidationResults($this->DraftModel->ValidationResults());
                 } else {
                     $DiscussionID = $this->DiscussionModel->Save($FormValues, $this->CommentModel);
                     $this->Form->SetValidationResults($this->DiscussionModel->ValidationResults());
                     if ($DiscussionID > 0) {
                         if ($DraftID > 0) {
                             $this->DraftModel->Delete($DraftID);
                         }
                     }
                     if ($DiscussionID == SPAM || $DiscussionID == UNAPPROVED) {
                         $this->StatusMessage = T('DiscussionRequiresApprovalStatus', 'Your discussion will appear after it is approved.');
                         $this->Render('Spam');
                         return;
                     }
                 }
             }
         } else {
             // If this was a preview click, create a discussion/comment shell with the values for this comment
             $this->Discussion = new stdClass();
             $this->Discussion->Name = $this->Form->GetValue('Name', '');
             $this->Comment = new stdClass();
             $this->Comment->InsertUserID = $Session->User->UserID;
             $this->Comment->InsertName = $Session->User->Name;
             $this->Comment->InsertPhoto = $Session->User->Photo;
             $this->Comment->DateInserted = Gdn_Format::Date();
             $this->Comment->Body = ArrayValue('Body', $FormValues, '');
             $this->Comment->Format = GetValue('Format', $FormValues, C('Garden.InputFormatter'));
             $this->EventArguments['Discussion'] =& $this->Discussion;
             $this->EventArguments['Comment'] =& $this->Comment;
             $this->FireEvent('BeforeDiscussionPreview');
             if ($this->_DeliveryType == DELIVERY_TYPE_ALL) {
                 $this->AddAsset('Content', $this->FetchView('preview'));
             } else {
                 $this->View = 'preview';
             }
         }
         if ($this->Form->ErrorCount() > 0) {
             // Return the form errors
             $this->ErrorMessage($this->Form->Errors());
         } else {
             if ($DiscussionID > 0 || $DraftID > 0) {
                 // Make sure that the ajax request form knows about the newly created discussion or draft id
                 $this->SetJson('DiscussionID', $DiscussionID);
                 $this->SetJson('DraftID', $DraftID);
                 if (!$Preview) {
                     // If the discussion was not a draft
                     if (!$Draft) {
                         // Redirect to the new discussion
                         $Discussion = $this->DiscussionModel->GetID($DiscussionID, DATASET_TYPE_OBJECT, array('Slave' => FALSE));
                         $this->SetData('Discussion', $Discussion);
                         $this->EventArguments['Discussion'] = $Discussion;
                         $this->FireEvent('AfterDiscussionSave');
                         if ($this->_DeliveryType == DELIVERY_TYPE_ALL) {
                             Redirect(DiscussionUrl($Discussion)) . '?new=1';
                         } else {
                             $this->RedirectUrl = DiscussionUrl($Discussion, '', TRUE) . '?new=1';
                         }
                     } else {
                         // If this was a draft save, notify the user about the save
                         $this->InformMessage(sprintf(T('Draft saved at %s'), Gdn_Format::Date()));
                     }
                 }
             }
         }
     }
     // Add hidden fields for editing
     $this->Form->AddHidden('DiscussionID', $DiscussionID);
     $this->Form->AddHidden('DraftID', $DraftID, TRUE);
     $this->FireEvent('BeforeDiscussionRender');
     if ($this->CategoryID) {
         $Breadcrumbs = CategoryModel::GetAncestors($this->CategoryID);
     } else {
         $Breadcrumbs = array();
     }
     $Breadcrumbs[] = array('Name' => $this->Data('Title'), 'Url' => '/post/discussion');
     $this->SetData('Breadcrumbs', $Breadcrumbs);
     $this->SetData('_AnnounceOptions', $this->AnnounceOptions());
     // Render view (posts/discussion.php or post/preview.php)
     $this->Render();
 }
   /**
    * 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'));
   }
 /**
  * Form to ask for the destination of the move, confirmation and permission check.
  */
 public function ConfirmDiscussionMoves($DiscussionID = NULL)
 {
     $Session = Gdn::Session();
     $this->Form = new Gdn_Form();
     $DiscussionModel = new DiscussionModel();
     $this->Title(T('Confirm'));
     if ($DiscussionID) {
         $CheckedDiscussions = (array) $DiscussionID;
         $ClearSelection = FALSE;
     } else {
         $CheckedDiscussions = Gdn::UserModel()->GetAttribute($Session->User->UserID, 'CheckedDiscussions', array());
         if (!is_array($CheckedDiscussions)) {
             $CheckedDiscussions = array();
         }
         $ClearSelection = TRUE;
     }
     $DiscussionIDs = $CheckedDiscussions;
     $CountCheckedDiscussions = count($DiscussionIDs);
     $this->SetData('CountCheckedDiscussions', $CountCheckedDiscussions);
     // Check for edit permissions on each discussion
     $AllowedDiscussions = array();
     $DiscussionData = $DiscussionModel->SQL->Select('DiscussionID, Name, DateLastComment, CategoryID')->From('Discussion')->WhereIn('DiscussionID', $DiscussionIDs)->Get();
     $DiscussionData = Gdn_DataSet::Index($DiscussionData->ResultArray(), array('DiscussionID'));
     foreach ($DiscussionData as $DiscussionID => $Discussion) {
         $Category = CategoryModel::Categories($Discussion['CategoryID']);
         if ($Category && $Category['PermsDiscussionsEdit']) {
             $AllowedDiscussions[] = $DiscussionID;
         }
     }
     $this->SetData('CountAllowed', count($AllowedDiscussions));
     $CountNotAllowed = $CountCheckedDiscussions - count($AllowedDiscussions);
     $this->SetData('CountNotAllowed', $CountNotAllowed);
     if ($this->Form->AuthenticatedPostBack()) {
         // Retrieve the category id
         $CategoryID = $this->Form->GetFormValue('CategoryID');
         $Category = CategoryModel::Categories($CategoryID);
         $RedirectLink = $this->Form->GetFormValue('RedirectLink');
         // User must have add permission on the target category
         if (!$Category['PermsDiscussionsAdd']) {
             throw ForbiddenException('@' . T('You do not have permission to add discussions to this category.'));
         }
         // Iterate and move.
         foreach ($AllowedDiscussions as $DiscussionID) {
             // Create the shadow redirect.
             if ($RedirectLink) {
                 $Discussion = GetValue($DiscussionID, $DiscussionData);
                 $DiscussionModel->DefineSchema();
                 $MaxNameLength = GetValue('Length', $DiscussionModel->Schema->GetField('Name'));
                 $RedirectDiscussion = array('Name' => SliceString(sprintf(T('Moved: %s'), $Discussion['Name']), $MaxNameLength), 'DateInserted' => $Discussion['DateLastComment'], 'Type' => 'redirect', 'CategoryID' => $Discussion['CategoryID'], 'Body' => FormatString(T('This discussion has been <a href="{url,html}">moved</a>.'), array('url' => DiscussionUrl($Discussion))), 'Format' => 'Html', 'Closed' => TRUE);
                 $RedirectID = $DiscussionModel->Save($RedirectDiscussion);
                 if (!$RedirectID) {
                     $this->Form->SetValidationResults($DiscussionModel->ValidationResults());
                     break;
                 }
             }
             $DiscussionModel->SetField($DiscussionID, 'CategoryID', $CategoryID);
         }
         // Clear selections.
         if ($ClearSelection) {
             Gdn::UserModel()->SaveAttribute($Session->UserID, 'CheckedDiscussions', FALSE);
             ModerationController::InformCheckedDiscussions($this);
         }
         if ($this->Form->ErrorCount() == 0) {
             $this->JsonTarget('', '', 'Refresh');
         }
     }
     $this->Render();
 }
 protected function PollFeed($FeedURL, $LastImportDate)
 {
     $Pr = new ProxyRequest();
     $FeedRSS = $Pr->Request(array('URL' => $FeedURL));
     if (!$FeedRSS) {
         return FALSE;
     }
     $RSSData = simplexml_load_string($FeedRSS);
     if (!$RSSData) {
         return FALSE;
     }
     $Channel = GetValue('channel', $RSSData, FALSE);
     if (!$Channel) {
         return FALSE;
     }
     if (!array_key_exists('item', $Channel)) {
         return FALSE;
     }
     $Feed = $this->GetFeed($FeedURL, FALSE);
     $DiscussionModel = new DiscussionModel();
     $DiscussionModel->SpamCheck = FALSE;
     $LastPublishDate = GetValue('LastPublishDate', $Feed, date('c'));
     $LastPublishTime = strtotime($LastPublishDate);
     $FeedLastPublishTime = 0;
     foreach (GetValue('item', $Channel) as $Item) {
         $FeedItemGUID = trim((string) GetValue('guid', $Item));
         if (empty($FeedItemGUID)) {
             Trace('guid is not set in each item of the RSS.  Will attempt to use link as unique identifier.');
             $FeedItemGUID = GetValue('link', $Item);
         }
         $FeedItemID = substr(md5($FeedItemGUID), 0, 30);
         $ItemPubDate = (string) GetValue('pubDate', $Item, NULL);
         if (is_null($ItemPubDate)) {
             $ItemPubTime = time();
         } else {
             $ItemPubTime = strtotime($ItemPubDate);
         }
         if ($ItemPubTime > $FeedLastPublishTime) {
             $FeedLastPublishTime = $ItemPubTime;
         }
         if ($ItemPubTime < $LastPublishTime && !$Feed['Historical']) {
             continue;
         }
         $ExistingDiscussion = $DiscussionModel->GetWhere(array('ForeignID' => $FeedItemID));
         if ($ExistingDiscussion && $ExistingDiscussion->NumRows()) {
             continue;
         }
         $this->EventArguments['Publish'] = TRUE;
         $this->EventArguments['FeedURL'] = $FeedURL;
         $this->EventArguments['Feed'] =& $Feed;
         $this->EventArguments['Item'] =& $Item;
         $this->FireEvent('FeedItem');
         if (!$this->EventArguments['Publish']) {
             continue;
         }
         $StoryTitle = array_shift($Trash = explode("\n", (string) GetValue('title', $Item)));
         $StoryBody = (string) GetValue('description', $Item);
         $StoryPublished = date("Y-m-d H:i:s", $ItemPubTime);
         $ParsedStoryBody = $StoryBody;
         $ParsedStoryBody = '<div class="AutoFeedDiscussion">' . $ParsedStoryBody . '</div> <br /><div class="AutoFeedSource">Source: ' . $FeedItemGUID . '</div>';
         $DiscussionData = array('Name' => $StoryTitle, 'Format' => 'Html', 'CategoryID' => $Feed['Category'], 'ForeignID' => substr($FeedItemID, 0, 30), 'Body' => $ParsedStoryBody);
         // Post as Minion (if one exists) or the system user
         if (Gdn::PluginManager()->CheckPlugin('Minion')) {
             $Minion = Gdn::PluginManager()->GetPluginInstance('MinionPlugin');
             $InsertUserID = $Minion->GetMinionUserID();
         } else {
             $InsertUserID = Gdn::UserModel()->GetSystemUserID();
         }
         $DiscussionData[$DiscussionModel->DateInserted] = $StoryPublished;
         $DiscussionData[$DiscussionModel->InsertUserID] = $InsertUserID;
         $DiscussionData[$DiscussionModel->DateUpdated] = $StoryPublished;
         $DiscussionData[$DiscussionModel->UpdateUserID] = $InsertUserID;
         $this->EventArguments['FeedDiscussion'] =& $DiscussionData;
         $this->FireEvent('Publish');
         if (!$this->EventArguments['Publish']) {
             continue;
         }
         $InsertID = $DiscussionModel->Save($DiscussionData);
         $this->EventArguments['DiscussionID'] = $InsertID;
         $this->EventArguments['Vaidation'] = $DiscussionModel->Validation;
         $this->FireEvent('Published');
         // Reset discussion validation
         $DiscussionModel->Validation->Results(TRUE);
     }
     $FeedKey = self::EncodeFeedKey($FeedURL);
     $this->UpdateFeed($FeedKey, array('LastImport' => date('Y-m-d H:i:s'), 'LastPublishDate' => date('c', $FeedLastPublishTime)));
 }
 /**
  * Sync a file to its discussion.
  *
  * @param $Code string
  * @parm $Name string
  * @param $Body string
  */
 public function SyncDocDiscussion($Code, $Name, $Body, $CategoryID)
 {
     $DiscussionModel = new DiscussionModel();
     $Document = $DiscussionModel->GetWhere(array('DocumentCode' => $Code))->FirstRow();
     if (!$Document) {
         // Create discussion
         $DiscussionModel->Save(array('Name' => $Name, 'Body' => $Body, 'CategoryID' => $CategoryID, 'Format' => 'Markdown', 'Type' => 'Doc', 'InsertUserID' => Gdn::UserModel()->GetSystemUserID(), 'DocumentCode' => $Code));
     } else {
         // Blindly update the discussion
         $DiscussionModel->Update(array('Name' => $Name, 'Body' => $Body, 'CategoryID' => $CategoryID), array('DiscussionID' => GetValue('DiscussionID', $Document)));
     }
 }
   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 !== FALSE)
            $Collapse = TRUE;
      }
      
      if (!$Collapse) {
         // Create a new Regarding entry
         $RegardingID = $RegardingModel->Save(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
         ));
      }
      
      // Handle collaborations
      
      // Don't error on foreach
      if (!is_array($this->CollaborativeActions))
         $this->CollaborativeActions = array();
      
      foreach ($this->CollaborativeActions as $Action) {
         $ActionType = GetValue('Type', $Action);
         switch ($ActionType) {
            case 'discussion':
               $DiscussionModel = new DiscussionModel();
               
               if (!$Collapse) {
                  $CategoryID = GetValue('Parameters', $Action);
               
                  // Make a new discussion
                  $DiscussionID = $DiscussionModel->Save(array(
                     'Name'         => $this->CollaborativeTitle,
                     'CategoryID'   => $CategoryID,
                     'Body'         => $this->OriginalContent,
                     'InsertUserID' => GetValue('InsertUserID', $this->SourceElement),
                     'Announce'     => 0,
                     'Close'        => 0,
                     'RegardingID'  => $RegardingID
                  ));
               } else {
                  // Add a comment to the existing discussion
                  
                  // First, find out which discussion it was, based on RegardingID
                  $Discussion = $DiscussionModel->GetWhere(array('RegardingID' => GetValue('RegardingID', $ExistingRegardingEntity, FALSE)))->FirstRow(DATASET_TYPE_ARRAY);
                  if ($Discussion !== FALSE) {
                     $CommentModel = new CommentModel();
                     $CommentID = $CommentModel->Save(array(
                        'DiscussionID' => GetValue('DiscussionID', $Discussion),
                        'Body'         => $this->Comment,
                        'InsertUserID' => $this->UserID
                     ));
                  }
               }
               
               break;

            case 'conversation':
                  
               $ConversationModel = new ConversationModel();
               $ConversationMessageModel = new ConversationMessageModel();
               
               $Users = GetValue('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;
   }