This value is also used to identify fields in the $_POST or $_GET
(depending on the forms method) collection when the form is submitted.
public setModel ( Gdn_Model $Model, Ressource $DataSet = false ) | ||
$Model | Gdn_Model | The Model that will enforce data rules on $this->_DataArray. This value is passed by reference so any changes made to the model outside this object apply when it is referenced here. |
$DataSet | Ressource | A result resource containing data to be filled in the form. |
/** * 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(); }
/** * 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(); }
/** * Enabling and disabling categories from list. * * @since 2.0.0 * @access public */ public function manageCategories() { // Check permission $this->permission('Garden.Community.Manage'); $this->addSideMenu('vanilla/settings/managecategories'); $this->addJsFile('categories.js'); $this->addJsFile('jquery.alphanumeric.js'); // This now works on latest jQuery version 1.10.2 // // Jan29, 2014, upgraded jQuery UI to 1.10.3 from 1.8.11 $this->addJsFile('nestedSortable/jquery-ui.min.js'); // Newer nestedSortable, but does not work. //$this->addJsFile('js/library/nestedSortable/jquery.mjs.nestedSortable.js'); // old jquery-ui //$this->addJsFile('js/library/nestedSortable.1.3.4/jquery-ui-1.8.11.custom.min.js'); $this->addJsFile('nestedSortable.1.3.4/jquery.ui.nestedSortable.js'); $this->title(t('Categories')); // Get category data $CategoryData = $this->CategoryModel->getAll('TreeLeft'); // Set CanDelete per-category so we can override later if we want. $canDelete = checkPermission('Garden.Settings.Manage'); array_walk($CategoryData->result(), function (&$value) use($canDelete) { setvalr('CanDelete', $value, $canDelete); }); $this->setData('CategoryData', $CategoryData, true); // Setup & save forms $Validation = new Gdn_Validation(); $ConfigurationModel = new Gdn_ConfigurationModel($Validation); $ConfigurationModel->setField(array('Vanilla.Categories.MaxDisplayDepth', 'Vanilla.Categories.DoHeadings', 'Vanilla.Categories.HideModule')); // Set the model on the form. $this->Form->setModel($ConfigurationModel); // Define MaxDepthOptions $DepthData = array(); $DepthData['2'] = sprintf(t('more than %s deep'), plural(1, '%s level', '%s levels')); $DepthData['3'] = sprintf(t('more than %s deep'), plural(2, '%s level', '%s levels')); $DepthData['4'] = sprintf(t('more than %s deep'), plural(3, '%s level', '%s levels')); $DepthData['0'] = t('never'); $this->setData('MaxDepthData', $DepthData); // If seeing the form for the first time... if ($this->Form->authenticatedPostBack() === false) { // Apply the config settings to the form. $this->Form->setData($ConfigurationModel->Data); } else { if ($this->Form->save() !== false) { $this->informMessage(t("Your settings have been saved.")); } } // Render default view $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); } if (c('Garden.ForceInputFormatter')) { $this->Form->removeFormValue('Format'); } $this->View = 'editcomment'; $this->Comment($this->Comment->DiscussionID); }
/** * Set the icon for an addon. * * @param int $AddonID Specified addon id. * @throws Exception Addon not found. */ public function icon($AddonID = '') { $Session = Gdn::session(); if (!$Session->isValid()) { $this->Form->addError('You must be authenticated in order to use this form.'); } $Addon = $this->AddonModel->getID($AddonID); if (!$Addon) { throw notFoundException('Addon'); } if ($Session->UserID != $Addon['InsertUserID']) { $this->permission('Addons.Addon.Manage'); } $this->addModule('AddonHelpModule', 'Panel'); $this->Form->setModel($this->AddonModel); $this->Form->addHidden('AddonID', $AddonID); if ($this->Form->authenticatedPostBack()) { $UploadImage = new Gdn_UploadImage(); try { // Validate the upload $imageLocation = $UploadImage->validateUpload('Icon'); $TargetImage = $this->saveIcon($imageLocation); } catch (Exception $ex) { $this->Form->addError($ex); } // If there were no errors, remove the old picture and insert the picture if ($this->Form->errorCount() == 0) { if ($Addon['Icon']) { $UploadImage->delete($Addon['Icon']); } $this->AddonModel->save(array('AddonID' => $AddonID, 'Icon' => $TargetImage)); } // If there were no problems, redirect back to the addon if ($this->Form->errorCount() == 0) { $this->RedirectUrl = Url('/addon/' . AddonModel::slug($Addon)); } } $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 = $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(); }
/** * Allows the configuration of basic setup information in Garden. This * should not be functional after the application has been set up. * * @since 2.0.0 * @access public * @param string $RedirectUrl Where to send user afterward. */ private function configure($RedirectUrl = '') { // Create a model to save configuration settings $Validation = new Gdn_Validation(); $ConfigurationModel = new Gdn_ConfigurationModel($Validation); $ConfigurationModel->setField(array('Garden.Locale', 'Garden.Title', 'Garden.WebRoot', 'Garden.Cookie.Salt', 'Garden.Cookie.Domain', 'Database.Name', 'Database.Host', 'Database.User', 'Database.Password', 'Garden.Registration.ConfirmEmail', 'Garden.Email.SupportName')); // Set the models on the forms. $this->Form->setModel($ConfigurationModel); // If seeing the form for the first time... if (!$this->Form->isPostback()) { // Force the webroot using our best guesstimates $ConfigurationModel->Data['Database.Host'] = 'localhost'; $this->Form->setData($ConfigurationModel->Data); } else { // Define some validation rules for the fields being saved $ConfigurationModel->Validation->applyRule('Database.Name', 'Required', 'You must specify the name of the database in which you want to set up Vanilla.'); // Let's make some user-friendly custom errors for database problems $DatabaseHost = $this->Form->getFormValue('Database.Host', '~~Invalid~~'); $DatabaseName = $this->Form->getFormValue('Database.Name', '~~Invalid~~'); $DatabaseUser = $this->Form->getFormValue('Database.User', '~~Invalid~~'); $DatabasePassword = $this->Form->getFormValue('Database.Password', '~~Invalid~~'); $ConnectionString = GetConnectionString($DatabaseName, $DatabaseHost); try { $Connection = new PDO($ConnectionString, $DatabaseUser, $DatabasePassword); } catch (PDOException $Exception) { switch ($Exception->getCode()) { case 1044: $this->Form->addError(t('The database user you specified does not have permission to access the database. Have you created the database yet? The database reported: <code>%s</code>'), strip_tags($Exception->getMessage())); break; case 1045: $this->Form->addError(t('Failed to connect to the database with the username and password you entered. Did you mistype them? The database reported: <code>%s</code>'), strip_tags($Exception->getMessage())); break; case 1049: $this->Form->addError(t('It appears as though the database you specified does not exist yet. Have you created it yet? Did you mistype the name? The database reported: <code>%s</code>'), strip_tags($Exception->getMessage())); break; case 2005: $this->Form->addError(t("Are you sure you've entered the correct database host name? Maybe you mistyped it? The database reported: <code>%s</code>"), strip_tags($Exception->getMessage())); break; default: $this->Form->addError(sprintf(t('ValidateConnection'), strip_tags($Exception->getMessage()))); break; } } $ConfigurationModel->Validation->applyRule('Garden.Title', 'Required'); $ConfigurationFormValues = $this->Form->formValues(); if ($ConfigurationModel->validate($ConfigurationFormValues) !== true || $this->Form->errorCount() > 0) { // Apply the validation results to the form(s) $this->Form->setValidationResults($ConfigurationModel->validationResults()); } else { $Host = array_shift(explode(':', Gdn::request()->requestHost())); $Domain = Gdn::request()->domain(); // Set up cookies now so that the user can be signed in. $ExistingSalt = c('Garden.Cookie.Salt', false); $ConfigurationFormValues['Garden.Cookie.Salt'] = $ExistingSalt ? $ExistingSalt : betterRandomString(16, 'Aa0'); $ConfigurationFormValues['Garden.Cookie.Domain'] = ''; // Don't set this to anything by default. # Tim - 2010-06-23 // Additional default setup values. $ConfigurationFormValues['Garden.Registration.ConfirmEmail'] = true; $ConfigurationFormValues['Garden.Email.SupportName'] = $ConfigurationFormValues['Garden.Title']; $ConfigurationModel->save($ConfigurationFormValues, true); // If changing locale, redefine locale sources: $NewLocale = 'en-CA'; // $this->Form->getFormValue('Garden.Locale', false); if ($NewLocale !== false && Gdn::config('Garden.Locale') != $NewLocale) { $Locale = Gdn::locale(); $Locale->set($NewLocale); } // Install db structure & basic data. $Database = Gdn::database(); $Database->init(); $Drop = false; $Explicit = false; try { include PATH_APPLICATIONS . DS . 'dashboard' . DS . 'settings' . DS . 'structure.php'; } catch (Exception $ex) { $this->Form->addError($ex); } if ($this->Form->errorCount() > 0) { return false; } // Create the administrative user $UserModel = Gdn::userModel(); $UserModel->defineSchema(); $UsernameError = t('UsernameError', 'Username can only contain letters, numbers, underscores, and must be between 3 and 20 characters long.'); $UserModel->Validation->applyRule('Name', 'Username', $UsernameError); $UserModel->Validation->applyRule('Name', 'Required', t('You must specify an admin username.')); $UserModel->Validation->applyRule('Password', 'Required', t('You must specify an admin password.')); $UserModel->Validation->applyRule('Password', 'Match'); $UserModel->Validation->applyRule('Email', 'Email'); if (!($AdminUserID = $UserModel->SaveAdminUser($ConfigurationFormValues))) { $this->Form->setValidationResults($UserModel->validationResults()); } else { // The user has been created successfully, so sign in now. saveToConfig('Garden.Installed', true, array('Save' => false)); Gdn::session()->start($AdminUserID, true); saveToConfig('Garden.Installed', false, array('Save' => false)); } if ($this->Form->errorCount() > 0) { return false; } // Assign some extra settings to the configuration file if everything succeeded. $ApplicationInfo = array(); include CombinePaths(array(PATH_APPLICATIONS . DS . 'dashboard' . DS . 'settings' . DS . 'about.php')); // Detect Internet connection for CDNs $Disconnected = !(bool) @fsockopen('ajax.googleapis.com', 80); saveToConfig(array('Garden.Version' => val('Version', val('Dashboard', $ApplicationInfo, array()), 'Undefined'), 'Garden.Cdns.Disable' => $Disconnected, 'Garden.CanProcessImages' => function_exists('gd_info'), 'EnabledPlugins.GettingStarted' => 'GettingStarted', 'EnabledPlugins.HtmLawed' => 'HtmLawed')); } } return $this->Form->errorCount() == 0 ? true : false; }
/** * Invitation-only registration. Requires code. * * @param int $InvitationCode * @since 2.0.0 */ public function registerInvitation($InvitationCode = 0) { $this->Form->setModel($this->UserModel); // Define gender dropdown options $this->GenderOptions = array('u' => t('Unspecified'), 'm' => t('Male'), 'f' => t('Female')); if (!$this->Form->isPostBack()) { $this->Form->setValue('InvitationCode', $InvitationCode); } $InvitationModel = new InvitationModel(); // Look for the invitation. $Invitation = $InvitationModel->getWhere(array('Code' => $this->Form->getValue('InvitationCode')))->firstRow(DATASET_TYPE_ARRAY); if (!$Invitation) { $this->Form->addError('Invitation not found.', 'Code'); } else { if ($Expires = val('DateExpires', $Invitation)) { $Expires = Gdn_Format::toTimestamp($Expires); if ($Expires <= time()) { } } } $this->Form->addHidden('ClientHour', date('Y-m-d H:00')); // Use the server's current hour as a default $this->Form->addHidden('Target', $this->target()); 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, array('Method' => 'Invitation')); $this->setData('UserID', $AuthUserID); 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 { // Set some form defaults. if ($Name = val('Name', $Invitation)) { $this->Form->setValue('Name', $Name); } $this->InvitationCode = $InvitationCode; } // Make sure that the hour offset for new users gets defined when their account is created $this->addJsFile('entry.js'); $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(); }
/** * Shows all uncleared messages within a conversation for the viewing user * * @since 2.0.0 * @access public * * @param int $ConversationID Unique ID of conversation to view. * @param int $Offset Number to skip. * @param int $Limit Number to show. */ public function index($ConversationID = false, $Offset = -1, $Limit = '') { $this->Offset = $Offset; $Session = Gdn::session(); Gdn_Theme::section('Conversation'); // Figure out Conversation ID if (!is_numeric($ConversationID) || $ConversationID < 0) { $ConversationID = 0; } // Form setup for adding comments $this->Form->setModel($this->ConversationMessageModel); $this->Form->addHidden('ConversationID', $ConversationID); // Check permissions on the recipients. $InConversation = $this->ConversationModel->inConversation($ConversationID, Gdn::session()->UserID); if (!$InConversation) { // Conversation moderation must be enabled and they must have permission if (!c('Conversations.Moderation.Allow', false)) { throw permissionException(); } $this->permission('Conversations.Moderation.Manage'); } $this->Conversation = $this->ConversationModel->getID($ConversationID); $this->Conversation->Participants = $this->ConversationModel->getRecipients($ConversationID); $this->setData('Conversation', $this->Conversation); // Bad conversation? Redirect if ($this->Conversation === false) { throw notFoundException('Conversation'); } // Get limit if ($Limit == '' || !is_numeric($Limit) || $Limit < 0) { $Limit = Gdn::config('Conversations.Messages.PerPage', 50); } // Calculate counts if (!is_numeric($this->Offset) || $this->Offset < 0) { // Round down to the appropriate offset based on the user's read messages & messages per page $CountReadMessages = $this->Conversation->CountMessages - $this->Conversation->CountNewMessages; if ($CountReadMessages < 0) { $CountReadMessages = 0; } if ($CountReadMessages > $this->Conversation->CountMessages) { $CountReadMessages = $this->Conversation->CountMessages; } // (((67 comments / 10 perpage) = 6.7) rounded down = 6) * 10 perpage = offset 60; $this->Offset = floor($CountReadMessages / $Limit) * $Limit; // Send the hash link in. if ($CountReadMessages > 1) { $this->addDefinition('LocationHash', '#Item_' . $CountReadMessages); } } // Fetch message data $this->MessageData = $this->ConversationMessageModel->get($ConversationID, $Session->UserID, $this->Offset, $Limit); $this->EventArguments['MessageData'] = $this->MessageData; $this->fireEvent('beforeMessages'); $this->setData('Messages', $this->MessageData); // Figure out who's participating. $ParticipantTitle = ConversationModel::participantTitle($this->Conversation, true); $this->Participants = $ParticipantTitle; $this->title(strip_tags($this->Participants)); // $CountMessages = $this->ConversationMessageModel->getCount($ConversationID, $Session->UserID); // Build a pager $PagerFactory = new Gdn_PagerFactory(); $this->Pager = $PagerFactory->getPager('MorePager', $this); $this->Pager->MoreCode = 'Newer Messages'; $this->Pager->LessCode = 'Older Messages'; $this->Pager->ClientID = 'Pager'; $this->Pager->configure($this->Offset, $Limit, $this->Conversation->CountMessages, 'messages/' . $ConversationID . '/%1$s/%2$s/'); // Mark the conversation as ready by this user. $this->ConversationModel->markRead($ConversationID, $Session->UserID); // Deliver json data if necessary if ($this->_DeliveryType != DELIVERY_TYPE_ALL) { $this->setJson('LessRow', $this->Pager->toString('less')); $this->setJson('MoreRow', $this->Pager->toString('more')); $this->View = 'messages'; } // Add modules. $ClearHistoryModule = new ClearHistoryModule($this); $ClearHistoryModule->conversationID($ConversationID); $this->addModule($ClearHistoryModule); $InThisConversationModule = new InThisConversationModule($this); $InThisConversationModule->setData($this->Conversation->Participants); $this->addModule($InThisConversationModule); // Doesn't make sense for people who can't even start conversations to be adding people if (checkPermission('Conversations.Conversations.Add')) { $this->addModule('AddPeopleModule'); } $Subject = $this->data('Conversation.Subject'); if (!$Subject) { $Subject = t('Message'); } $this->Data['Breadcrumbs'][] = array('Name' => $Subject, 'Url' => url('', '//')); // Render view $this->render(); }
/** * 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); }
/** * Set user's photo (avatar). * * @since 2.0.0 * @access public * * @param mixed $userReference Unique identifier, possible username or ID. * @param string $username The username. * @param string $userID The user's ID. * * @throws Exception * @throws Gdn_UserException */ public function picture($userReference = '', $username = '', $userID = '') { $this->addJsFile('profile.js'); if (!$this->CanEditPhotos) { 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 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->authenticatedPostBack() && $this->Form->getFormValue('UserID')) { $userID = $this->Form->getFormValue('UserID'); } $this->getUserInfo($userReference, $username, $userID, true); $validation = new Gdn_Validation(); $configurationModel = new Gdn_ConfigurationModel($validation); $this->Form->setModel($configurationModel); $avatar = $this->User->Photo; if ($avatar === null) { $avatar = UserModel::getDefaultAvatarUrl(); } $source = ''; $crop = null; if ($this->isUploadedAvatar($avatar)) { // Get the image source so we can manipulate it in the crop module. $upload = new Gdn_UploadImage(); $thumbnailSize = c('Garden.Thumbnail.Size', 40); $basename = changeBasename($avatar, "p%s"); $source = $upload->copyLocal($basename); // Set up cropping. $crop = new CropImageModule($this, $this->Form, $thumbnailSize, $thumbnailSize, $source); $crop->setExistingCropUrl(Gdn_UploadImage::url(changeBasename($avatar, "n%s"))); $crop->setSourceImageUrl(Gdn_UploadImage::url(changeBasename($avatar, "p%s"))); $this->setData('crop', $crop); } else { $this->setData('avatar', $avatar); } if (!$this->Form->authenticatedPostBack()) { $this->Form->setData($configurationModel->Data); } else { if ($this->Form->save() !== false) { $upload = new Gdn_UploadImage(); $newAvatar = false; if ($tmpAvatar = $upload->validateUpload('Avatar', false)) { // New upload $thumbOptions = array('Crop' => true, 'SaveGif' => c('Garden.Thumbnail.SaveGif')); $newAvatar = $this->saveAvatars($tmpAvatar, $thumbOptions, $upload); } else { if ($avatar && $crop && $crop->isCropped()) { // New thumbnail $tmpAvatar = $source; $thumbOptions = array('Crop' => true, 'SourceX' => $crop->getCropXValue(), 'SourceY' => $crop->getCropYValue(), 'SourceWidth' => $crop->getCropWidth(), 'SourceHeight' => $crop->getCropHeight()); $newAvatar = $this->saveAvatars($tmpAvatar, $thumbOptions); } } if ($this->Form->errorCount() == 0) { if ($newAvatar !== false) { $thumbnailSize = c('Garden.Thumbnail.Size', 40); // Update crop properties. $basename = changeBasename($newAvatar, "p%s"); $source = $upload->copyLocal($basename); $crop = new CropImageModule($this, $this->Form, $thumbnailSize, $thumbnailSize, $source); $crop->setSize($thumbnailSize, $thumbnailSize); $crop->setExistingCropUrl(Gdn_UploadImage::url(changeBasename($newAvatar, "n%s"))); $crop->setSourceImageUrl(Gdn_UploadImage::url(changeBasename($newAvatar, "p%s"))); $this->setData('crop', $crop); } } if ($this->deliveryType() === DELIVERY_TYPE_VIEW) { $this->jsonTarget('', '', 'Refresh'); $this->RedirectUrl = userUrl($this->User); } $this->informMessage(t("Your settings have been saved.")); } } if (val('SideMenuModule', val('Panel', val('Assets', $this)))) { /** @var SideMenuModule $sidemenu */ $sidemenu = $this->Assets['Panel']['SideMenuModule']; $sidemenu->highlightRoute('/profile/picture'); } $this->title(t('Change Picture')); $this->_setBreadcrumbs(t('Change My Picture'), userUrl($this->User, '', 'picture')); $this->render('picture', 'profile', 'dashboard'); }
/** * * * @param $Sender * @param bool|false $PocketID * @return mixed * @throws Gdn_UserException */ 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'); }