/**
  * Captcha-authenticated registration. Used by default.
  *
  * Events: RegistrationSuccessful
  * 
  * @access private
  * @since 2.0.0
  */
 private function RegisterCaptcha()
 {
     Gdn::UserModel()->AddPasswordStrength($this);
     include CombinePaths(array(PATH_LIBRARY, 'vendors/recaptcha', 'functions.recaptchalib.php'));
     if ($this->Form->IsPostBack() === TRUE) {
         // Add validation rules that are not enforced by the model
         $this->UserModel->DefineSchema();
         $this->UserModel->Validation->ApplyRule('Name', 'Username', $this->UsernameError);
         $this->UserModel->Validation->ApplyRule('TermsOfService', 'Required', T('You must agree to the terms of service.'));
         $this->UserModel->Validation->ApplyRule('Password', 'Required');
         $this->UserModel->Validation->ApplyRule('Password', 'Strength');
         $this->UserModel->Validation->ApplyRule('Password', 'Match');
         // $this->UserModel->Validation->ApplyRule('DateOfBirth', 'MinimumAge');
         $this->FireEvent('RegisterValidation');
         try {
             $Values = $this->Form->FormValues();
             $Values = $this->UserModel->FilterForm($Values, TRUE);
             unset($Values['Roles']);
             $AuthUserID = $this->UserModel->Register($Values);
             if ($AuthUserID == UserModel::REDIRECT_APPROVE) {
                 $this->Form->SetFormValue('Target', '/entry/registerthanks');
                 $this->_SetRedirect();
                 return;
             } elseif (!$AuthUserID) {
                 $this->Form->SetValidationResults($this->UserModel->ValidationResults());
                 if ($this->_DeliveryType != DELIVERY_TYPE_ALL) {
                     $this->_DeliveryType = DELIVERY_TYPE_MESSAGE;
                 }
             } else {
                 // The user has been created successfully, so sign in now.
                 if (!Gdn::Session()->IsValid()) {
                     Gdn::Session()->Start($AuthUserID, TRUE, (bool) $this->Form->GetFormValue('RememberMe'));
                 }
                 try {
                     $this->UserModel->SendWelcomeEmail($AuthUserID, '', 'Register');
                 } catch (Exception $Ex) {
                 }
                 $this->FireEvent('RegistrationSuccessful');
                 // ... and redirect them appropriately
                 $Route = $this->RedirectTo();
                 if ($this->_DeliveryType != DELIVERY_TYPE_ALL) {
                     $this->RedirectUrl = Url($Route);
                 } else {
                     if ($Route !== FALSE) {
                         Redirect($Route);
                     }
                 }
             }
         } catch (Exception $Ex) {
             $this->Form->AddError($Ex);
         }
     }
     $this->Render();
 }
 /**
  * Edit a comment (wrapper for PostController::Comment).
  *
  * Will throw an error if both params are blank.
  *
  * @since 2.0.0
  * @access public
  * 
  * @param int $CommentID Unique ID of the comment to edit.
  * @param int $DraftID Unique ID of the draft to edit.
  */
 public function EditComment($CommentID = '', $DraftID = '')
 {
     if (is_numeric($CommentID) && $CommentID > 0) {
         $this->Form->SetModel($this->CommentModel);
         $this->Comment = $this->CommentModel->GetID($CommentID);
     } else {
         $this->Form->SetModel($this->DraftModel);
         $this->Comment = $this->DraftModel->GetID($DraftID);
     }
     $this->Form->SetFormValue('Format', GetValue('Format', $this->Comment));
     $this->View = 'editcomment';
     $this->Comment($this->Comment->DiscussionID);
 }
 public function ThemeOptions($Style = NULL)
 {
     $this->Permission('Garden.Themes.Manage');
     try {
         $this->AddJsFile('addons.js');
         $this->AddSideMenu('dashboard/settings/themeoptions');
         $ThemeManager = new Gdn_ThemeManager();
         $this->SetData('ThemeInfo', $ThemeManager->EnabledThemeInfo());
         if ($this->Form->IsPostBack()) {
             // Save the styles to the config.
             $StyleKey = $this->Form->GetFormValue('StyleKey');
             SaveToConfig(array('Garden.ThemeOptions.Styles.Key' => $StyleKey, 'Garden.ThemeOptions.Styles.Value' => $this->Data("ThemeInfo.Options.Styles.{$StyleKey}.Basename")));
             // Save the text to the locale.
             $Translations = array();
             foreach ($this->Data('ThemeInfo.Options.Text', array()) as $Key => $Default) {
                 $Value = $this->Form->GetFormValue($this->Form->EscapeString('Text_' . $Key));
                 $Translations['Theme_' . $Key] = $Value;
                 //$this->Form->SetFormValue('Text_'.$Key, $Value);
             }
             if (count($Translations) > 0) {
                 try {
                     Gdn::Locale()->SaveTranslations($Translations);
                     Gdn::Locale()->Refresh();
                 } catch (Exception $Ex) {
                     $this->Form->AddError($Ex);
                 }
             }
             $this->StatusMessage = T("Your changes have been saved.");
         } elseif ($Style) {
             SaveToConfig(array('Garden.ThemeOptions.Styles.Key' => $Style, 'Garden.ThemeOptions.Styles.Value' => $this->Data("ThemeInfo.Options.Styles.{$Style}.Basename")));
         }
         $this->SetData('ThemeOptions', C('Garden.ThemeOptions'));
         $StyleKey = $this->Data('ThemeOptions.Styles.Key');
         if (!$this->Form->IsPostBack()) {
             foreach ($this->Data('ThemeInfo.Options.Text', array()) as $Key => $Options) {
                 $Default = GetValue('Default', $Options, '');
                 $Value = T('Theme_' . $Key, '#DEFAULT#');
                 if ($Value === '#DEFAULT#') {
                     $Value = $Default;
                 }
                 $this->Form->SetFormValue($this->Form->EscapeString('Text_' . $Key), $Value);
             }
         }
         $this->SetData('ThemeFolder', $ThemeManager->EnabledTheme());
         $this->Title(T('Theme Options'));
         $this->Form->AddHidden('StyleKey', $StyleKey);
     } catch (Exception $Ex) {
         $this->Form->AddError($Ex);
     }
     $this->Render();
 }
 /**
  * Manage options for a mobile theme.
  *
  * @since 2.0.0
  * @access public
  * @param string $Style Unique ID.
  * @todo Why is this in a giant try/catch block?
  */
 public function MobileThemeOptions($Style = NULL)
 {
     $this->Permission('Garden.Settings.Manage');
     try {
         $this->AddJsFile('addons.js');
         $this->AddSideMenu('dashboard/settings/mobilethemeoptions');
         $ThemeManager = Gdn::ThemeManager();
         $EnabledThemeName = $ThemeManager->MobileTheme();
         $EnabledThemeInfo = $ThemeManager->GetThemeInfo($EnabledThemeName);
         $this->SetData('ThemeInfo', $EnabledThemeInfo);
         if ($this->Form->IsPostBack()) {
             // Save the styles to the config.
             $StyleKey = $this->Form->GetFormValue('StyleKey');
             $ConfigSaveData = array('Garden.MobileThemeOptions.Styles.Key' => $StyleKey, 'Garden.MobileThemeOptions.Styles.Value' => $this->Data("ThemeInfo.Options.Styles.{$StyleKey}.Basename"));
             // Save the text to the locale.
             $Translations = array();
             foreach ($this->Data('ThemeInfo.Options.Text', array()) as $Key => $Default) {
                 $Value = $this->Form->GetFormValue($this->Form->EscapeString('Text_' . $Key));
                 $ConfigSaveData["ThemeOption.{$Key}"] = $Value;
                 //$this->Form->SetFormValue('Text_'.$Key, $Value);
             }
             SaveToConfig($ConfigSaveData);
             $this->InformMessage(T("Your changes have been saved."));
         } elseif ($Style) {
             SaveToConfig(array('Garden.MobileThemeOptions.Styles.Key' => $Style, 'Garden.MobileThemeOptions.Styles.Value' => $this->Data("ThemeInfo.Options.Styles.{$Style}.Basename")));
         }
         $this->SetData('ThemeOptions', C('Garden.MobileThemeOptions'));
         $StyleKey = $this->Data('ThemeOptions.Styles.Key');
         if (!$this->Form->IsPostBack()) {
             foreach ($this->Data('ThemeInfo.Options.Text', array()) as $Key => $Options) {
                 $Default = GetValue('Default', $Options, '');
                 $Value = C("ThemeOption.{$Key}", '#DEFAULT#');
                 if ($Value === '#DEFAULT#') {
                     $Value = $Default;
                 }
                 $this->Form->SetFormValue($this->Form->EscapeString('Text_' . $Key), $Value);
             }
         }
         $this->SetData('ThemeFolder', $EnabledThemeName);
         $this->Title(T('Mobile Theme Options'));
         $this->Form->AddHidden('StyleKey', $StyleKey);
     } catch (Exception $Ex) {
         $this->Form->AddError($Ex);
     }
     $this->Render();
 }
 /**
  * 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();
     }
 }
 /**
  * Editing a category.
  *
  * @since 2.0.0
  * @access public
  *
  * @param int $CategoryID Unique ID of the category to be updated.
  */
 public function EditCategory($CategoryID = '')
 {
     // Check permission
     $this->Permission('Garden.Settings.Manage');
     // Set up models
     $RoleModel = new RoleModel();
     $PermissionModel = Gdn::PermissionModel();
     $this->Form->SetModel($this->CategoryModel);
     if (!$CategoryID && $this->Form->IsPostBack()) {
         if ($ID = $this->Form->GetFormValue('CategoryID')) {
             $CategoryID = $ID;
         }
     }
     // Get category data
     $this->Category = $this->CategoryModel->GetID($CategoryID);
     $this->Category->CustomPermissions = $this->Category->CategoryID == $this->Category->PermissionCategoryID;
     // Set up head
     $this->AddJsFile('jquery.alphanumeric.js');
     $this->AddJsFile('categories.js');
     $this->AddJsFile('jquery.gardencheckboxgrid.js');
     $this->Title(T('Edit Category'));
     $this->AddSideMenu('vanilla/settings/managecategories');
     // Make sure the form knows which item we are editing.
     $this->Form->AddHidden('CategoryID', $CategoryID);
     $this->SetData('CategoryID', $CategoryID);
     // Load all roles with editable permissions
     $this->RoleArray = $RoleModel->GetArray();
     $this->FireEvent('AddEditCategory');
     if ($this->Form->IsPostBack() == FALSE) {
         $this->Form->SetData($this->Category);
         $this->SetupDiscussionTypes($this->Category);
         $this->Form->SetValue('CustomPoints', $this->Category->PointsCategoryID == $this->Category->CategoryID);
     } else {
         $this->SetupDiscussionTypes($this->Category);
         $Upload = new Gdn_Upload();
         $TmpImage = $Upload->ValidateUpload('PhotoUpload', FALSE);
         if ($TmpImage) {
             // Generate the target image name
             $TargetImage = $Upload->GenerateTargetName(PATH_UPLOADS);
             $ImageBaseName = pathinfo($TargetImage, PATHINFO_BASENAME);
             // Save the uploaded image
             $Parts = $Upload->SaveAs($TmpImage, $ImageBaseName);
             $this->Form->SetFormValue('Photo', $Parts['SaveName']);
         }
         $this->Form->SetFormValue('CustomPoints', (bool) $this->Form->GetFormValue('CustomPoints'));
         if ($this->Form->Save()) {
             $Category = CategoryModel::Categories($CategoryID);
             $this->SetData('Category', $Category);
             if ($this->DeliveryType() == DELIVERY_TYPE_ALL) {
                 Redirect('vanilla/settings/managecategories');
             }
         }
     }
     // Get all of the currently selected role/permission combinations for this junction.
     $Permissions = $PermissionModel->GetJunctionPermissions(array('JunctionID' => $CategoryID), 'Category', '', array('AddDefaults' => !$this->Category->CustomPermissions));
     $Permissions = $PermissionModel->UnpivotPermissions($Permissions, TRUE);
     if ($this->DeliveryType() == DELIVERY_TYPE_ALL) {
         $this->SetData('PermissionData', $Permissions, TRUE);
     }
     // Render default view
     $this->Render();
 }
   /**
    * Attempt to syncronize user data from remote system into Dashboard.
    * 
    * @access public
    * @since 2.0.?
    * @author Tim Gunter
    *
    * @param object $Authenticator
    * @param array $UserInfo
    * @param array $Payload
    */
   public function SyncScreen($Authenticator, $UserInfo, $Payload) {
      $this->AddJsFile('entry.js');
      $this->View = 'handshake';
      $this->HandshakeScheme = $Authenticator->GetAuthenticationSchemeAlias();
      $this->Form->SetModel($this->UserModel);
      $this->Form->AddHidden('ClientHour', date('G', time())); // Use the server's current hour as a default
      $this->Form->AddHidden('Target', $this->Target());
      
      $PreservedKeys = array(
         'UserKey', 'Token', 'Consumer', 'Email', 'Name', 'Gender', 'HourOffset'
      );
      $UserID = 0;
      $Target = $this->Target();
   
      if ($this->Form->IsPostBack() === TRUE) {
            
         $FormValues = $this->Form->FormValues();
         if (ArrayValue('StopLinking', $FormValues)) {
            $AuthResponse = Gdn_Authenticator::AUTH_ABORTED;
            
            $UserEventData = array_merge(array(
               'UserID'       => $UserID,
               'Payload'      => $Payload
            ),$UserInfo);
            Gdn::Authenticator()->Trigger($AuthResponse, $UserEventData);
            
            $Authenticator->DeleteCookie();
            Gdn::Request()->WithRoute('DefaultController');
            return Gdn::Dispatcher()->Dispatch();
            
         } elseif (ArrayValue('NewAccount', $FormValues)) {
            $AuthResponse = Gdn_Authenticator::AUTH_CREATED;
         
            // Try and synchronize the user with the new username/email.
            $FormValues['Name'] = $FormValues['NewName'];
            $FormValues['Email'] = $FormValues['NewEmail'];
            $UserID = $this->UserModel->Synchronize($UserInfo['UserKey'], $FormValues);
            $this->Form->SetValidationResults($this->UserModel->ValidationResults());
            
         } else {
            $AuthResponse = Gdn_Authenticator::AUTH_SUCCESS;
   
            // Try and sign the user in.
            $PasswordAuthenticator = Gdn::Authenticator()->AuthenticateWith('password');
            $PasswordAuthenticator->HookDataField('Email', 'SignInEmail');
            $PasswordAuthenticator->HookDataField('Password', 'SignInPassword');
            $PasswordAuthenticator->FetchData($this->Form);
            
            $UserID = $PasswordAuthenticator->Authenticate();
            
            if ($UserID < 0) {
               $this->Form->AddError('ErrorPermission');
            } else if ($UserID == 0) {
               $this->Form->AddError('ErrorCredentials');
            }
            
            if ($UserID > 0) {
               $Data = $FormValues;
               $Data['UserID'] = $UserID;
               $Data['Email'] = ArrayValue('SignInEmail', $FormValues, '');
               $UserID = $this->UserModel->Synchronize($UserInfo['UserKey'], $Data);
            }
         }
         
         if ($UserID > 0) {
            // The user has been created successfully, so sign in now
            
            // Finalize the link between the forum user and the foreign userkey
            $Authenticator->Finalize($UserInfo['UserKey'], $UserID, $UserInfo['ConsumerKey'], $UserInfo['TokenKey'], $Payload);
            
            $UserEventData = array_merge(array(
               'UserID'       => $UserID,
               'Payload'      => $Payload
            ),$UserInfo);
            Gdn::Authenticator()->Trigger($AuthResponse, $UserEventData);
            
            /// ... and redirect them appropriately
            $Route = $this->RedirectTo();
            if ($Route !== FALSE)
               Redirect($Route);
         } else {
            // Add the hidden inputs back into the form.
            foreach($FormValues as $Key => $Value) {
               if (in_array($Key, $PreservedKeys))
                  $this->Form->AddHidden($Key, $Value);
            }
         }
      } else {
         $Id = Gdn::Authenticator()->GetIdentity(TRUE);
         if ($Id > 0) {
            // The user is signed in so we can just go back to the homepage.
            Redirect($Target);
         }
         
         $Name = $UserInfo['UserName'];
         $Email = $UserInfo['UserEmail'];
         
         // Set the defaults for a new user.
         $this->Form->SetFormValue('NewName', $Name);
         $this->Form->SetFormValue('NewEmail', $Email);
         
         // Set the default for the login.
         $this->Form->SetFormValue('SignInEmail', $Email);
         $this->Form->SetFormValue('Handshake', 'NEW');
         
         // Add the handshake data as hidden fields.
         $this->Form->AddHidden('Name',       $Name);
         $this->Form->AddHidden('Email',      $Email);
         $this->Form->AddHidden('UserKey',    $UserInfo['UserKey']);
         $this->Form->AddHidden('Token',      $UserInfo['TokenKey']);
         $this->Form->AddHidden('Consumer',   $UserInfo['ConsumerKey']);
         
/*
         $this->Form->AddHidden('Payload',    serialize($Payload));
         $this->Form->AddHidden('UserInfo',   serialize($UserInfo));
*/
         
      }
      
      $this->SetData('Name', ArrayValue('Name', $this->Form->HiddenInputs));
      $this->SetData('Email', ArrayValue('Email', $this->Form->HiddenInputs));
      
      $this->Render();
   }
 /**
  * Edit a user account.
  *
  * @since 2.0.0
  * @access public
  * @param int $UserID Unique ID.
  */
 public function Edit($UserID)
 {
     $this->Permission('Garden.Users.Edit');
     // Page setup
     $this->AddJsFile('user.js');
     $this->Title(T('Edit User'));
     $this->AddSideMenu('dashboard/user');
     // Only admins can reassign roles
     $RoleModel = new RoleModel();
     $AllRoles = $RoleModel->GetArray();
     $RoleData = CheckPermission('Garden.Settings.Manage') ? $AllRoles : array();
     $UserModel = new UserModel();
     $User = $UserModel->GetID($UserID, DATASET_TYPE_ARRAY);
     // Determine if username can be edited
     $CanEditUsername = (bool) C("Garden.Profile.EditUsernames") || Gdn::Session()->CheckPermission('Garden.Users.Edit');
     $this->SetData('_CanEditUsername', $CanEditUsername);
     // Determine if emails can be edited
     $CanEditEmail = Gdn::Session()->CheckPermission('Garden.Users.Edit');
     $this->SetData('_CanEditEmail', $CanEditEmail);
     // Decide if they have ability to confirm users
     $Confirmed = (bool) GetValueR('Confirmed', $User);
     $CanConfirmEmail = UserModel::RequireConfirmEmail() && Gdn::Session()->CheckPermission('Garden.Users.Edit');
     $this->SetData('_CanConfirmEmail', $CanConfirmEmail);
     $this->SetData('_EmailConfirmed', $Confirmed);
     $User['ConfirmEmail'] = (int) $Confirmed;
     // Determine whether user being edited is privileged (can escalate permissions)
     $UserModel = new UserModel();
     $EditingPrivilegedUser = $UserModel->CheckPermission($User, 'Garden.Settings.Manage');
     // Determine our password reset options
     // Anyone with user editing my force reset over email
     $this->ResetOptions = array(0 => T('Keep current password.'), 'Auto' => T('Force user to reset their password and send email notification.'));
     // Only admins may manually reset passwords for other admins
     if (CheckPermission('Garden.Settings.Manage') || !$EditingPrivilegedUser) {
         $this->ResetOptions['Manual'] = T('Manually set user password. No email notification.');
     }
     // Set the model on the form.
     $this->Form->SetModel($UserModel);
     // Make sure the form knows which item we are editing.
     $this->Form->AddHidden('UserID', $UserID);
     try {
         $AllowEditing = TRUE;
         $this->EventArguments['AllowEditing'] =& $AllowEditing;
         $this->EventArguments['TargetUser'] =& $User;
         // These are all the 'effective' roles for this edit action. This list can
         // be trimmed down from the real list to allow subsets of roles to be
         // edited.
         $this->EventArguments['RoleData'] =& $RoleData;
         $UserRoleData = $UserModel->GetRoles($UserID)->ResultArray();
         $RoleIDs = ConsolidateArrayValuesByKey($UserRoleData, 'RoleID');
         $RoleNames = ConsolidateArrayValuesByKey($UserRoleData, 'Name');
         $UserRoleData = ArrayCombine($RoleIDs, $RoleNames);
         $this->EventArguments['UserRoleData'] =& $UserRoleData;
         $this->FireEvent("BeforeUserEdit");
         $this->SetData('AllowEditing', $AllowEditing);
         $this->Form->SetData($User);
         if ($this->Form->AuthenticatedPostBack()) {
             if (!$CanEditUsername) {
                 $this->Form->SetFormValue("Name", $User['Name']);
             }
             // Allow mods to confirm/unconfirm emails
             $this->Form->RemoveFormValue('Confirmed');
             $Confirmation = $this->Form->GetFormValue('ConfirmEmail', null);
             $Confirmation = !is_null($Confirmation) ? (bool) $Confirmation : null;
             if ($CanConfirmEmail && is_bool($Confirmation)) {
                 $this->Form->SetFormValue('Confirmed', (int) $Confirmation);
             }
             $ResetPassword = $this->Form->GetValue('ResetPassword', FALSE);
             // If we're an admin or this isn't a privileged user, allow manual setting of password
             $AllowManualReset = CheckPermission('Garden.Settings.Manage') || !$EditingPrivilegedUser;
             if ($ResetPassword == 'Manual' && $AllowManualReset) {
                 // If a new password was specified, add it to the form's collection
                 $NewPassword = $this->Form->GetValue('NewPassword', '');
                 $this->Form->SetFormValue('Password', $NewPassword);
             }
             // Role changes
             // These are the new roles the editing user wishes to apply to the target
             // user, adjusted for his ability to affect those roles
             $RequestedRoles = $this->Form->GetFormValue('RoleID');
             if (!is_array($RequestedRoles)) {
                 $RequestedRoles = array();
             }
             $RequestedRoles = array_flip($RequestedRoles);
             $UserNewRoles = array_intersect_key($RoleData, $RequestedRoles);
             // These roles will stay turned on regardless of the form submission contents
             // because the editing user does not have permission to modify them
             $ImmutableRoles = array_diff_key($AllRoles, $RoleData);
             $UserImmutableRoles = array_intersect_key($ImmutableRoles, $UserRoleData);
             // Apply immutable roles
             foreach ($UserImmutableRoles as $IMRoleID => $IMRoleName) {
                 $UserNewRoles[$IMRoleID] = $IMRoleName;
             }
             // Put the data back into the forum object as if the user had submitted
             // this themselves
             $this->Form->SetFormValue('RoleID', array_keys($UserNewRoles));
             if ($this->Form->Save(array('SaveRoles' => TRUE)) !== FALSE) {
                 if ($this->Form->GetValue('ResetPassword', '') == 'Auto') {
                     $UserModel->PasswordRequest($User['Email']);
                     $UserModel->SetField($UserID, 'HashMethod', 'Reset');
                 }
                 $this->InformMessage(T('Your changes have been saved.'));
             }
             $UserRoleData = $UserNewRoles;
         }
     } catch (Exception $Ex) {
         $this->Form->AddError($Ex);
     }
     $this->SetData('User', $User);
     $this->SetData('Roles', $RoleData);
     $this->SetData('UserRoles', $UserRoleData);
     $this->Render();
 }
 /**
  * @param Gdn_Controller $Sender
  * @param array $Args
  */
 protected function Settings_AddEdit($Sender, $Args)
 {
     $client_id = $Sender->Request->Get('client_id');
     Gdn::Locale()->SetTranslation('AuthenticationKey', 'Client ID');
     Gdn::Locale()->SetTranslation('AssociationSecret', 'Secret');
     Gdn::Locale()->SetTranslation('AuthenticateUrl', 'Authentication Url');
     $Form = new Gdn_Form();
     $Sender->Form = $Form;
     if ($Form->AuthenticatedPostBack()) {
         if ($Form->GetFormValue('Generate') || $Sender->Request->Post('Generate')) {
             $Form->SetFormValue('AuthenticationKey', mt_rand());
             $Form->SetFormValue('AssociationSecret', md5(mt_rand()));
             $Sender->SetFormSaved(FALSE);
         } else {
             $Form->ValidateRule('AuthenticationKey', 'ValidateRequired');
             //          $Form->ValidateRule('AuthenticationKey', 'regex:`^[a-z0-9_-]+$`i', T('The client id must contain only letters, numbers and dashes.'));
             $Form->ValidateRule('AssociationSecret', 'ValidateRequired');
             $Form->ValidateRule('AuthenticateUrl', 'ValidateRequired');
             $Values = $Form->FormValues();
             //        $Values = ArrayTranslate($Values, array('Name', 'AuthenticationKey', 'URL', 'AssociationSecret', 'AuthenticateUrl', 'SignInUrl', 'RegisterUrl', 'SignOutUrl', 'IsDefault'));
             $Values['AuthenticationSchemeAlias'] = 'jsconnect';
             $Values['AssociationHashMethod'] = 'md5';
             $Values['Attributes'] = serialize(array('HashType' => $Form->GetFormValue('HashType'), 'TestMode' => $Form->GetFormValue('TestMode'), 'Trusted' => $Form->GetFormValue('Trusted', 0)));
             if ($Form->ErrorCount() == 0) {
                 if ($client_id) {
                     Gdn::SQL()->Put('UserAuthenticationProvider', $Values, array('AuthenticationKey' => $client_id));
                 } else {
                     Gdn::SQL()->Options('Ignore', TRUE)->Insert('UserAuthenticationProvider', $Values);
                 }
                 $Sender->RedirectUrl = Url('/settings/jsconnect');
             }
         }
     } else {
         if ($client_id) {
             $Provider = self::GetProvider($client_id);
             TouchValue('Trusted', $Provider, 1);
         } else {
             $Provider = array();
         }
         $Form->SetData($Provider);
     }
     $Sender->SetData('Title', sprintf(T($client_id ? 'Edit %s' : 'Add %s'), T('Connection')));
     $Sender->Render('Settings_AddEdit', '', 'plugins/jsconnect');
 }
   /**
    * 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();
   }
 protected function _AddEdit($Sender, $PocketID = FALSE)
 {
     $Form = new Gdn_Form();
     $PocketModel = new Gdn_Model('Pocket');
     $Form->SetModel($PocketModel);
     $Sender->ConditionModule = new ConditionModule($Sender);
     $Sender->Form = $Form;
     if ($Form->AuthenticatedPostBack()) {
         // Save the pocket.
         if ($PocketID !== FALSE) {
             $Form->SetFormValue('PocketID', $PocketID);
         }
         // Convert the form data into a format digestable by the database.
         $Repeat = $Form->GetFormValue('RepeatType');
         switch ($Repeat) {
             case Pocket::REPEAT_EVERY:
                 $PocketModel->Validation->ApplyRule('EveryFrequency', 'Integer');
                 $PocketModel->Validation->ApplyRule('EveryBegin', 'Integer');
                 $Frequency = $Form->GetFormValue('EveryFrequency', 1);
                 if (!$Frequency || !ValidateInteger($Frequency) || $Frequency < 1) {
                     $Frequency = 1;
                 }
                 $Repeat .= ' ' . $Frequency;
                 if ($Form->GetFormValue('EveryBegin', 1) > 1) {
                     $Repeat .= ',' . $Form->GetFormValue('EveryBegin');
                 }
                 break;
             case Pocket::REPEAT_INDEX:
                 $PocketModel->Validation->AddRule('IntegerArray', 'function:ValidateIntegerArray');
                 $PocketModel->Validation->ApplyRule('Indexes', 'IntegerArray');
                 $Indexes = explode(',', $Form->GetFormValue('Indexes', ''));
                 $Indexes = array_map('trim', $Indexes);
                 $Repeat .= ' ' . implode(',', $Indexes);
                 break;
             default:
                 break;
         }
         $Form->SetFormValue('Repeat', $Repeat);
         $Form->SetFormValue('Sort', 0);
         $Form->SetFormValue('Format', 'Raw');
         $Condition = Gdn_Condition::ToString($Sender->ConditionModule->Conditions(TRUE));
         $Form->SetFormValue('Condition', $Condition);
         if ($Form->GetFormValue('Ad', 0)) {
             $Form->SetFormValue('Type', Pocket::TYPE_AD);
         } else {
             $Form->SetFormValue('Type', Pocket::TYPE_DEFAULT);
         }
         $Saved = $Form->Save();
         if ($Saved) {
             $Sender->StatusMessage = T('Your changes have been saved.');
             $Sender->RedirectUrl = Url('settings/pockets');
         }
     } else {
         if ($PocketID !== FALSE) {
             // Load the pocket.
             $Pocket = $PocketModel->GetWhere(array('PocketID' => $PocketID))->FirstRow(DATASET_TYPE_ARRAY);
             if (!$Pocket) {
                 return Gdn::Dispatcher()->Dispatch('Default404');
             }
             // Convert some of the pocket data into a format digestable by the form.
             list($RepeatType, $RepeatFrequency) = Pocket::ParseRepeat($Pocket['Repeat']);
             $Pocket['RepeatType'] = $RepeatType;
             $Pocket['EveryFrequency'] = GetValue(0, $RepeatFrequency, 1);
             $Pocket['EveryBegin'] = GetValue(1, $RepeatFrequency, 1);
             $Pocket['Indexes'] = implode(',', $RepeatFrequency);
             $Pocket['Ad'] = $Pocket['Type'] == Pocket::TYPE_AD;
             $Sender->ConditionModule->Conditions(Gdn_Condition::FromString($Pocket['Condition']));
             $Form->SetData($Pocket);
         } else {
             // Default the repeat.
             $Form->SetFormValue('RepeatType', Pocket::REPEAT_ONCE);
         }
     }
     $Sender->Form = $Form;
     $Sender->SetData('Locations', $this->Locations);
     $Sender->SetData('LocationsArray', $this->GetLocationsArray());
     $Sender->SetData('Pages', array('' => '(' . T('All') . ')', 'activity' => 'activity', 'comments' => 'comments', 'dashboard' => 'dashboard', 'discussions' => 'discussions', 'inbox' => 'inbox', 'profile' => 'profile'));
     return $Sender->Render('AddEdit', '', 'plugins/Pockets');
 }
 /**
  * Edit a user account.
  *
  * @since 2.0.0
  * @access public
  * @param int $UserID Unique ID.
  */
 public function Edit($UserID)
 {
     $this->Permission('Garden.Users.Edit');
     // Page setup
     $this->AddJsFile('user.js');
     $this->Title(T('Edit User'));
     $this->AddSideMenu('dashboard/user');
     // Determine if username can be edited
     $this->CanEditUsername = TRUE;
     $this->CanEditUsername = $this->CanEditUsername & Gdn::Config("Garden.Profile.EditUsernames");
     $this->CanEditUsername = $this->CanEditUsername | Gdn::Session()->CheckPermission('Garden.Users.Edit');
     $RoleModel = new RoleModel();
     $AllRoles = $RoleModel->GetArray();
     // By default, people with access here can freely assign all roles
     $this->RoleData = $AllRoles;
     $UserModel = new UserModel();
     $this->User = $UserModel->GetID($UserID);
     // Set the model on the form.
     $this->Form->SetModel($UserModel);
     // Make sure the form knows which item we are editing.
     $this->Form->AddHidden('UserID', $UserID);
     try {
         $AllowEditing = TRUE;
         $this->EventArguments['AllowEditing'] =& $AllowEditing;
         $this->EventArguments['TargetUser'] =& $this->User;
         // These are all the 'effective' roles for this edit action. This list can
         // be trimmed down from the real list to allow subsets of roles to be
         // edited.
         $this->EventArguments['RoleData'] =& $this->RoleData;
         $UserRoleData = $UserModel->GetRoles($UserID)->ResultArray();
         $RoleIDs = ConsolidateArrayValuesByKey($UserRoleData, 'RoleID');
         $RoleNames = ConsolidateArrayValuesByKey($UserRoleData, 'Name');
         $this->UserRoleData = ArrayCombine($RoleIDs, $RoleNames);
         $this->EventArguments['UserRoleData'] =& $this->UserRoleData;
         $this->FireEvent("BeforeUserEdit");
         $this->SetData('AllowEditing', $AllowEditing);
         if (!$this->Form->AuthenticatedPostBack()) {
             $this->Form->SetData($this->User);
         } else {
             if (!$this->CanEditUsername) {
                 $this->Form->SetFormValue("Name", $this->User->Name);
             }
             // If a new password was specified, add it to the form's collection
             $ResetPassword = $this->Form->GetValue('ResetPassword', FALSE);
             $NewPassword = $this->Form->GetValue('NewPassword', '');
             if ($ResetPassword == 'Manual') {
                 $this->Form->SetFormValue('Password', $NewPassword);
             }
             // Role changes
             // These are the new roles the editing user wishes to apply to the target
             // user, adjusted for his ability to affect those roles
             $RequestedRoles = $this->Form->GetFormValue('RoleID');
             if (!is_array($RequestedRoles)) {
                 $RequestedRoles = array();
             }
             $RequestedRoles = array_flip($RequestedRoles);
             $UserNewRoles = array_intersect_key($this->RoleData, $RequestedRoles);
             // These roles will stay turned on regardless of the form submission contents
             // because the editing user does not have permission to modify them
             $ImmutableRoles = array_diff_key($AllRoles, $this->RoleData);
             $UserImmutableRoles = array_intersect_key($ImmutableRoles, $this->UserRoleData);
             // Apply immutable roles
             foreach ($UserImmutableRoles as $IMRoleID => $IMRoleName) {
                 $UserNewRoles[$IMRoleID] = $IMRoleName;
             }
             // Put the data back into the forum object as if the user had submitted
             // this themselves
             $this->Form->SetFormValue('RoleID', array_keys($UserNewRoles));
             if ($this->Form->Save(array('SaveRoles' => TRUE)) !== FALSE) {
                 if ($this->Form->GetValue('ResetPassword', '') == 'Auto') {
                     $UserModel->PasswordRequest($this->User->Email);
                     $UserModel->SetField($UserID, 'HashMethod', 'Reset');
                 }
                 $this->InformMessage(T('Your changes have been saved.'));
             }
             $this->UserRoleData = $UserNewRoles;
         }
     } catch (Exception $Ex) {
         $this->Form->AddError($Ex);
     }
     $this->Render();
 }
 /**
  * Set user's photo (avatar).
  *
  * @since 2.0.0
  * @access public
  * @param mixed $UserReference Unique identifier, possible username or ID.
  * @param string $Username.
  */
 public function Picture($UserReference = '', $Username = '', $UserID = '')
 {
     if (!C('Garden.Profile.EditPhotos', TRUE)) {
         throw ForbiddenException('@Editing user photos has been disabled.');
     }
     // Permission checks
     $this->Permission(array('Garden.Profiles.Edit', 'Moderation.Profiles.Edit', 'Garden.ProfilePicture.Edit'), FALSE);
     $Session = Gdn::Session();
     if (!$Session->IsValid()) {
         $this->Form->AddError('You must be authenticated in order to use this form.');
     }
     // Check ability to manipulate image
     $ImageManipOk = FALSE;
     if (function_exists('gd_info')) {
         $GdInfo = gd_info();
         $GdVersion = preg_replace('/[a-z ()]+/i', '', $GdInfo['GD Version']);
         if ($GdVersion < 2) {
             throw new Exception(sprintf(T("This installation of GD is too old (v%s). Vanilla requires at least version 2 or compatible."), $GdVersion));
         }
     } else {
         throw new Exception(sprintf(T("Unable to detect PHP GD installed on this system. Vanilla requires GD version 2 or better.")));
     }
     // Get user data & prep form.
     if ($this->Form->IsPostBack() && $this->Form->GetFormValue('UserID')) {
         $UserID = $this->Form->GetFormValue('UserID');
     }
     $this->GetUserInfo($UserReference, $Username, $UserID, TRUE);
     $this->Form->SetModel($this->UserModel);
     if ($this->Form->AuthenticatedPostBack() === TRUE) {
         $this->Form->SetFormValue('UserID', $this->User->UserID);
         $UploadImage = new Gdn_UploadImage();
         try {
             // Validate the upload
             $TmpImage = $UploadImage->ValidateUpload('Picture');
             // Generate the target image name.
             $TargetImage = $UploadImage->GenerateTargetName(PATH_UPLOADS, '', TRUE);
             $Basename = pathinfo($TargetImage, PATHINFO_BASENAME);
             $Subdir = StringBeginsWith(dirname($TargetImage), PATH_UPLOADS . '/', FALSE, TRUE);
             // Delete any previously uploaded image.
             $UploadImage->Delete(ChangeBasename($this->User->Photo, 'p%s'));
             // Save the uploaded image in profile size.
             $Props = $UploadImage->SaveImageAs($TmpImage, "userpics/{$Subdir}/p{$Basename}", C('Garden.Profile.MaxHeight', 1000), C('Garden.Profile.MaxWidth', 250), array('SaveGif' => C('Garden.Thumbnail.SaveGif')));
             $UserPhoto = sprintf($Props['SaveFormat'], "userpics/{$Subdir}/{$Basename}");
             //            // Save the uploaded image in preview size
             //            $UploadImage->SaveImageAs(
             //               $TmpImage,
             //               'userpics/t'.$ImageBaseName,
             //               Gdn::Config('Garden.Preview.MaxHeight', 100),
             //               Gdn::Config('Garden.Preview.MaxWidth', 75)
             //            );
             // Save the uploaded image in thumbnail size
             $ThumbSize = Gdn::Config('Garden.Thumbnail.Size', 40);
             $UploadImage->SaveImageAs($TmpImage, "userpics/{$Subdir}/n{$Basename}", $ThumbSize, $ThumbSize, array('Crop' => TRUE, 'SaveGif' => C('Garden.Thumbnail.SaveGif')));
         } catch (Exception $Ex) {
             $this->Form->AddError($Ex);
         }
         // If there were no errors, associate the image with the user
         if ($this->Form->ErrorCount() == 0) {
             if (!$this->UserModel->Save(array('UserID' => $this->User->UserID, 'Photo' => $UserPhoto), array('CheckExisting' => TRUE))) {
                 $this->Form->SetValidationResults($this->UserModel->ValidationResults());
             } else {
                 $this->User->Photo = $UserPhoto;
             }
         }
         // If there were no problems, redirect back to the user account
         if ($this->Form->ErrorCount() == 0) {
             $this->InformMessage(Sprite('Check', 'InformSprite') . T('Your changes have been saved.'), 'Dismissable AutoDismiss HasSprite');
             Redirect($this->DeliveryType() == DELIVERY_TYPE_VIEW ? UserUrl($this->User) : UserUrl($this->User, '', 'picture'));
         }
     }
     if ($this->Form->ErrorCount() > 0) {
         $this->DeliveryType(DELIVERY_TYPE_ALL);
     }
     $this->Title(T('Change Picture'));
     $this->_SetBreadcrumbs(T('Change My Picture'), UserUrl($this->User, '', 'picture'));
     $this->Render();
 }