public function Index($Offset = 0, $Limit = NULL) {
		$this->AddJsFile('jquery.gardenmorepager.js');
		$this->AddJsFile('search.js');
		$this->Title(T('Search'));

		if(!is_numeric($Limit))
			$Limit = Gdn::Config('Garden.Search.PerPage', 20);
		
		$Search = $this->Form->GetFormValue('Search');
      $Mode = $this->Form->GetFormValue('Mode');
      if ($Mode)
         $this->SearchModel->ForceSearchMode = $Mode;
      try {
         $ResultSet = $this->SearchModel->Search($Search, $Offset, $Limit);
      } catch (Gdn_UserException $Ex) {
         $this->Form->AddError($Ex);
         $ResultSet = array();
      } catch (Exception $Ex) {
         $ResultSet = array();
      }
		$this->SetData('SearchResults', $ResultSet, TRUE);
		$this->SetData('SearchTerm', Gdn_Format::Text($Search), TRUE);
		if($ResultSet)
			$NumResults = count($ResultSet);
		else
			$NumResults = 0;
		if ($NumResults == $Offset + $Limit)
			$NumResults++;
		
		// Build a pager
		$PagerFactory = new Gdn_PagerFactory();
		$this->Pager = $PagerFactory->GetPager('MorePager', $this);
		$this->Pager->MoreCode = 'More Results';
		$this->Pager->LessCode = 'Previous Results';
		$this->Pager->ClientID = 'Pager';
		$this->Pager->Configure(
			$Offset,
			$Limit,
			$NumResults,
			'dashboard/search/%1$s/%2$s/?Search='.Gdn_Format::Url($Search)
		);
		
		if ($this->_DeliveryType != DELIVERY_TYPE_ALL) {
         $this->SetJson('LessRow', $this->Pager->ToString('less'));
         $this->SetJson('MoreRow', $this->Pager->ToString('more'));
         $this->View = 'results';
      }
		
      $this->CanonicalUrl(Url('search', TRUE));

		$this->Render();
	}
 public function RemoveAddon($Type, $Name, $TransientKey = '')
 {
     $RequiredPermission = 'Undefined';
     switch ($Type) {
         case SettingsModule::TYPE_APPLICATION:
             $Manager = Gdn::Factory('ApplicationManager');
             $Enabled = 'EnabledApplications';
             $Remove = 'RemoveApplication';
             $RequiredPermission = 'Garden.Applications.Manage';
             break;
         case SettingsModule::TYPE_PLUGIN:
             $Manager = Gdn::Factory('PluginManager');
             $Enabled = 'EnabledPlugins';
             $Remove = 'RemovePlugin';
             $RequiredPermission = 'Garden.Plugins.Manage';
             break;
     }
     $Session = Gdn::Session();
     if ($Session->ValidateTransientKey($TransientKey) && $Session->CheckPermission($RequiredPermission)) {
         try {
             if (array_key_exists($Name, $Manager->{$Enabled}) === FALSE) {
                 $Manager->{$Remove}($Name);
             }
         } catch (Exception $e) {
             $this->Form->AddError(strip_tags($e->getMessage()));
         }
     }
     if ($this->Form->ErrorCount() == 0) {
         Redirect('/settings/plugins');
     }
 }
 /**
  * Do password reset.
  *
  * @access public
  * @since 2.0.0
  *
  * @param int $UserID Unique.
  * @param string $PasswordResetKey Authenticate with unique, 1-time code sent via email.
  */
 public function PasswordReset($UserID = '', $PasswordResetKey = '')
 {
     if (!is_numeric($UserID) || $PasswordResetKey == '' || $this->UserModel->GetAttribute($UserID, 'PasswordResetKey', '') != $PasswordResetKey) {
         $this->Form->AddError('Failed to authenticate your password reset request. Try using the reset request form again.');
     }
     if ($this->Form->ErrorCount() == 0) {
         $User = $this->UserModel->GetID($UserID, DATASET_TYPE_ARRAY);
         if ($User) {
             $User = ArrayTranslate($User, array('UserID', 'Name', 'Email'));
             $this->SetData('User', $User);
         }
     }
     if ($this->Form->ErrorCount() == 0 && $this->Form->IsPostBack() === TRUE) {
         $Password = $this->Form->GetFormValue('Password', '');
         $Confirm = $this->Form->GetFormValue('Confirm', '');
         if ($Password == '') {
             $this->Form->AddError('Your new password is invalid');
         } else {
             if ($Password != $Confirm) {
                 $this->Form->AddError('Your passwords did not match.');
             }
         }
         if ($this->Form->ErrorCount() == 0) {
             $User = $this->UserModel->PasswordReset($UserID, $Password);
             Gdn::Session()->Start($User->UserID, TRUE);
             //            $Authenticator = Gdn::Authenticator()->AuthenticateWith('password');
             //            $Authenticator->FetchData($Authenticator, array('Email' => $User->Email, 'Password' => $Password, 'RememberMe' => FALSE));
             //            $AuthUserID = $Authenticator->Authenticate();
             Redirect('/');
         }
     }
     $this->Render();
 }
 /**
  * Prompts new admins how to get started using new install.
  *
  * @since 2.0.0
  * @access public
  */
 public function GettingStarted()
 {
     $this->Permission('Garden.Settings.Manage');
     $this->SetData('Title', T('Getting Started'));
     $this->AddSideMenu('dashboard/settings/gettingstarted');
     $this->TextEnterEmails = T('TextEnterEmails', 'Type email addresses separated by commas here');
     if ($this->Form->AuthenticatedPostBack()) {
         // Do invitations to new members.
         $Message = $this->Form->GetFormValue('InvitationMessage');
         $Message .= "\n\n" . Gdn::Request()->Url('/', TRUE);
         $Message = trim($Message);
         $Recipients = $this->Form->GetFormValue('Recipients');
         if ($Recipients == $this->TextEnterEmails) {
             $Recipients = '';
         }
         $Recipients = explode(',', $Recipients);
         $CountRecipients = 0;
         foreach ($Recipients as $Recipient) {
             if (trim($Recipient) != '') {
                 $CountRecipients++;
                 if (!ValidateEmail($Recipient)) {
                     $this->Form->AddError(sprintf(T('%s is not a valid email address'), $Recipient));
                 }
             }
         }
         if ($CountRecipients == 0) {
             $this->Form->AddError(T('You must provide at least one recipient'));
         }
         if ($this->Form->ErrorCount() == 0) {
             $Email = new Gdn_Email();
             $Email->Subject(T('Check out my new community!'));
             $Email->Message($Message);
             foreach ($Recipients as $Recipient) {
                 if (trim($Recipient) != '') {
                     $Email->To($Recipient);
                     try {
                         $Email->Send();
                     } catch (Exception $ex) {
                         $this->Form->AddError($ex);
                     }
                 }
             }
         }
         if ($this->Form->ErrorCount() == 0) {
             $this->InformMessage(T('Your invitations were sent successfully.'));
         }
     }
     $this->Render();
 }
 /**
  * Restore logs.
  *
  * @since 2.0.?
  * @access public
  *
  * @param array $LogIDs List of log IDs.
  */
 public function Restore($LogIDs)
 {
     $this->Permission('Garden.Moderation.Manage');
     // Grab the logs.
     $Logs = $this->LogModel->GetIDs($LogIDs);
     try {
         foreach ($Logs as $Log) {
             $this->LogModel->Restore($Log);
         }
     } catch (Exception $Ex) {
         $this->Form->AddError($Ex->getMessage());
     }
     $this->LogModel->Recalculate();
     $this->Render('Blank', 'Utility');
 }
 /**
  * Determine whether user can register with this username.
  *
  * @since 2.0.0
  * @access public
  * @param string $Name Username to be checked.
  */
 public function UsernameAvailable($Name = '')
 {
     $this->_DeliveryType = DELIVERY_TYPE_BOOL;
     $Available = TRUE;
     if (C('Garden.Registration.NameUnique', TRUE) && $Name != '') {
         $UserModel = Gdn::UserModel();
         if ($UserModel->GetByUsername($Name)) {
             $Available = FALSE;
         }
     }
     if (!$Available) {
         $this->Form->AddError(sprintf(T('%s unavailable'), T('Name')));
     }
     $this->Render();
 }
 /**
  * Do password reset.
  *
  * @access public
  * @since 2.0.0
  *
  * @param int $UserID Unique.
  * @param string $PasswordResetKey Authenticate with unique, 1-time code sent via email.
  */
 public function PasswordReset($UserID = '', $PasswordResetKey = '')
 {
     $PasswordResetKey = trim($PasswordResetKey);
     if (!is_numeric($UserID) || $PasswordResetKey == '' || $this->UserModel->GetAttribute($UserID, 'PasswordResetKey', '') != $PasswordResetKey) {
         $this->Form->AddError('Failed to authenticate your password reset request. Try using the reset request form again.');
         Logger::event('password_reset_failure', Logger::NOTICE, '{username} failed to authenticate password reset request.');
     }
     $Expires = $this->UserModel->GetAttribute($UserID, 'PasswordResetExpires');
     if ($this->Form->ErrorCount() === 0 && $Expires < time()) {
         $this->Form->AddError('@' . T('Your password reset token has expired.', 'Your password reset token has expired. Try using the reset request form again.'));
         Logger::event('password_reset_failure', Logger::NOTICE, '{username} has an expired reset token.');
     }
     if ($this->Form->ErrorCount() == 0) {
         $User = $this->UserModel->GetID($UserID, DATASET_TYPE_ARRAY);
         if ($User) {
             $User = ArrayTranslate($User, array('UserID', 'Name', 'Email'));
             $this->SetData('User', $User);
         }
     } else {
         $this->SetData('Fatal', TRUE);
     }
     if ($this->Form->ErrorCount() == 0 && $this->Form->IsPostBack() === TRUE) {
         $Password = $this->Form->GetFormValue('Password', '');
         $Confirm = $this->Form->GetFormValue('Confirm', '');
         if ($Password == '') {
             $this->Form->AddError('Your new password is invalid');
             Logger::event('password_reset_failure', Logger::NOTICE, 'Failed to reset the password for {username}. Password is invalid.');
         } else {
             if ($Password != $Confirm) {
                 $this->Form->AddError('Your passwords did not match.');
             }
         }
         Logger::event('password_reset_failure', Logger::NOTICE, 'Failed to reset the password for {username}. Passwords did not match.');
         if ($this->Form->ErrorCount() == 0) {
             $User = $this->UserModel->PasswordReset($UserID, $Password);
             Logger::event('password_reset', Logger::NOTICE, '{username} has reset their password.', array('UserName', $User->Name));
             Gdn::Session()->Start($User->UserID, TRUE);
             //            $Authenticator = Gdn::Authenticator()->AuthenticateWith('password');
             //            $Authenticator->FetchData($Authenticator, array('Email' => $User->Email, 'Password' => $Password, 'RememberMe' => FALSE));
             //            $AuthUserID = $Authenticator->Authenticate();
             Redirect('/');
         }
     }
     $this->Render();
 }
 /**
  * Revoke an invitation.
  *
  * @since 2.0.0
  * @param int $InvitationID Unique identifier.
  * @throws Exception Throws an exception when the invitation isn't found or the user doesn't have permission to delete it.
  */
 public function UnInvite($InvitationID)
 {
     $this->Permission('Garden.SignIn.Allow');
     if (!$this->Form->AuthenticatedPostBack()) {
         throw ForbiddenException('GET');
     }
     $InvitationModel = new InvitationModel();
     $Session = Gdn::Session();
     try {
         $Valid = $InvitationModel->Delete($InvitationID, $this->UserModel);
         if ($Valid) {
             $this->InformMessage(T('The invitation was removed successfully.'));
             $this->JsonTarget(".js-invitation[data-id=\"{$InvitationID}\"]", '', 'SlideUp');
         }
     } catch (Exception $ex) {
         $this->Form->AddError(strip_tags($ex->getMessage()));
     }
     if ($this->Form->ErrorCount() == 0) {
         $this->Render('Blank', 'Utility');
     }
 }
 /**
  * Create or update a comment.
  *
  * @since 2.0.0
  * @access public
  *
  * @param int $DiscussionID Unique ID to add the comment to. If blank, this method will throw an error.
  */
 public function Comment($DiscussionID = '')
 {
     // Get $DiscussionID from RequestArgs if valid
     if ($DiscussionID == '' && count($this->RequestArgs)) {
         if (is_numeric($this->RequestArgs[0])) {
             $DiscussionID = $this->RequestArgs[0];
         }
     }
     // If invalid $DiscussionID, get from form.
     $this->Form->SetModel($this->CommentModel);
     $DiscussionID = is_numeric($DiscussionID) ? $DiscussionID : $this->Form->GetFormValue('DiscussionID', 0);
     // Set discussion data
     $this->DiscussionID = $DiscussionID;
     $this->Discussion = $Discussion = $this->DiscussionModel->GetID($DiscussionID);
     // Is this an embedded comment being posted to a discussion that doesn't exist yet?
     $vanilla_type = $this->Form->GetFormValue('vanilla_type', '');
     $vanilla_url = $this->Form->GetFormValue('vanilla_url', '');
     $vanilla_category_id = $this->Form->GetFormValue('vanilla_category_id', '');
     $Attributes = array('ForeignUrl' => $vanilla_url);
     $vanilla_identifier = $this->Form->GetFormValue('vanilla_identifier', '');
     // Only allow vanilla identifiers of 32 chars or less - md5 if larger
     if (strlen($vanilla_identifier) > 32) {
         $Attributes['vanilla_identifier'] = $vanilla_identifier;
         $vanilla_identifier = md5($vanilla_identifier);
     }
     if (!$Discussion && $vanilla_url != '' && $vanilla_identifier != '') {
         $Discussion = $Discussion = $this->DiscussionModel->GetForeignID($vanilla_identifier, $vanilla_type);
         if ($Discussion) {
             $this->DiscussionID = $DiscussionID = $Discussion->DiscussionID;
             $this->Form->SetValue('DiscussionID', $DiscussionID);
         }
     }
     // If so, create it!
     if (!$Discussion && $vanilla_url != '' && $vanilla_identifier != '') {
         // Add these values back to the form if they exist!
         $this->Form->AddHidden('vanilla_identifier', $vanilla_identifier);
         $this->Form->AddHidden('vanilla_type', $vanilla_type);
         $this->Form->AddHidden('vanilla_url', $vanilla_url);
         $this->Form->AddHidden('vanilla_category_id', $vanilla_category_id);
         $PageInfo = FetchPageInfo($vanilla_url);
         if (!($Title = $this->Form->GetFormValue('Name'))) {
             $Title = GetValue('Title', $PageInfo, '');
             if ($Title == '') {
                 $Title = T('Undefined discussion subject.');
             }
         }
         $Description = GetValue('Description', $PageInfo, '');
         $Images = GetValue('Images', $PageInfo, array());
         $LinkText = T('EmbededDiscussionLinkText', 'Read the full story here');
         if (!$Description && count($Images) == 0) {
             $Body = FormatString('<p><a href="{Url}">{LinkText}</a></p>', array('Url' => $vanilla_url, 'LinkText' => $LinkText));
         } else {
             $Body = FormatString('
         <div class="EmbeddedContent">{Image}<strong>{Title}</strong>
            <p>{Excerpt}</p>
            <p><a href="{Url}">{LinkText}</a></p>
            <div class="ClearFix"></div>
         </div>', array('Title' => $Title, 'Excerpt' => $Description, 'Image' => count($Images) > 0 ? Img(GetValue(0, $Images), array('class' => 'LeftAlign')) : '', 'Url' => $vanilla_url, 'LinkText' => $LinkText));
         }
         if ($Body == '') {
             $Body = $vanilla_url;
         }
         if ($Body == '') {
             $Body = T('Undefined discussion body.');
         }
         // Validate the CategoryID for inserting.
         $Category = CategoryModel::Categories($vanilla_category_id);
         if (!$Category) {
             $vanilla_category_id = C('Vanilla.Embed.DefaultCategoryID', 0);
             if ($vanilla_category_id <= 0) {
                 // No default category defined, so grab the first non-root category and use that.
                 $vanilla_category_id = $this->DiscussionModel->SQL->Select('CategoryID')->From('Category')->Where('CategoryID >', 0)->Get()->FirstRow()->CategoryID;
                 // No categories in the db? default to 0
                 if (!$vanilla_category_id) {
                     $vanilla_category_id = 0;
                 }
             }
         } else {
             $vanilla_category_id = $Category['CategoryID'];
         }
         $EmbedUserID = C('Garden.Embed.UserID');
         if ($EmbedUserID) {
             $EmbedUser = Gdn::UserModel()->GetID($EmbedUserID);
         }
         if (!$EmbedUserID || !$EmbedUser) {
             $EmbedUserID = Gdn::UserModel()->GetSystemUserID();
         }
         $EmbeddedDiscussionData = array('InsertUserID' => $EmbedUserID, 'DateInserted' => Gdn_Format::ToDateTime(), 'DateUpdated' => Gdn_Format::ToDateTime(), 'CategoryID' => $vanilla_category_id, 'ForeignID' => $vanilla_identifier, 'Type' => $vanilla_type, 'Name' => $Title, 'Body' => $Body, 'Format' => 'Html', 'Attributes' => serialize($Attributes));
         $this->EventArguments['Discussion'] = $EmbeddedDiscussionData;
         $this->FireEvent('BeforeEmbedDiscussion');
         $DiscussionID = $this->DiscussionModel->SQL->Insert('Discussion', $EmbeddedDiscussionData);
         $ValidationResults = $this->DiscussionModel->ValidationResults();
         if (count($ValidationResults) == 0 && $DiscussionID > 0) {
             $this->Form->AddHidden('DiscussionID', $DiscussionID);
             // Put this in the form so reposts won't cause new discussions.
             $this->Form->SetFormValue('DiscussionID', $DiscussionID);
             // Put this in the form values so it is used when saving comments.
             $this->SetJson('DiscussionID', $DiscussionID);
             $this->Discussion = $Discussion = $this->DiscussionModel->GetID($DiscussionID, DATASET_TYPE_OBJECT, array('Slave' => FALSE));
             // Update the category discussion count
             if ($vanilla_category_id > 0) {
                 $this->DiscussionModel->UpdateDiscussionCount($vanilla_category_id, $DiscussionID);
             }
         }
     }
     // If no discussion was found, error out
     if (!$Discussion) {
         $this->Form->AddError(T('Failed to find discussion for commenting.'));
     }
     $PermissionCategoryID = GetValue('PermissionCategoryID', $Discussion);
     // Setup head
     $this->AddJsFile('jquery.autosize.min.js');
     $this->AddJsFile('post.js');
     $this->AddJsFile('autosave.js');
     // Setup comment model, $CommentID, $DraftID
     $Session = Gdn::Session();
     $CommentID = isset($this->Comment) && property_exists($this->Comment, 'CommentID') ? $this->Comment->CommentID : '';
     $DraftID = isset($this->Comment) && property_exists($this->Comment, 'DraftID') ? $this->Comment->DraftID : '';
     $this->EventArguments['CommentID'] = $CommentID;
     $this->EventArguments['DraftID'] = $DraftID;
     // Determine whether we are editing
     $Editing = $CommentID > 0 || $DraftID > 0;
     $this->EventArguments['Editing'] = $Editing;
     // If closed, cancel & go to discussion
     if ($Discussion && $Discussion->Closed == 1 && !$Editing && !$Session->CheckPermission('Vanilla.Discussions.Close', TRUE, 'Category', $PermissionCategoryID)) {
         Redirect(DiscussionUrl($Discussion));
     }
     // Add hidden IDs to form
     $this->Form->AddHidden('DiscussionID', $DiscussionID);
     $this->Form->AddHidden('CommentID', $CommentID);
     $this->Form->AddHidden('DraftID', $DraftID, TRUE);
     // Check permissions
     if ($Discussion && $Editing) {
         // Permisssion to edit
         if ($this->Comment->InsertUserID != $Session->UserID) {
             $this->Permission('Vanilla.Comments.Edit', TRUE, 'Category', $Discussion->PermissionCategoryID);
         }
         // Make sure that content can (still) be edited.
         $EditContentTimeout = C('Garden.EditContentTimeout', -1);
         $CanEdit = $EditContentTimeout == -1 || strtotime($this->Comment->DateInserted) + $EditContentTimeout > time();
         if (!$CanEdit) {
             $this->Permission('Vanilla.Comments.Edit', TRUE, 'Category', $Discussion->PermissionCategoryID);
         }
         // Make sure only moderators can edit closed things
         if ($Discussion->Closed) {
             $this->Permission('Vanilla.Comments.Edit', TRUE, 'Category', $Discussion->PermissionCategoryID);
         }
         $this->Form->SetFormValue('CommentID', $CommentID);
     } else {
         if ($Discussion) {
             // Permission to add
             $this->Permission('Vanilla.Comments.Add', TRUE, 'Category', $Discussion->PermissionCategoryID);
         }
     }
     if (!$this->Form->IsPostBack()) {
         // Form was validly submitted
         if (isset($this->Comment)) {
             $this->Form->SetData((array) $this->Comment);
         }
     } else {
         // Save as a draft?
         $FormValues = $this->Form->FormValues();
         $FormValues = $this->CommentModel->FilterForm($FormValues);
         if ($DraftID == 0) {
             $DraftID = $this->Form->GetFormValue('DraftID', 0);
         }
         $Type = GetIncomingValue('Type');
         $Draft = $Type == 'Draft';
         $this->EventArguments['Draft'] = $Draft;
         $Preview = $Type == 'Preview';
         if ($Draft) {
             $DraftID = $this->DraftModel->Save($FormValues);
             $this->Form->AddHidden('DraftID', $DraftID, TRUE);
             $this->Form->SetValidationResults($this->DraftModel->ValidationResults());
         } else {
             if (!$Preview) {
                 // Fix an undefined title if we can.
                 if ($this->Form->GetFormValue('Name') && GetValue('Name', $Discussion) == T('Undefined discussion subject.')) {
                     $Set = array('Name' => $this->Form->GetFormValue('Name'));
                     if (isset($vanilla_url) && $vanilla_url && strpos(GetValue('Body', $Discussion), T('Undefined discussion subject.')) !== FALSE) {
                         $LinkText = T('EmbededDiscussionLinkText', 'Read the full story here');
                         $Set['Body'] = FormatString('<p><a href="{Url}">{LinkText}</a></p>', array('Url' => $vanilla_url, 'LinkText' => $LinkText));
                     }
                     $this->DiscussionModel->SetField(GetValue('DiscussionID', $Discussion), $Set);
                 }
                 $Inserted = !$CommentID;
                 $CommentID = $this->CommentModel->Save($FormValues);
                 // The comment is now half-saved.
                 if (is_numeric($CommentID) && $CommentID > 0) {
                     if ($this->_DeliveryType == DELIVERY_TYPE_ALL) {
                         $this->CommentModel->Save2($CommentID, $Inserted, TRUE, TRUE);
                     } else {
                         $this->JsonTarget('', Url("/vanilla/post/comment2.json?commentid={$CommentID}&inserted={$Inserted}"), 'Ajax');
                     }
                     // $Discussion = $this->DiscussionModel->GetID($DiscussionID);
                     $Comment = $this->CommentModel->GetID($CommentID, DATASET_TYPE_OBJECT, array('Slave' => FALSE));
                     $this->EventArguments['Discussion'] = $Discussion;
                     $this->EventArguments['Comment'] = $Comment;
                     $this->FireEvent('AfterCommentSave');
                 } elseif ($CommentID === SPAM || $CommentID === UNAPPROVED) {
                     $this->StatusMessage = T('CommentRequiresApprovalStatus', 'Your comment will appear after it is approved.');
                 }
                 $this->Form->SetValidationResults($this->CommentModel->ValidationResults());
                 if ($CommentID > 0 && $DraftID > 0) {
                     $this->DraftModel->Delete($DraftID);
                 }
             }
         }
         // Handle non-ajax requests first:
         if ($this->_DeliveryType == DELIVERY_TYPE_ALL) {
             if ($this->Form->ErrorCount() == 0) {
                 // Make sure that this form knows what comment we are editing.
                 if ($CommentID > 0) {
                     $this->Form->AddHidden('CommentID', $CommentID);
                 }
                 // If the comment was not a draft
                 if (!$Draft) {
                     // Redirect to the new comment.
                     if ($CommentID > 0) {
                         Redirect("discussion/comment/{$CommentID}/#Comment_{$CommentID}");
                     } elseif ($CommentID == SPAM) {
                         $this->SetData('DiscussionUrl', DiscussionUrl($Discussion));
                         $this->View = 'Spam';
                     }
                 } elseif ($Preview) {
                     // If this was a preview click, create a comment shell with the values for this comment
                     $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->AddAsset('Content', $this->FetchView('preview'));
                 } else {
                     // If this was a draft save, notify the user about the save
                     $this->InformMessage(sprintf(T('Draft saved at %s'), Gdn_Format::Date()));
                 }
             }
         } else {
             // Handle ajax-based requests
             if ($this->Form->ErrorCount() > 0) {
                 // Return the form errors
                 $this->ErrorMessage($this->Form->Errors());
             } else {
                 // Make sure that the ajax request form knows about the newly created comment or draft id
                 $this->SetJson('CommentID', $CommentID);
                 $this->SetJson('DraftID', $DraftID);
                 if ($Preview) {
                     // If this was a preview click, create a comment shell with the values for this comment
                     $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->View = 'preview';
                 } elseif (!$Draft) {
                     // If the comment was not a draft
                     // If Editing a comment
                     if ($Editing) {
                         // Just reload the comment in question
                         $this->Offset = 1;
                         $Comments = $this->CommentModel->GetIDData($CommentID, array('Slave' => FALSE));
                         $this->SetData('Comments', $Comments);
                         $this->SetData('Discussion', $Discussion);
                         // Load the discussion
                         $this->ControllerName = 'discussion';
                         $this->View = 'comments';
                         // Also define the discussion url in case this request came from the post screen and needs to be redirected to the discussion
                         $this->SetJson('DiscussionUrl', DiscussionUrl($this->Discussion) . '#Comment_' . $CommentID);
                     } else {
                         // If the comment model isn't sorted by DateInserted or CommentID then we can't do any fancy loading of comments.
                         $OrderBy = GetValueR('0.0', $this->CommentModel->OrderBy());
                         //                     $Redirect = !in_array($OrderBy, array('c.DateInserted', 'c.CommentID'));
                         //							$DisplayNewCommentOnly = $this->Form->GetFormValue('DisplayNewCommentOnly');
                         //                     if (!$Redirect) {
                         //                        // Otherwise load all new comments that the user hasn't seen yet
                         //                        $LastCommentID = $this->Form->GetFormValue('LastCommentID');
                         //                        if (!is_numeric($LastCommentID))
                         //                           $LastCommentID = $CommentID - 1; // Failsafe back to this new comment if the lastcommentid was not defined properly
                         //
                         //                        // Don't reload the first comment if this new comment is the first one.
                         //                        $this->Offset = $LastCommentID == 0 ? 1 : $this->CommentModel->GetOffset($LastCommentID);
                         //                        // Do not load more than a single page of data...
                         //                        $Limit = C('Vanilla.Comments.PerPage', 30);
                         //
                         //                        // Redirect if the new new comment isn't on the same page.
                         //                        $Redirect |= !$DisplayNewCommentOnly && PageNumber($this->Offset, $Limit) != PageNumber($Discussion->CountComments - 1, $Limit);
                         //                     }
                         //                     if ($Redirect) {
                         //                        // The user posted a comment on a page other than the last one, so just redirect to the last page.
                         //                        $this->RedirectUrl = Gdn::Request()->Url("discussion/comment/$CommentID/#Comment_$CommentID", TRUE);
                         //                     } else {
                         //                        // Make sure to load all new comments since the page was last loaded by this user
                         //								if ($DisplayNewCommentOnly)
                         $this->Offset = $this->CommentModel->GetOffset($CommentID);
                         $Comments = $this->CommentModel->GetIDData($CommentID, array('Slave' => FALSE));
                         $this->SetData('Comments', $Comments);
                         $this->SetData('NewComments', TRUE);
                         $this->ClassName = 'DiscussionController';
                         $this->ControllerName = 'discussion';
                         $this->View = 'comments';
                         //                     }
                         // Make sure to set the user's discussion watch records
                         $CountComments = $this->CommentModel->GetCount($DiscussionID);
                         $Limit = is_object($this->Data('Comments')) ? $this->Data('Comments')->NumRows() : $Discussion->CountComments;
                         $Offset = $CountComments - $Limit;
                         $this->CommentModel->SetWatch($this->Discussion, $Limit, $Offset, $CountComments);
                     }
                 } else {
                     // If this was a draft save, notify the user about the save
                     $this->InformMessage(sprintf(T('Draft saved at %s'), Gdn_Format::Date()));
                 }
                 // And update the draft count
                 $UserModel = Gdn::UserModel();
                 $CountDrafts = $UserModel->GetAttribute($Session->UserID, 'CountDrafts', 0);
                 $this->SetJson('MyDrafts', T('My Drafts'));
                 $this->SetJson('CountDrafts', $CountDrafts);
             }
         }
     }
     // Include data for FireEvent
     if (property_exists($this, 'Discussion')) {
         $this->EventArguments['Discussion'] = $this->Discussion;
     }
     if (property_exists($this, 'Comment')) {
         $this->EventArguments['Comment'] = $this->Comment;
     }
     $this->FireEvent('BeforeCommentRender');
     if ($this->DeliveryType() == DELIVERY_TYPE_DATA) {
         $Comment = $this->Data('Comments')->FirstRow(DATASET_TYPE_ARRAY);
         if ($Comment) {
             $Photo = $Comment['InsertPhoto'];
             if (strpos($Photo, '//') === FALSE) {
                 $Photo = Gdn_Upload::Url(ChangeBasename($Photo, 'n%s'));
             }
             $Comment['InsertPhoto'] = $Photo;
         }
         $this->Data = array('Comment' => $Comment);
         $this->RenderData($this->Data);
     } else {
         require_once $this->FetchViewLocation('helper_functions', 'Discussion');
         // Render default view.
         $this->Render();
     }
 }
 /**
  * Deleting a category.
  *
  * @since 2.0.0
  * @access public
  *
  * @param int $CategoryID Unique ID of the category to be deleted.
  */
 public function DeleteCategory($CategoryID = FALSE)
 {
     // Check permission
     $this->Permission('Garden.Settings.Manage');
     // Set up head
     $this->AddJsFile('categories.js');
     $this->Title(T('Delete Category'));
     $this->AddSideMenu('vanilla/settings/managecategories');
     // Get category data
     $this->Category = $this->CategoryModel->GetID($CategoryID);
     if (!$this->Category) {
         $this->Form->AddError('The specified category could not be found.');
     } else {
         // Make sure the form knows which item we are deleting.
         $this->Form->AddHidden('CategoryID', $CategoryID);
         // Get a list of categories other than this one that can act as a replacement
         $this->OtherCategories = $this->CategoryModel->GetWhere(array('CategoryID <>' => $CategoryID, 'AllowDiscussions' => $this->Category->AllowDiscussions, 'CategoryID >' => 0), 'Sort');
         if (!$this->Form->AuthenticatedPostBack()) {
             $this->Form->SetFormValue('DeleteDiscussions', '1');
             // Checked by default
         } else {
             $ReplacementCategoryID = $this->Form->GetValue('ReplacementCategoryID');
             $ReplacementCategory = $this->CategoryModel->GetID($ReplacementCategoryID);
             // Error if:
             // 1. The category being deleted is the last remaining category that
             // allows discussions.
             if ($this->Category->AllowDiscussions == '1' && $this->OtherCategories->NumRows() == 0) {
                 $this->Form->AddError('You cannot remove the only remaining category that allows discussions');
             }
             /*
             // 2. The category being deleted allows discussions, and it contains
             // discussions, and there is no replacement category specified.
             if ($this->Form->ErrorCount() == 0
                && $this->Category->AllowDiscussions == '1'
                && $this->Category->CountDiscussions > 0
                && ($ReplacementCategory == FALSE || $ReplacementCategory->AllowDiscussions != '1'))
                $this->Form->AddError('You must select a replacement category in order to remove this category.');
             */
             // 3. The category being deleted does not allow discussions, and it
             // does contain other categories, and there are replacement parent
             // categories available, and one is not selected.
             /*
             if ($this->Category->AllowDiscussions == '0'
                && $this->OtherCategories->NumRows() > 0
                && !$ReplacementCategory) {
                if ($this->CategoryModel->GetWhere(array('ParentCategoryID' => $CategoryID))->NumRows() > 0)
                   $this->Form->AddError('You must select a replacement category in order to remove this category.');
             }
             */
             if ($this->Form->ErrorCount() == 0) {
                 // Go ahead and delete the category
                 try {
                     $this->CategoryModel->Delete($this->Category, $this->Form->GetValue('ReplacementCategoryID'));
                 } catch (Exception $ex) {
                     $this->Form->AddError($ex);
                 }
                 if ($this->Form->ErrorCount() == 0) {
                     $this->RedirectUrl = Url('vanilla/settings/managecategories');
                     $this->InformMessage(T('Deleting category...'));
                 }
             }
         }
     }
     // Render default view
     $this->Render();
 }
   /**
    * 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($CategoryID = '') {
      // Override CategoryID if categories are disabled
      $UseCategories = $this->ShowCategorySelector = (bool)C('Vanilla.Categories.Use');
      if (!$UseCategories) 
         $CategoryID = 0;
         
      // Setup head
      $this->AddJsFile('jquery.autogrow.js');
      $this->AddJsFile('post.js');
      $this->AddJsFile('autosave.js');
      
      $Session = Gdn::Session();
      
      // Set discussion, draft, and category data
      $DiscussionID = isset($this->Discussion) ? $this->Discussion->DiscussionID : '';
      $DraftID = isset($this->Draft) ? $this->Draft->DraftID : 0;
      $this->CategoryID = isset($this->Discussion) ? $this->Discussion->CategoryID : $CategoryID;
      $this->Category = FALSE;
      if ($UseCategories) {
         $CategoryModel = new CategoryModel();
         $CategoryData = $CategoryModel->GetFull('', 'Vanilla.Discussions.Add');
         $aCategoryData = array();
         foreach ($CategoryData->Result() as $Category) {
            if ($Category->CategoryID <= 0)
               continue;
            
            if ($this->CategoryID == $Category->CategoryID)
               $this->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;
            $this->EventArguments['aCategoryData'] = &$aCategoryData;
				$this->EventArguments['Category'] = &$Category;
				$this->FireEvent('AfterCategoryItem');
         }
         $this->CategoryData = $aCategoryData;
      }
      
      // 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);

         $this->Title(T('Edit Discussion'));
      } else {
         // Permission to add
         $this->Permission('Vanilla.Discussions.Add');
         $this->Title(T('Start a New Discussion'));
      }
      
      // Set the model on the form
      $this->Form->SetModel($this->DiscussionModel);
      if ($this->Form->AuthenticatedPostBack() === FALSE) {
         // Prep form with current data for editing
         if (isset($this->Discussion)) {
            $this->Form->SetData($this->Discussion);
         } else if (isset($this->Draft))
            $this->Form->SetData($this->Draft);
         else
            $this->Form->SetData(array('CategoryID' => $CategoryID));
            
      } else { // Form was submitted
         // Save as a draft?
         $FormValues = $this->Form->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) && isset($FormValues['CategoryID']))
               $this->Category = $aCategoryData[$FormValues['CategoryID']];

            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 (!$Session->CheckPermission('Vanilla.Discussions.Add', TRUE, 'Category', $this->Category->PermissionCategoryID))
                  $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 && $DraftID > 0)
                     $this->DraftModel->Delete($DraftID);
                  if ($DiscussionID == SPAM) {
                     $this->StatusMessage = T('Your post has been flagged for moderation.');
                     $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->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);
                  $this->EventArguments['Discussion'] = $Discussion;
                  $this->FireEvent('AfterDiscussionSave');
                  
                  if ($this->_DeliveryType == DELIVERY_TYPE_ALL) {
                     Redirect('/discussion/'.$DiscussionID.'/'.Gdn_Format::Url($Discussion->Name));
                  } else {
                     $this->RedirectUrl = Url('/discussion/'.$DiscussionID.'/'.Gdn_Format::Url($Discussion->Name));
                  }
               } 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');
      
      // Render view (posts/discussion.php or post/preview.php)
      $this->Render();
   }