getValue() public method

If the form has been posted back, it will retrieve the value from the form. If it hasn't been posted back, it gets the value from $this->_DataArray. Failing either of those, it returns $Default.
public getValue ( string $FieldName, mixed $Default = false ) : mixed
$FieldName string
$Default mixed
return mixed
 /**
  * Select Authentication method.
  *
  * @since 2.0.3
  * @access public
  *
  * @param string $AuthenticationSchemeAlias
  */
 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', $this->ConfigureList);
     $this->setData('PreFocusAuthenticationScheme', $PreFocusAuthenticationScheme);
     $this->render();
 }
 /**
  * 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();
 }
示例#3
0
 /**
  * Configuration of registration settings.
  *
  * Events: BeforeRegistrationUpdate
  *
  * @since 2.0.0
  * @access public
  * @param string $RedirectUrl Where to send user after registration.
  */
 public function registration($RedirectUrl = '')
 {
     $this->permission('Garden.Settings.Manage');
     $this->addSideMenu('dashboard/settings/registration');
     $this->addJsFile('registration.js');
     $this->title(t('Registration'));
     // Load roles with sign-in permission
     $RoleModel = new RoleModel();
     $this->RoleData = $RoleModel->getByPermission('Garden.SignIn.Allow');
     $this->setData('_Roles', array_column($this->RoleData->resultArray(), 'Name', 'RoleID'));
     // 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('Basic' => "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.", 'Connect' => "New users are only registered through SSO plugins.");
     // 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'));
     // Replace 'Captcha' with 'Basic' if needed
     if (c('Garden.Registration.Method') == 'Captcha') {
         saveToConfig('Garden.Registration.Method', 'Basic');
     }
     // Create a model to save configuration settings
     $Validation = new Gdn_Validation();
     $ConfigurationModel = new Gdn_ConfigurationModel($Validation);
     $registrationOptions = array('Garden.Registration.Method' => 'Basic', 'Garden.Registration.InviteExpiration', 'Garden.Registration.ConfirmEmail');
     $ConfigurationModel->setField($registrationOptions);
     $this->EventArguments['Validation'] =& $Validation;
     $this->EventArguments['Configuration'] =& $ConfigurationModel;
     $this->fireEvent('Registration');
     // Set the model on the forms.
     $this->Form->setModel($ConfigurationModel);
     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');
         // 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);
         // Event hook
         $this->EventArguments['ConfigurationModel'] =& $ConfigurationModel;
         $this->fireEvent('BeforeRegistrationUpdate');
         // Save!
         if ($this->Form->save() !== false) {
             $this->informMessage(t("Your settings have been saved."));
             if ($RedirectUrl != '') {
                 $this->RedirectUrl = $RedirectUrl;
             }
         }
     }
     $this->render();
 }
 /**
  * Move a category to a different parent.
  *
  * @param int $categoryID Unique ID for the category to move.
  * @throws Exception if category is not found.
  */
 public function moveCategory($categoryID)
 {
     // Check permission
     $this->permission(['Garden.Community.Manage', 'Garden.Settings.Manage'], false);
     $category = CategoryModel::categories($categoryID);
     if (!$category) {
         throw notFoundException();
     }
     $this->Form->setModel($this->CategoryModel);
     $this->Form->addHidden('CategoryID', $categoryID);
     $this->setData('Category', $category);
     $parentCategories = CategoryModel::getAncestors($categoryID);
     array_pop($parentCategories);
     if (!empty($parentCategories)) {
         $this->setData('ParentCategories', array_column($parentCategories, 'Name', 'CategoryID'));
     }
     if ($this->Form->authenticatedPostBack()) {
         // Verify we're only attempting to save specific values.
         $this->Form->formValues(['CategoryID' => $this->Form->getValue('CategoryID'), 'ParentCategoryID' => $this->Form->getValue('ParentCategoryID')]);
         $this->Form->save();
     } else {
         $this->Form->setData($category);
     }
     $this->render();
 }
 /**
  * Attach editor anywhere 'BodyBox' is used.
  *
  * It is not being used for editing a posted reply, so find another event to hook into.
  *
  * @param Gdn_Form $Sender
  */
 public function gdn_form_beforeBodyBox_handler($Sender, $Args)
 {
     // TODO have some way to prevent this content from getting loaded when in embedded.
     // The only problem is figuring out how to know when content is embedded.
     $attributes = array();
     if (val('Attributes', $Args)) {
         $attributes = val('Attributes', $Args);
     }
     // TODO move this property to constructor
     $this->Format = $Sender->getValue('Format');
     // Make sure we have some sort of format.
     if (!$this->Format) {
         $this->Format = c('Garden.InputFormatter', 'Html');
         $Sender->setValue('Format', $this->Format);
     }
     // If force Wysiwyg enabled in settings
     $needsConversion = !in_array($this->Format, array('Html', 'Wysiwyg'));
     if (c('Garden.InputFormatter', 'Wysiwyg') == 'Wysiwyg' && $this->ForceWysiwyg == true && $needsConversion) {
         $wysiwygBody = Gdn_Format::to($Sender->getValue('Body'), $this->Format);
         $Sender->setValue('Body', $wysiwygBody);
         $this->Format = 'Wysiwyg';
         $Sender->setValue('Format', $this->Format);
     }
     if (in_array(strtolower($this->Format), array_map('strtolower', $this->Formats))) {
         $c = Gdn::controller();
         // Set minor data for view
         $c->setData('_EditorInputFormat', $this->Format);
         // Get the generated editor toolbar from getEditorToolbar, and assign it data object for view.
         if (!isset($c->Data['_EditorToolbar'])) {
             $editorToolbar = $this->getEditorToolbar($attributes);
             $this->EventArguments['EditorToolbar'] =& $editorToolbar;
             $this->fireEvent('InitEditorToolbar');
             // Set data for view
             $c->setData('_EditorToolbar', $editorToolbar);
         }
         $c->addDefinition('canUpload', $this->canUpload);
         $c->setData('_canUpload', $this->canUpload);
         // Determine which controller (post or discussion) is invoking this.
         // At the moment they're both the same, but in future you may want
         // to know this information to modify it accordingly.
         $View = $c->fetchView('editor', '', 'plugins/editor');
         $Args['BodyBox'] .= $View;
     }
 }
 /**
  * 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 = $RoleModel->getAssignable();
     $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) valr('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 = array_column($UserRoleData, 'RoleID');
         $RoleNames = array_column($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();
 }
示例#7
0
 /**
  * Create or update a discussion.
  *
  * @since 2.0.0
  * @access public
  *
  * @param int $CategoryID Unique ID of the category to add the discussion to.
  */
 public function discussion($CategoryUrlCode = '')
 {
     // Override CategoryID if categories are disabled
     $UseCategories = $this->ShowCategorySelector = (bool) c('Vanilla.Categories.Use');
     if (!$UseCategories) {
         $CategoryUrlCode = '';
     }
     // Setup head
     $this->addJsFile('jquery.autosize.min.js');
     $this->addJsFile('autosave.js');
     $this->addJsFile('post.js');
     $Session = Gdn::session();
     Gdn_Theme::section('PostDiscussion');
     // Set discussion, draft, and category data
     $DiscussionID = isset($this->Discussion) ? $this->Discussion->DiscussionID : '';
     $DraftID = isset($this->Draft) ? $this->Draft->DraftID : 0;
     $Category = false;
     $CategoryModel = new CategoryModel();
     if (isset($this->Discussion)) {
         $this->CategoryID = $this->Discussion->CategoryID;
         $Category = CategoryModel::categories($this->CategoryID);
     } elseif ($CategoryUrlCode != '') {
         $Category = CategoryModel::categories($CategoryUrlCode);
         if ($Category) {
             $this->CategoryID = val('CategoryID', $Category);
         }
     }
     if ($Category) {
         $this->Category = (object) $Category;
         $this->setData('Category', $Category);
         $this->Form->addHidden('CategoryID', $this->Category->CategoryID);
         if (val('DisplayAs', $this->Category) == 'Discussions' && !$DraftID) {
             $this->ShowCategorySelector = false;
         } else {
             // Get all our subcategories to add to the category if we are in a Header or Categories category.
             $this->Context = CategoryModel::getSubtree($this->CategoryID);
         }
     } else {
         $this->CategoryID = 0;
         $this->Category = null;
     }
     $CategoryData = $this->ShowCategorySelector ? CategoryModel::categories() : false;
     // Check permission
     if (isset($this->Discussion)) {
         // Make sure that content can (still) be edited.
         $CanEdit = DiscussionModel::canEdit($this->Discussion);
         if (!$CanEdit) {
             throw permissionException('Vanilla.Discussions.Edit');
         }
         // Make sure only moderators can edit closed things
         if ($this->Discussion->Closed) {
             $this->permission('Vanilla.Discussions.Edit', true, 'Category', $this->Category->PermissionCategoryID);
         }
         $this->Form->setFormValue('DiscussionID', $this->Discussion->DiscussionID);
         $this->title(t('Edit Discussion'));
         if ($this->Discussion->Type) {
             $this->setData('Type', $this->Discussion->Type);
         } else {
             $this->setData('Type', 'Discussion');
         }
     } else {
         // Permission to add.
         if ($this->Category) {
             $this->permission('Vanilla.Discussions.Add', true, 'Category', $this->Category->PermissionCategoryID);
         } else {
             $this->permission('Vanilla.Discussions.Add');
         }
         $this->title(t('New Discussion'));
     }
     touchValue('Type', $this->Data, 'Discussion');
     // See if we should hide the category dropdown.
     if ($this->ShowCategorySelector) {
         $AllowedCategories = CategoryModel::getByPermission('Discussions.Add', $this->Form->getValue('CategoryID', $this->CategoryID), ['Archived' => 0, 'AllowDiscussions' => 1], ['AllowedDiscussionTypes' => $this->Data['Type']]);
         if (count($AllowedCategories) == 1) {
             $AllowedCategory = array_pop($AllowedCategories);
             $this->ShowCategorySelector = false;
             $this->Form->addHidden('CategoryID', $AllowedCategory['CategoryID']);
             if ($this->Form->isPostBack() && !$this->Form->getFormValue('CategoryID')) {
                 $this->Form->setFormValue('CategoryID', $AllowedCategory['CategoryID']);
             }
         }
     }
     // Set the model on the form
     $this->Form->setModel($this->DiscussionModel);
     if (!$this->Form->isPostBack()) {
         // Prep form with current data for editing
         if (isset($this->Discussion)) {
             $this->Form->setData($this->Discussion);
         } elseif (isset($this->Draft)) {
             $this->Form->setData($this->Draft);
         } else {
             if ($this->Category !== null) {
                 $this->Form->setData(array('CategoryID' => $this->Category->CategoryID));
             }
             $this->populateForm($this->Form);
         }
     } elseif ($this->Form->authenticatedPostBack()) {
         // Form was submitted
         // Save as a draft?
         $FormValues = $this->Form->formValues();
         $FormValues = $this->DiscussionModel->filterForm($FormValues);
         $this->deliveryType(Gdn::request()->getValue('DeliveryType', $this->_DeliveryType));
         if ($DraftID == 0) {
             $DraftID = $this->Form->getFormValue('DraftID', 0);
         }
         $Draft = $this->Form->buttonExists('Save_Draft') ? true : false;
         $Preview = $this->Form->buttonExists('Preview') ? true : false;
         if (!$Preview) {
             if (!is_object($this->Category) && is_array($CategoryData) && isset($FormValues['CategoryID'])) {
                 $this->Category = val($FormValues['CategoryID'], $CategoryData);
             }
             if (is_object($this->Category)) {
                 // Check category permissions.
                 if ($this->Form->getFormValue('Announce', '') && !$Session->checkPermission('Vanilla.Discussions.Announce', true, 'Category', $this->Category->PermissionCategoryID)) {
                     $this->Form->addError('You do not have permission to announce in this category', 'Announce');
                 }
                 if ($this->Form->getFormValue('Close', '') && !$Session->checkPermission('Vanilla.Discussions.Close', true, 'Category', $this->Category->PermissionCategoryID)) {
                     $this->Form->addError('You do not have permission to close in this category', 'Close');
                 }
                 if ($this->Form->getFormValue('Sink', '') && !$Session->checkPermission('Vanilla.Discussions.Sink', true, 'Category', $this->Category->PermissionCategoryID)) {
                     $this->Form->addError('You do not have permission to sink in this category', 'Sink');
                 }
                 if (!isset($this->Discussion) && (!$Session->checkPermission('Vanilla.Discussions.Add', true, 'Category', $this->Category->PermissionCategoryID) || !$this->Category->AllowDiscussions)) {
                     $this->Form->addError('You do not have permission to start discussions in this category', 'CategoryID');
                 }
             }
             $isTitleValid = true;
             $Name = trim($this->Form->getFormValue('Name', ''));
             if (!$Draft) {
                 // Let's be super aggressive and disallow titles with no word characters in them!
                 $hasWordCharacter = preg_match('/\\w/u', $Name) === 1;
                 if (!$hasWordCharacter || $Name != '' && Gdn_Format::text($Name) == '') {
                     $this->Form->addError(t('You have entered an invalid discussion title'), 'Name');
                     $isTitleValid = false;
                 }
             }
             if ($isTitleValid) {
                 // Trim the name.
                 $FormValues['Name'] = $Name;
                 $this->Form->setFormValue('Name', $Name);
             }
             if ($this->Form->errorCount() == 0) {
                 if ($Draft) {
                     $DraftID = $this->DraftModel->save($FormValues);
                     $this->Form->setValidationResults($this->DraftModel->validationResults());
                 } else {
                     $DiscussionID = $this->DiscussionModel->save($FormValues);
                     $this->Form->setValidationResults($this->DiscussionModel->validationResults());
                     if ($DiscussionID > 0) {
                         if ($DraftID > 0) {
                             $this->DraftModel->delete($DraftID);
                         }
                     }
                     if ($DiscussionID == SPAM || $DiscussionID == UNAPPROVED) {
                         $this->StatusMessage = t('DiscussionRequiresApprovalStatus', 'Your discussion will appear after it is approved.');
                         // Clear out the form so that a draft won't save.
                         $this->Form->formValues(array());
                         $this->render('Spam');
                         return;
                     }
                 }
             }
         } else {
             // If this was a preview click, create a discussion/comment shell with the values for this comment
             $this->Discussion = new stdClass();
             $this->Discussion->Name = $this->Form->getValue('Name', '');
             $this->Comment = new stdClass();
             $this->Comment->InsertUserID = $Session->User->UserID;
             $this->Comment->InsertName = $Session->User->Name;
             $this->Comment->InsertPhoto = $Session->User->Photo;
             $this->Comment->DateInserted = Gdn_Format::date();
             $this->Comment->Body = val('Body', $FormValues, '');
             $this->Comment->Format = val('Format', $FormValues, c('Garden.InputFormatter'));
             $this->EventArguments['Discussion'] =& $this->Discussion;
             $this->EventArguments['Comment'] =& $this->Comment;
             $this->fireEvent('BeforeDiscussionPreview');
             if ($this->_DeliveryType == DELIVERY_TYPE_ALL) {
                 $this->addAsset('Content', $this->fetchView('preview'));
             } else {
                 $this->View = 'preview';
             }
         }
         if ($this->Form->errorCount() > 0) {
             // Return the form errors
             $this->errorMessage($this->Form->errors());
         } elseif ($DiscussionID > 0 || $DraftID > 0) {
             // Make sure that the ajax request form knows about the newly created discussion or draft id
             $this->setJson('DiscussionID', $DiscussionID);
             $this->setJson('DraftID', $DraftID);
             if (!$Preview) {
                 // If the discussion was not a draft
                 if (!$Draft) {
                     // Redirect to the new discussion
                     $Discussion = $this->DiscussionModel->getID($DiscussionID, DATASET_TYPE_OBJECT, array('Slave' => false));
                     $this->setData('Discussion', $Discussion);
                     $this->EventArguments['Discussion'] = $Discussion;
                     $this->fireEvent('AfterDiscussionSave');
                     if ($this->_DeliveryType == DELIVERY_TYPE_ALL) {
                         redirect(discussionUrl($Discussion, 1)) . '?new=1';
                     } else {
                         $this->RedirectUrl = discussionUrl($Discussion, 1, true) . '?new=1';
                     }
                 } else {
                     // If this was a draft save, notify the user about the save
                     $this->informMessage(sprintf(t('Draft saved at %s'), Gdn_Format::date()));
                 }
             }
         }
     }
     // Add hidden fields for editing
     $this->Form->addHidden('DiscussionID', $DiscussionID);
     $this->Form->addHidden('DraftID', $DraftID, true);
     $this->fireEvent('BeforeDiscussionRender');
     if ($this->CategoryID) {
         $Breadcrumbs = CategoryModel::getAncestors($this->CategoryID);
     } else {
         $Breadcrumbs = array();
     }
     $Breadcrumbs[] = array('Name' => $this->data('Title'), 'Url' => val('AddUrl', val($this->data('Type'), DiscussionModel::discussionTypes()), '/post/discussion'));
     $this->setData('Breadcrumbs', $Breadcrumbs);
     $this->setData('_AnnounceOptions', $this->announceOptions());
     // Render view (posts/discussion.php or post/preview.php)
     $this->render();
 }
 /**
  * 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();
 }
 /**
  * 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();
 }
示例#10
0
 /**
  * Create a controller to deal with plugin settings in dashboard.
  *
  * @param Gdn_Controller $sender.
  * @param Gdn_Controller $args.
  */
 public function settingsEndpoint($sender, $args)
 {
     $sender->permission('Garden.Settings.Manage');
     $model = new Gdn_AuthenticationProviderModel();
     /* @var Gdn_Form $form */
     $form = new Gdn_Form();
     $form->setModel($model);
     $sender->Form = $form;
     if (!$form->AuthenticatedPostBack()) {
         $provider = $this->provider();
         $form->setData($provider);
     } else {
         $form->setFormValue('AuthenticationKey', $this->getProviderKey());
         $sender->Form->validateRule('AssociationKey', 'ValidateRequired', 'You must provide a unique AccountID.');
         $sender->Form->validateRule('AssociationSecret', 'ValidateRequired', 'You must provide a Secret');
         $sender->Form->validateRule('AuthorizeUrl', 'isUrl', 'You must provide a complete URL in the Authorize Url field.');
         $sender->Form->validateRule('TokenUrl', 'isUrl', 'You must provide a complete URL in the Token Url field.');
         // To satisfy the AuthenticationProviderModel, create a BaseUrl.
         $baseUrlParts = parse_url($form->getValue('AuthorizeUrl'));
         $baseUrl = val('scheme', $baseUrlParts) && val('host', $baseUrlParts) ? val('scheme', $baseUrlParts) . '://' . val('host', $baseUrlParts) : null;
         if ($baseUrl) {
             $form->setFormValue('BaseUrl', $baseUrl);
             $form->setFormValue('SignInUrl', $baseUrl);
             // kludge for default provider
         }
         if ($form->save()) {
             $sender->informMessage(t('Saved'));
         }
     }
     // Set up the form.
     $formFields = ['AssociationKey' => ['LabelCode' => 'Client ID', 'Description' => 'Enter the unique ID of the authentication application.'], 'AssociationSecret' => ['LabelCode' => 'Secret', 'Description' => 'Enter the secret provided by the authentication provider.'], 'AuthorizeUrl' => ['LabelCode' => 'Authorize Url', 'Description' => 'Enter the endpoint to be appended to the base domain to retrieve the authorization token for a user.'], 'TokenUrl' => ['LabelCode' => 'Token Url', 'Description' => 'Enter the endpoint to be appended to the base domain to retrieve the authorization token for a user.'], 'ProfileUrl' => ['LabelCode' => 'Profile Url', 'Description' => 'Enter the endpoint to be appended to the base domain to retrieve a user\'s profile.']];
     $formFields = $formFields + $this->getSettingsFormFields();
     $formFields['IsDefault'] = ['LabelCode' => 'Make this connection your default signin method.', 'Control' => 'checkbox'];
     $sender->setData('_Form', $formFields);
     $sender->addSideMenu();
     if (!$sender->data('Title')) {
         $sender->setData('Title', sprintf(T('%s Settings'), 'Oauth2 SSO'));
     }
     $view = $this->settingsView ? $this->settingsView : 'plugins/oauth2';
     // Create send the possible redirect URLs that will be required by Oculus and display them in the dashboard.
     // Use Gdn::Request instead of convience function so that we can return http and https.
     $redirectUrls = Gdn::request()->url('/entry/' . $this->getProviderKey(), true, true);
     $sender->setData('redirectUrls', $redirectUrls);
     $sender->render('settings', '', 'plugins/' . $view);
 }
示例#11
0
 /**
  * Edit user's preferences (mostly notification settings).
  *
  * @since 2.0.0
  * @access public
  * @param mixed $UserReference Unique identifier, possibly username or ID.
  * @param string $Username .
  * @param int $UserID Unique identifier.
  */
 public function preferences($UserReference = '', $Username = '', $UserID = '')
 {
     $this->addJsFile('profile.js');
     $Session = Gdn::session();
     $this->permission('Garden.SignIn.Allow');
     // Get user data
     $this->getUserInfo($UserReference, $Username, $UserID, true);
     $UserPrefs = dbdecode($this->User->Preferences);
     if ($this->User->UserID != $Session->UserID) {
         $this->permission(array('Garden.Users.Edit', 'Moderation.Profiles.Edit'), false);
     }
     if (!is_array($UserPrefs)) {
         $UserPrefs = array();
     }
     $MetaPrefs = UserModel::GetMeta($this->User->UserID, 'Preferences.%', 'Preferences.');
     // Define the preferences to be managed
     $Notifications = array();
     if (c('Garden.Profile.ShowActivities', true)) {
         $Notifications = array('Email.WallComment' => t('Notify me when people write on my wall.'), 'Email.ActivityComment' => t('Notify me when people reply to my wall comments.'), 'Popup.WallComment' => t('Notify me when people write on my wall.'), 'Popup.ActivityComment' => t('Notify me when people reply to my wall comments.'));
     }
     $this->Preferences = array('Notifications' => $Notifications);
     // Allow email notification of applicants (if they have permission & are using approval registration)
     if (checkPermission('Garden.Users.Approve') && c('Garden.Registration.Method') == 'Approval') {
         $this->Preferences['Notifications']['Email.Applicant'] = array(t('NotifyApplicant', 'Notify me when anyone applies for membership.'), 'Meta');
     }
     $this->fireEvent('AfterPreferencesDefined');
     // Loop through the preferences looking for duplicates, and merge into a single row
     $this->PreferenceGroups = array();
     $this->PreferenceTypes = array();
     foreach ($this->Preferences as $PreferenceGroup => $Preferences) {
         $this->PreferenceGroups[$PreferenceGroup] = array();
         $this->PreferenceTypes[$PreferenceGroup] = array();
         foreach ($Preferences as $Name => $Description) {
             $Location = 'Prefs';
             if (is_array($Description)) {
                 list($Description, $Location) = $Description;
             }
             $NameParts = explode('.', $Name);
             $PrefType = val('0', $NameParts);
             $SubName = val('1', $NameParts);
             if ($SubName != false) {
                 // Save an array of all the different types for this group
                 if (!in_array($PrefType, $this->PreferenceTypes[$PreferenceGroup])) {
                     $this->PreferenceTypes[$PreferenceGroup][] = $PrefType;
                 }
                 // Store all the different subnames for the group
                 if (!array_key_exists($SubName, $this->PreferenceGroups[$PreferenceGroup])) {
                     $this->PreferenceGroups[$PreferenceGroup][$SubName] = array($Name);
                 } else {
                     $this->PreferenceGroups[$PreferenceGroup][$SubName][] = $Name;
                 }
             } else {
                 $this->PreferenceGroups[$PreferenceGroup][$Name] = array($Name);
             }
         }
     }
     // Loop the preferences, setting defaults from the configuration.
     $CurrentPrefs = array();
     foreach ($this->Preferences as $PrefGroup => $Prefs) {
         foreach ($Prefs as $Pref => $Desc) {
             $Location = 'Prefs';
             if (is_array($Desc)) {
                 list($Desc, $Location) = $Desc;
             }
             if ($Location == 'Meta') {
                 $CurrentPrefs[$Pref] = val($Pref, $MetaPrefs, false);
             } else {
                 $CurrentPrefs[$Pref] = val($Pref, $UserPrefs, c('Preferences.' . $Pref, '0'));
             }
             unset($MetaPrefs[$Pref]);
         }
     }
     $CurrentPrefs = array_merge($CurrentPrefs, $MetaPrefs);
     $CurrentPrefs = array_map('intval', $CurrentPrefs);
     $this->setData('Preferences', $CurrentPrefs);
     if (UserModel::noEmail()) {
         $this->PreferenceGroups = self::_removeEmailPreferences($this->PreferenceGroups);
         $this->PreferenceTypes = self::_removeEmailPreferences($this->PreferenceTypes);
         $this->setData('NoEmail', true);
     }
     $this->setData('PreferenceGroups', $this->PreferenceGroups);
     $this->setData('PreferenceTypes', $this->PreferenceTypes);
     $this->setData('PreferenceList', $this->Preferences);
     if ($this->Form->authenticatedPostBack()) {
         // Get, assign, and save the preferences.
         $NewMetaPrefs = array();
         foreach ($this->Preferences as $PrefGroup => $Prefs) {
             foreach ($Prefs as $Pref => $Desc) {
                 $Location = 'Prefs';
                 if (is_array($Desc)) {
                     list($Desc, $Location) = $Desc;
                 }
                 $Value = $this->Form->getValue($Pref, null);
                 if (is_null($Value)) {
                     continue;
                 }
                 if ($Location == 'Meta') {
                     $NewMetaPrefs[$Pref] = $Value ? $Value : null;
                     if ($Value) {
                         $UserPrefs[$Pref] = $Value;
                         // dup for notifications code.
                     }
                 } else {
                     if (!$CurrentPrefs[$Pref] && !$Value) {
                         unset($UserPrefs[$Pref]);
                         // save some space
                     } else {
                         $UserPrefs[$Pref] = $Value;
                     }
                 }
             }
         }
         $this->UserModel->savePreference($this->User->UserID, $UserPrefs);
         UserModel::setMeta($this->User->UserID, $NewMetaPrefs, 'Preferences.');
         $this->setData('Preferences', array_merge($this->data('Preferences', array()), $UserPrefs, $NewMetaPrefs));
         if (count($this->Form->errors() == 0)) {
             $this->informMessage(sprite('Check', 'InformSprite') . t('Your preferences have been saved.'), 'Dismissable AutoDismiss HasSprite');
         }
     } else {
         $this->Form->setData($CurrentPrefs);
     }
     $this->title(t('Notification Preferences'));
     $this->_setBreadcrumbs($this->data('Title'), $this->canonicalUrl());
     $this->render();
 }