public function Choose($AuthenticationSchemeAlias = NULL) { $this->Permission('Garden.Settings.Manage'); $this->AddSideMenu('dashboard/authentication'); $this->Title(T('Authentication')); $this->AddCssFile('authentication.css'); $PreFocusAuthenticationScheme = NULL; if (!is_null($AuthenticationSchemeAlias)) { $PreFocusAuthenticationScheme = $AuthenticationSchemeAlias; } if ($this->Form->AuthenticatedPostback()) { $NewAuthSchemeAlias = $this->Form->GetValue('Garden.Authentication.Chooser'); $AuthenticatorInfo = Gdn::Authenticator()->GetAuthenticatorInfo($NewAuthSchemeAlias); if ($AuthenticatorInfo !== FALSE) { $CurrentAuthenticatorAlias = Gdn::Authenticator()->AuthenticateWith('default')->GetAuthenticationSchemeAlias(); // Disable current $AuthenticatorDisableEvent = "DisableAuthenticator" . ucfirst($CurrentAuthenticatorAlias); $this->FireEvent($AuthenticatorDisableEvent); // Enable new $AuthenticatorEnableEvent = "EnableAuthenticator" . ucfirst($NewAuthSchemeAlias); $this->FireEvent($AuthenticatorEnableEvent); $PreFocusAuthenticationScheme = $NewAuthSchemeAlias; $this->CurrentAuthenticationAlias = Gdn::Authenticator()->AuthenticateWith('default')->GetAuthenticationSchemeAlias(); } } $this->SetData('AuthenticationConfigureList', json_encode($this->ConfigureList)); $this->SetData('PreFocusAuthenticationScheme', $PreFocusAuthenticationScheme); $this->Render(); }
/** * * @param Gdn_Form $Sender */ public function Gdn_Form_BeforeBodyBox_Handler($Sender, $Args) { $this->_AddCLEditor(Gdn::Controller()); $Format = $Sender->GetValue('Format'); if ($Format) { $Formatter = Gdn::Factory($Format . 'Formatter'); if ($Formatter && method_exists($Formatter, 'FormatForWysiwyg')) { $Body = $Formatter->FormatForWysiwyg($Sender->GetValue('Body')); $Sender->SetValue('Body', $Body); } elseif (!in_array($Format, array('Html', 'Wysiwyg'))) { $Sender->SetValue('Body', Gdn_Format::To($Sender->GetValue('Body'), $Format)); } } $Sender->SetValue('Format', 'Wysiwyg'); }
/** * Request password reset. * * @access public * @since 2.0.0 */ public function PasswordRequest() { Gdn::Locale()->SetTranslation('Email', T(UserModel::SigninLabelCode())); if ($this->Form->IsPostBack() === TRUE) { $this->Form->ValidateRule('Email', 'ValidateRequired'); if ($this->Form->ErrorCount() == 0) { try { $Email = $this->Form->GetFormValue('Email'); if (!$this->UserModel->PasswordRequest($Email)) { $this->Form->SetValidationResults($this->UserModel->ValidationResults()); Logger::event('password_reset_failure', Logger::INFO, 'Can\'t find account associated with email/username {Input}.', array('Input' => $Email)); } } catch (Exception $ex) { $this->Form->AddError($ex->getMessage()); } if ($this->Form->ErrorCount() == 0) { $this->Form->AddError('Success!'); $this->View = 'passwordrequestsent'; Logger::event('password_reset_request', Logger::INFO, '{Input} has been sent a password reset email.', array('Input' => $Email)); } } else { if ($this->Form->ErrorCount() == 0) { $this->Form->AddError("Couldn't find an account associated with that email/username."); Logger::event('password_reset_failure', Logger::INFO, 'Can\'t find account associated with email/username {Input}.', array('Input' => $this->Form->GetValue('Email'))); } } } $this->Render(); }
/** * Configuration of registration settings. */ public function Registration($RedirectUrl = '') { $this->Permission('Garden.Registration.Manage'); if (!C('Garden.Registration.Manage', TRUE)) { return Gdn::Dispatcher()->Dispatch('Default404'); } $this->AddSideMenu('dashboard/settings/registration'); $this->AddJsFile('registration.js'); $this->Title(T('Registration')); // Create a model to save configuration settings $Validation = new Gdn_Validation(); $ConfigurationModel = new Gdn_ConfigurationModel($Validation); $ConfigurationModel->SetField(array('Garden.Registration.Method' => 'Captcha', 'Garden.Registration.CaptchaPrivateKey', 'Garden.Registration.CaptchaPublicKey', 'Garden.Registration.InviteExpiration')); // Set the model on the forms. $this->Form->SetModel($ConfigurationModel); // Load roles with sign-in permission $RoleModel = new RoleModel(); $this->RoleData = $RoleModel->GetByPermission('Garden.SignIn.Allow'); // Get the currently selected default roles // $this->ExistingRoleData = Gdn::Config('Garden.Registration.DefaultRoles'); // if (is_array($this->ExistingRoleData) === FALSE) // $this->ExistingRoleData = array(); // Get currently selected InvitationOptions $this->ExistingRoleInvitations = Gdn::Config('Garden.Registration.InviteRoles'); if (is_array($this->ExistingRoleInvitations) === FALSE) { $this->ExistingRoleInvitations = array(); } // Get the currently selected Expiration Length $this->InviteExpiration = Gdn::Config('Garden.Registration.InviteExpiration', ''); // Registration methods. $this->RegistrationMethods = array('Captcha' => "New users fill out a simple form and are granted access immediately.", 'Approval' => "New users are reviewed and approved by an administrator (that's you!).", 'Invitation' => "Existing members send invitations to new members."); // Options for how many invitations a role can send out per month. $this->InvitationOptions = array('0' => T('None'), '1' => '1', '2' => '2', '5' => '5', '-1' => T('Unlimited')); // Options for when invitations should expire. $this->InviteExpirationOptions = array('-1 week' => T('1 week after being sent'), '-2 weeks' => T('2 weeks after being sent'), '-1 month' => T('1 month after being sent'), 'FALSE' => T('never')); if ($this->Form->AuthenticatedPostBack() === FALSE) { $this->Form->SetData($ConfigurationModel->Data); } else { // Define some validation rules for the fields being saved $ConfigurationModel->Validation->ApplyRule('Garden.Registration.Method', 'Required'); // if($this->Form->GetValue('Garden.Registration.Method') != 'Closed') // $ConfigurationModel->Validation->ApplyRule('Garden.Registration.DefaultRoles', 'RequiredArray'); // Define the Garden.Registration.RoleInvitations setting based on the postback values $InvitationRoleIDs = $this->Form->GetValue('InvitationRoleID'); $InvitationCounts = $this->Form->GetValue('InvitationCount'); $this->ExistingRoleInvitations = ArrayCombine($InvitationRoleIDs, $InvitationCounts); $ConfigurationModel->ForceSetting('Garden.Registration.InviteRoles', $this->ExistingRoleInvitations); // Save! if ($this->Form->Save() !== FALSE) { $this->StatusMessage = T("Your settings have been saved."); if ($RedirectUrl != '') { $this->RedirectUrl = $RedirectUrl; } } } $this->Render(); }
/** * Invitation-only registration. Requires code. * * Events: RegistrationSuccessful * * @access private * @since 2.0.0 */ private function RegisterInvitation($InvitationCode) { Gdn::UserModel()->AddPasswordStrength($this); if ($this->Form->IsPostBack() === TRUE) { $this->InvitationCode = $this->Form->GetValue('InvitationCode'); // 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) { $this->Form->SetValidationResults($this->UserModel->ValidationResults()); } else { // The user has been created successfully, so sign in now. Gdn::Session()->Start($AuthUserID); if ($this->Form->GetFormValue('RememberMe')) { Gdn::Authenticator()->SetIdentity($AuthUserID, TRUE); } $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); } } else { $this->InvitationCode = $InvitationCode; } $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($CategoryUrlCode = '') { // Override CategoryID if categories are disabled $UseCategories = $this->ShowCategorySelector = (bool) C('Vanilla.Categories.Use'); if (!$UseCategories) { $CategoryUrlCode = ''; } // Setup head $this->AddJsFile('jquery.autosize.min.js'); $this->AddJsFile('post.js'); $this->AddJsFile('autosave.js'); $Session = Gdn::Session(); Gdn_Theme::Section('PostDiscussion'); // Set discussion, draft, and category data $DiscussionID = isset($this->Discussion) ? $this->Discussion->DiscussionID : ''; $DraftID = isset($this->Draft) ? $this->Draft->DraftID : 0; $Category = FALSE; if (isset($this->Discussion)) { $this->CategoryID = $this->Discussion->CategoryID; $Category = CategoryModel::Categories($this->CategoryID); } else { if ($CategoryUrlCode != '') { $CategoryModel = new CategoryModel(); $Category = $CategoryModel->GetByCode($CategoryUrlCode); $this->CategoryID = $Category->CategoryID; } } if ($Category) { $this->Category = (object) $Category; $this->SetData('Category', $Category); } else { $this->CategoryID = 0; $this->Category = NULL; } $CategoryData = $UseCategories ? CategoryModel::Categories() : FALSE; // Check permission if (isset($this->Discussion)) { // Permission to edit if ($this->Discussion->InsertUserID != $Session->UserID) { $this->Permission('Vanilla.Discussions.Edit', TRUE, 'Category', $this->Category->PermissionCategoryID); } // Make sure that content can (still) be edited. $EditContentTimeout = C('Garden.EditContentTimeout', -1); $CanEdit = $EditContentTimeout == -1 || strtotime($this->Discussion->DateInserted) + $EditContentTimeout > time(); if (!$CanEdit) { $this->Permission('Vanilla.Discussions.Edit', TRUE, 'Category', $this->Category->PermissionCategoryID); } // Make sure only moderators can edit closed things if ($this->Discussion->Closed) { $this->Permission('Vanilla.Discussions.Edit', TRUE, 'Category', $this->Category->PermissionCategoryID); } $this->Form->SetFormValue('DiscussionID', $this->Discussion->DiscussionID); $this->Title(T('Edit Discussion')); if ($this->Discussion->Type) { $this->SetData('Type', $this->Discussion->Type); } else { $this->SetData('Type', 'Discussion'); } } else { // Permission to add $this->Permission('Vanilla.Discussions.Add'); $this->Title(T('New Discussion')); } TouchValue('Type', $this->Data, 'Discussion'); // See if we should hide the category dropdown. $AllowedCategories = CategoryModel::GetByPermission('Discussions.Add', $this->Form->GetValue('CategoryID', $this->CategoryID), array('Archived' => 0, 'AllowDiscussions' => 1), array('AllowedDiscussionTypes' => $this->Data['Type'])); if (count($AllowedCategories) == 1) { $AllowedCategory = array_pop($AllowedCategories); $this->ShowCategorySelector = FALSE; $this->Form->AddHidden('CategoryID', $AllowedCategory['CategoryID']); if ($this->Form->IsPostBack() && !$this->Form->GetFormValue('CategoryID')) { $this->Form->SetFormValue('CategoryID', $AllowedCategory['CategoryID']); } } // Set the model on the form $this->Form->SetModel($this->DiscussionModel); if ($this->Form->IsPostBack() == FALSE) { // Prep form with current data for editing if (isset($this->Discussion)) { $this->Form->SetData($this->Discussion); } elseif (isset($this->Draft)) { $this->Form->SetData($this->Draft); } else { if ($this->Category !== NULL) { $this->Form->SetData(array('CategoryID' => $this->Category->CategoryID)); } $this->PopulateForm($this->Form); } } else { // Form was submitted // Save as a draft? $FormValues = $this->Form->FormValues(); $FormValues = $this->DiscussionModel->FilterForm($FormValues); $this->DeliveryType(GetIncomingValue('DeliveryType', $this->_DeliveryType)); if ($DraftID == 0) { $DraftID = $this->Form->GetFormValue('DraftID', 0); } $Draft = $this->Form->ButtonExists('Save Draft') ? TRUE : FALSE; $Preview = $this->Form->ButtonExists('Preview') ? TRUE : FALSE; if (!$Preview) { if (!is_object($this->Category) && is_array($CategoryData) && isset($FormValues['CategoryID'])) { $this->Category = GetValue($FormValues['CategoryID'], $CategoryData); } if (is_object($this->Category)) { // Check category permissions. if ($this->Form->GetFormValue('Announce', '') && !$Session->CheckPermission('Vanilla.Discussions.Announce', TRUE, 'Category', $this->Category->PermissionCategoryID)) { $this->Form->AddError('You do not have permission to announce in this category', 'Announce'); } if ($this->Form->GetFormValue('Close', '') && !$Session->CheckPermission('Vanilla.Discussions.Close', TRUE, 'Category', $this->Category->PermissionCategoryID)) { $this->Form->AddError('You do not have permission to close in this category', 'Close'); } if ($this->Form->GetFormValue('Sink', '') && !$Session->CheckPermission('Vanilla.Discussions.Sink', TRUE, 'Category', $this->Category->PermissionCategoryID)) { $this->Form->AddError('You do not have permission to sink in this category', 'Sink'); } if (!isset($this->Discussion) && (!$Session->CheckPermission('Vanilla.Discussions.Add', TRUE, 'Category', $this->Category->PermissionCategoryID) || !$this->Category->AllowDiscussions)) { $this->Form->AddError('You do not have permission to start discussions in this category', 'CategoryID'); } } // Make sure that the title will not be invisible after rendering $Name = trim($this->Form->GetFormValue('Name', '')); if ($Name != '' && Gdn_Format::Text($Name) == '') { $this->Form->AddError(T('You have entered an invalid discussion title'), 'Name'); } else { // Trim the name. $FormValues['Name'] = $Name; $this->Form->SetFormValue('Name', $Name); } if ($this->Form->ErrorCount() == 0) { if ($Draft) { $DraftID = $this->DraftModel->Save($FormValues); $this->Form->SetValidationResults($this->DraftModel->ValidationResults()); } else { $DiscussionID = $this->DiscussionModel->Save($FormValues, $this->CommentModel); $this->Form->SetValidationResults($this->DiscussionModel->ValidationResults()); if ($DiscussionID > 0) { if ($DraftID > 0) { $this->DraftModel->Delete($DraftID); } } if ($DiscussionID == SPAM || $DiscussionID == UNAPPROVED) { $this->StatusMessage = T('DiscussionRequiresApprovalStatus', 'Your discussion will appear after it is approved.'); $this->Render('Spam'); return; } } } } else { // If this was a preview click, create a discussion/comment shell with the values for this comment $this->Discussion = new stdClass(); $this->Discussion->Name = $this->Form->GetValue('Name', ''); $this->Comment = new stdClass(); $this->Comment->InsertUserID = $Session->User->UserID; $this->Comment->InsertName = $Session->User->Name; $this->Comment->InsertPhoto = $Session->User->Photo; $this->Comment->DateInserted = Gdn_Format::Date(); $this->Comment->Body = ArrayValue('Body', $FormValues, ''); $this->Comment->Format = GetValue('Format', $FormValues, C('Garden.InputFormatter')); $this->EventArguments['Discussion'] =& $this->Discussion; $this->EventArguments['Comment'] =& $this->Comment; $this->FireEvent('BeforeDiscussionPreview'); if ($this->_DeliveryType == DELIVERY_TYPE_ALL) { $this->AddAsset('Content', $this->FetchView('preview')); } else { $this->View = 'preview'; } } if ($this->Form->ErrorCount() > 0) { // Return the form errors $this->ErrorMessage($this->Form->Errors()); } else { if ($DiscussionID > 0 || $DraftID > 0) { // Make sure that the ajax request form knows about the newly created discussion or draft id $this->SetJson('DiscussionID', $DiscussionID); $this->SetJson('DraftID', $DraftID); if (!$Preview) { // If the discussion was not a draft if (!$Draft) { // Redirect to the new discussion $Discussion = $this->DiscussionModel->GetID($DiscussionID, DATASET_TYPE_OBJECT, array('Slave' => FALSE)); $this->SetData('Discussion', $Discussion); $this->EventArguments['Discussion'] = $Discussion; $this->FireEvent('AfterDiscussionSave'); if ($this->_DeliveryType == DELIVERY_TYPE_ALL) { Redirect(DiscussionUrl($Discussion)) . '?new=1'; } else { $this->RedirectUrl = DiscussionUrl($Discussion, '', TRUE) . '?new=1'; } } else { // If this was a draft save, notify the user about the save $this->InformMessage(sprintf(T('Draft saved at %s'), Gdn_Format::Date())); } } } } } // Add hidden fields for editing $this->Form->AddHidden('DiscussionID', $DiscussionID); $this->Form->AddHidden('DraftID', $DraftID, TRUE); $this->FireEvent('BeforeDiscussionRender'); if ($this->CategoryID) { $Breadcrumbs = CategoryModel::GetAncestors($this->CategoryID); } else { $Breadcrumbs = array(); } $Breadcrumbs[] = array('Name' => $this->Data('Title'), 'Url' => '/post/discussion'); $this->SetData('Breadcrumbs', $Breadcrumbs); $this->SetData('_AnnounceOptions', $this->AnnounceOptions()); // Render view (posts/discussion.php or post/preview.php) $this->Render(); }
/** * 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(); }
/** * 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(); }
/** * 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(' ', ' ', $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(); }
/** * 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 thumbnail (crop & center photo). * * @since 2.0.0 * @access public * @param mixed $UserReference Unique identifier, possible username or ID. * @param string $Username. */ public function Thumbnail($UserReference = '', $Username = '') { if (!C('Garden.Profile.EditPhotos', TRUE)) { throw ForbiddenException('@Editing user photos has been disabled.'); } // Initial permission checks (valid user) $this->Permission('Garden.SignIn.Allow'); $Session = Gdn::Session(); if (!$Session->IsValid()) { $this->Form->AddError('You must be authenticated in order to use this form.'); } // Need some extra JS // jcrop update jan28, 2014 as jQuery upgrade to 1.10.2 no longer // supported browser() $this->AddJsFile('jquery.jcrop.min.js'); $this->AddJsFile('profile.js'); $this->GetUserInfo($UserReference, $Username, '', TRUE); // Permission check (correct user) if ($this->User->UserID != $Session->UserID && !CheckPermission('Garden.Users.Edit') && !CheckPermission('Moderation.Profiles.Edit')) { throw new Exception(T('You cannot edit the thumbnail of another member.')); } // Form prep $this->Form->SetModel($this->UserModel); $this->Form->AddHidden('UserID', $this->User->UserID); // Confirm we have a photo to manipulate if (!$this->User->Photo) { $this->Form->AddError('You must first upload a picture before you can create a thumbnail.'); } // Define the thumbnail size $this->ThumbSize = Gdn::Config('Garden.Thumbnail.Size', 40); // Define the source (profile sized) picture & dimensions. $Basename = ChangeBasename($this->User->Photo, 'p%s'); $Upload = new Gdn_UploadImage(); $PhotoParsed = Gdn_Upload::Parse($Basename); $Source = $Upload->CopyLocal($Basename); if (!$Source) { $this->Form->AddError('You cannot edit the thumbnail of an externally linked profile picture.'); } else { $this->SourceSize = getimagesize($Source); } // We actually need to upload a new file to help with cdb ttls. $NewPhoto = $Upload->GenerateTargetName('userpics', trim(pathinfo($this->User->Photo, PATHINFO_EXTENSION), '.'), TRUE); // Add some more hidden form fields for jcrop $this->Form->AddHidden('x', '0'); $this->Form->AddHidden('y', '0'); $this->Form->AddHidden('w', $this->ThumbSize); $this->Form->AddHidden('h', $this->ThumbSize); $this->Form->AddHidden('HeightSource', $this->SourceSize[1]); $this->Form->AddHidden('WidthSource', $this->SourceSize[0]); $this->Form->AddHidden('ThumbSize', $this->ThumbSize); if ($this->Form->AuthenticatedPostBack() === TRUE) { try { // Get the dimensions from the form. Gdn_UploadImage::SaveImageAs($Source, ChangeBasename($NewPhoto, 'n%s'), $this->ThumbSize, $this->ThumbSize, array('Crop' => TRUE, 'SourceX' => $this->Form->GetValue('x'), 'SourceY' => $this->Form->GetValue('y'), 'SourceWidth' => $this->Form->GetValue('w'), 'SourceHeight' => $this->Form->GetValue('h'))); // Save new profile picture. $Parsed = $Upload->SaveAs($Source, ChangeBasename($NewPhoto, 'p%s')); $UserPhoto = sprintf($Parsed['SaveFormat'], $NewPhoto); // Save the new photo info. Gdn::UserModel()->SetField($this->User->UserID, 'Photo', $UserPhoto); // Remove the old profile picture. @$Upload->Delete($Basename); } catch (Exception $Ex) { $this->Form->AddError($Ex); } // If there were no problems, redirect back to the user account if ($this->Form->ErrorCount() == 0) { Redirect(UserUrl($this->User, '', 'picture')); $this->InformMessage(Sprite('Check', 'InformSprite') . T('Your changes have been saved.'), 'Dismissable AutoDismiss HasSprite'); } } // Delete the source image if it is externally hosted. if ($PhotoParsed['Type']) { @unlink($Source); } $this->Title(T('Edit My Thumbnail')); $this->_SetBreadcrumbs(T('Edit My Thumbnail'), '/profile/thumbnail'); $this->Render(); }
/** * Populates the dropdown list for searching in certain categories -direct copy pretty * much out of the core of vanilla * * @param string $FieldName * @param mixed $Options * @return mixed dropdown list */ public function CategoryDropDown($FieldName = 'forums[]', $Options = FALSE) { $Form = new Gdn_Form(); //get form object $Value = ArrayValueI('Value', $Options); // The selected category id $CategoryData = GetValue('CategoryData', $Options, CategoryModel::Categories()); // Sanity check if (is_object($CategoryData)) { $CategoryData = (array) $CategoryData; } else { if (!is_array($CategoryData)) { $CategoryData = array(); } } // Respect category permissions (remove categories that the user shouldn't see). $SafeCategoryData = array(); foreach ($CategoryData as $CategoryID => $Category) { if ($Value != $CategoryID) { if ($Category['CategoryID'] < 0 || !$Category['PermsDiscussionsView']) { continue; } } $SafeCategoryData[$CategoryID] = $Category; } // Opening select tag $Return = '<select'; $Return .= ' multiple="multiple"'; $Return .= ' id="SearchDropdown"'; $Return .= ' name="' . $FieldName . '"'; $Return .= ' size="4"'; $Return .= ">\n"; // Get value from attributes if ($Value === FALSE) { $Value = $Form->GetValue($FieldName); $Return .= '<option value="0" selected="selected">All</option>'; $All = TRUE; } else { $Return .= '<option value="0">All</option>'; $All = FALSE; } if (!is_array($Value)) { $Value = array($Value); } // Prevent default $Value from matching key of zero $HasValue = $Value !== array(FALSE) && $Value !== array('') ? TRUE : FALSE; // Start with null option? //$Return .= '<option value="0" selected="selected">All</option>'; //Put an "All" categories option // Show root categories as headings (ie. you can't post in them)? $DoHeadings = C('Vanilla.Categories.DoHeadings'); // If making headings disabled and there was no default value for // selection, make sure to select the first non-disabled value, or the // browser will auto-select the first disabled option. $ForceCleanSelection = $DoHeadings && !$HasValue; // Write out the category options if (is_array($SafeCategoryData)) { foreach ($SafeCategoryData as $CategoryID => $Category) { $Depth = GetValue('Depth', $Category, 0); $Disabled = $Depth == 1 && $DoHeadings; $Selected = in_array($CategoryID, $Value) && $HasValue; if ($ForceCleanSelection && $Depth > 1) { $Selected = TRUE; $ForceCleanSelection = FALSE; } $Return .= '<option value="' . $CategoryID . '"'; if ($Disabled) { $Return .= ' disabled="disabled"'; } else { if ($Selected && $All == FALSE) { $Return .= ' selected="selected"'; } } // only allow selection if NOT disabled $Name = GetValue('Name', $Category, 'Blank Category Name'); if ($Depth > 1) { $Name = str_pad($Name, strlen($Name) + $Depth - 1, ' ', STR_PAD_LEFT); $Name = str_replace(' ', ' ', $Name); } $Return .= '>' . $Name . "</option>\n"; } } return $Return . '</select>'; }