save() public method

Events: BeforeSaveDiscussion, AfterValidateDiscussion, AfterSaveDiscussion.
public save ( array $FormPostValues, array $Settings = false ) : integer
$FormPostValues array Data sent from the form model.
$Settings array Currently unused.
return integer $DiscussionID Unique ID of the discussion.
Esempio n. 1
0
 /**
  * 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('autosave.js');
     $this->addJsFile('post.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;
     $CategoryModel = new CategoryModel();
     if (isset($this->Discussion)) {
         $this->CategoryID = $this->Discussion->CategoryID;
         $Category = CategoryModel::categories($this->CategoryID);
     } elseif ($CategoryUrlCode != '') {
         $Category = CategoryModel::categories($CategoryUrlCode);
         if ($Category) {
             $this->CategoryID = val('CategoryID', $Category);
         }
     }
     if ($Category) {
         $this->Category = (object) $Category;
         $this->setData('Category', $Category);
         $this->Form->addHidden('CategoryID', $this->Category->CategoryID);
         if (val('DisplayAs', $this->Category) == 'Discussions' && !$DraftID) {
             $this->ShowCategorySelector = false;
         } else {
             // Get all our subcategories to add to the category if we are in a Header or Categories category.
             $this->Context = CategoryModel::getSubtree($this->CategoryID);
         }
     } else {
         $this->CategoryID = 0;
         $this->Category = null;
     }
     $CategoryData = $this->ShowCategorySelector ? CategoryModel::categories() : false;
     // Check permission
     if (isset($this->Discussion)) {
         // Make sure that content can (still) be edited.
         $CanEdit = DiscussionModel::canEdit($this->Discussion);
         if (!$CanEdit) {
             throw permissionException('Vanilla.Discussions.Edit');
         }
         // 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.
         if ($this->Category) {
             $this->permission('Vanilla.Discussions.Add', true, 'Category', $this->Category->PermissionCategoryID);
         } else {
             $this->permission('Vanilla.Discussions.Add');
         }
         $this->title(t('New Discussion'));
     }
     touchValue('Type', $this->Data, 'Discussion');
     // See if we should hide the category dropdown.
     if ($this->ShowCategorySelector) {
         $AllowedCategories = CategoryModel::getByPermission('Discussions.Add', $this->Form->getValue('CategoryID', $this->CategoryID), ['Archived' => 0, 'AllowDiscussions' => 1], ['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()) {
         // 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);
         }
     } elseif ($this->Form->authenticatedPostBack()) {
         // Form was submitted
         // Save as a draft?
         $FormValues = $this->Form->formValues();
         $FormValues = $this->DiscussionModel->filterForm($FormValues);
         $this->deliveryType(Gdn::request()->getValue('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 = val($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');
                 }
             }
             $isTitleValid = true;
             $Name = trim($this->Form->getFormValue('Name', ''));
             if (!$Draft) {
                 // Let's be super aggressive and disallow titles with no word characters in them!
                 $hasWordCharacter = preg_match('/\\w/u', $Name) === 1;
                 if (!$hasWordCharacter || $Name != '' && Gdn_Format::text($Name) == '') {
                     $this->Form->addError(t('You have entered an invalid discussion title'), 'Name');
                     $isTitleValid = false;
                 }
             }
             if ($isTitleValid) {
                 // 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->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.');
                         // Clear out the form so that a draft won't save.
                         $this->Form->formValues(array());
                         $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 = val('Body', $FormValues, '');
             $this->Comment->Format = val('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());
         } elseif ($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, 1)) . '?new=1';
                     } else {
                         $this->RedirectUrl = discussionUrl($Discussion, 1, 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' => val('AddUrl', val($this->data('Type'), DiscussionModel::discussionTypes()), '/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 = val('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';
         $Data['Type'] = 'Discussion';
         $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);
             $CommentModel->removePageCache($DiscussionID, 1);
             // 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', val('CategoryID', $Discussion));
     }
     $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();
     $CategoryModel = new CategoryModel();
     $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, CountComments')->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.'));
         }
         $AffectedCategories = array();
         // Iterate and move.
         foreach ($AllowedDiscussions as $DiscussionID) {
             $Discussion = val($DiscussionID, $DiscussionData);
             // Create the shadow redirect.
             if ($RedirectLink) {
                 $DiscussionModel->defineSchema();
                 $MaxNameLength = val('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);
                 // Pass a forced input formatter around this exception.
                 if (c('Garden.ForceInputFormatter')) {
                     $InputFormat = c('Garden.InputFormatter');
                     saveToConfig('Garden.InputFormatter', 'Html', false);
                 }
                 $RedirectID = $DiscussionModel->save($RedirectDiscussion);
                 // Reset the input formatter
                 if (c('Garden.ForceInputFormatter')) {
                     saveToConfig('Garden.InputFormatter', $InputFormat, false);
                 }
                 if (!$RedirectID) {
                     $this->Form->setValidationResults($DiscussionModel->validationResults());
                     break;
                 }
             }
             $DiscussionModel->setField($DiscussionID, 'CategoryID', $CategoryID);
             if (!isset($AffectedCategories[$Discussion['CategoryID']])) {
                 $AffectedCategories[$Discussion['CategoryID']] = array(-1, -$Discussion['CountComments']);
             } else {
                 $AffectedCategories[$Discussion['CategoryID']][0] -= 1;
                 $AffectedCategories[$Discussion['CategoryID']][1] -= $Discussion['CountComments'];
             }
             if (!isset($AffectedCategories[$CategoryID])) {
                 $AffectedCategories[$CategoryID] = array(1, $Discussion['CountComments']);
             } else {
                 $AffectedCategories[$CategoryID][0] += 1;
                 $AffectedCategories[$CategoryID][1] += $Discussion['CountComments'];
             }
         }
         // Update recent posts and counts on all affected categories.
         foreach ($AffectedCategories as $CategoryID => $Counts) {
             $CategoryModel->SetRecentPost($CategoryID);
             $CategoryModel->SQL->update('Category')->set('CountDiscussions', 'CountDiscussions' . ($Counts[0] < 0 ? ' - ' : ' + ') . abs($Counts[0]), false)->set('CountComments', 'CountComments' . ($Counts[1] < 0 ? ' - ' : ' + ') . abs($Counts[1]), false)->where('CategoryID', $CategoryID)->put();
         }
         // Clear selections.
         if ($ClearSelection) {
             Gdn::userModel()->saveAttribute($Session->UserID, 'CheckedDiscussions', false);
             ModerationController::InformCheckedDiscussions($this);
         }
         if ($this->Form->errorCount() == 0) {
             $this->jsonTarget('', '', 'Refresh');
         }
     }
     $this->render();
 }
Esempio n. 4
0
 /**
  *
  *
  * @return bool
  * @throws Exception
  * @throws Gdn_UserException
  */
 public function commit()
 {
     if (is_null($this->Type)) {
         throw new Exception(T("Adding a Regarding event requires a type."));
     }
     if (is_null($this->ForeignType)) {
         throw new Exception(T("Adding a Regarding event requires a foreign association type."));
     }
     if (is_null($this->ForeignID)) {
         throw new Exception(T("Adding a Regarding event requires a foreign association id."));
     }
     if (is_null($this->Comment)) {
         throw new Exception(T("Adding a Regarding event requires a comment."));
     }
     if (is_null($this->UserID)) {
         $this->UserID = Gdn::session()->UserID;
     }
     $RegardingModel = new RegardingModel();
     $CollapseMode = c('Garden.Regarding.AutoCollapse', true);
     $Collapse = false;
     if ($CollapseMode) {
         // Check for an existing report of this type
         $ExistingRegardingEntity = $RegardingModel->getRelated($this->Type, $this->ForeignType, $this->ForeignID);
         if ($ExistingRegardingEntity) {
             $Collapse = true;
             $RegardingID = val('RegardingID', $ExistingRegardingEntity);
         }
     }
     if (!$Collapse) {
         // Create a new Regarding entry
         $RegardingPreSend = array('Type' => $this->Type, 'ForeignType' => $this->ForeignType, 'ForeignID' => $this->ForeignID, 'InsertUserID' => $this->UserID, 'DateInserted' => date('Y-m-d H:i:s'), 'ParentType' => $this->ParentType, 'ParentID' => $this->ParentID, 'ForeignURL' => $this->ForeignURL, 'Comment' => $this->Comment, 'OriginalContent' => $this->OriginalContent, 'Reports' => 1);
         $RegardingID = $RegardingModel->save($RegardingPreSend);
         if (!$RegardingID) {
             return false;
         }
     }
     // Handle collaborations
     // Don't error on foreach
     if (!is_array($this->CollaborativeActions)) {
         $this->CollaborativeActions = array();
     }
     foreach ($this->CollaborativeActions as $Action) {
         $ActionType = val('Type', $Action);
         switch ($ActionType) {
             case 'discussion':
                 $DiscussionModel = new DiscussionModel();
                 if ($Collapse) {
                     $Discussion = Gdn::SQL()->select('*')->from('Discussion')->where(array('RegardingID' => $RegardingID))->get()->firstRow(DATASET_TYPE_ARRAY);
                 }
                 if (!$Collapse || !$Discussion) {
                     $CategoryID = val('Parameters', $Action);
                     // Make a new discussion
                     $DiscussionID = $DiscussionModel->save(array('Name' => $this->CollaborativeTitle, 'CategoryID' => $CategoryID, 'Body' => $this->OriginalContent, 'InsertUserID' => val('InsertUserID', $this->SourceElement), 'Announce' => 0, 'Close' => 0, 'RegardingID' => $RegardingID));
                     if (!$DiscussionID) {
                         throw new Gdn_UserException($DiscussionModel->Validation->resultsText());
                     }
                     $DiscussionModel->updateDiscussionCount($CategoryID);
                 } else {
                     // Add a comment to the existing discussion.
                     $CommentModel = new CommentModel();
                     $CommentID = $CommentModel->save(array('DiscussionID' => val('DiscussionID', $Discussion), 'Body' => $this->Comment, 'InsertUserID' => $this->UserID));
                     $CommentModel->save2($CommentID, true);
                 }
                 break;
             case 'conversation':
                 $ConversationModel = new ConversationModel();
                 $ConversationMessageModel = new ConversationMessageModel();
                 $Users = val('Parameters', $Action);
                 $UserList = explode(',', $Users);
                 if (!sizeof($UserList)) {
                     throw new Exception(sprintf(T("The userlist provided for collaboration on '%s:%s' is invalid.", $this->Type, $this->ForeignType)));
                 }
                 $ConversationID = $ConversationModel->save(array('To' => 'Admins', 'Body' => $this->CollaborativeTitle, 'RecipientUserID' => $UserList, 'RegardingID' => $RegardingID), $ConversationMessageModel);
                 break;
         }
     }
     return true;
 }