setData() public method

Assign a set of data to be displayed in the form elements.
public setData ( array $Data )
$Data array A result resource or associative array containing data to be filled in
コード例 #1
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();
 }
コード例 #2
0
 /**
  * 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();
 }
コード例 #3
0
 /**
  * Remove an addon from a discussion.
  *
  * @param int $DiscussionID Discussion to remove addon attachment.
  * @throws Gdn_UserException Discussion not found.
  */
 public function detachFromDiscussion($DiscussionID = null)
 {
     $this->permission('Addons.Addon.Manage');
     $DiscussionModel = new DiscussionModel();
     $Discussion = $DiscussionModel->getID($DiscussionID);
     if ($Discussion) {
         $Addon = $this->AddonModel->getID($Discussion->AddonID);
         $this->Form->setData($Addon);
         $RedirectUrl = 'discussion/' . $Discussion->DiscussionID;
     } else {
         throw notFoundException('Discussion');
     }
     if ($this->Form->authenticatedPostBack()) {
         if (!$this->Form->getFormValue('DetachConfirm', false)) {
             $this->Form->addError(t('You must confirm the detachment'), 'DetachConfirm');
         } else {
             $DiscussionModel->setField($DiscussionID, 'AddonID', null);
             if ($this->deliveryType() === DELIVERY_TYPE_ALL) {
                 redirect($RedirectUrl);
             } else {
                 $this->informMessage(t('Successfully detached addon'));
                 $this->jsonTarget('.Warning.AddonAttachment', null, 'Remove');
                 $this->jsonTarget('a.AttachAddonDiscussion.Popup', t('Attach Addon...'), 'Text');
             }
         }
     }
     $this->render('detach');
 }
コード例 #4
0
 /**
  * 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();
 }
コード例 #5
0
 /**
  * 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();
 }
コード例 #6
0
 /**
  * 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;
 }
コード例 #7
0
 /**
  * Connect the user with an external source.
  *
  * This controller method is meant to be used with plugins that set its data array to work.
  * Events: ConnectData
  *
  * @since 2.0.0
  * @access public
  *
  * @param string $Method Used to register multiple providers on ConnectData event.
  */
 public function connect($Method)
 {
     $this->addJsFile('entry.js');
     $this->View = 'connect';
     $IsPostBack = $this->Form->isPostBack() && $this->Form->getFormValue('Connect', null) !== null;
     $UserSelect = $this->Form->getFormValue('UserSelect');
     if (!$IsPostBack) {
         // Here are the initial data array values. that can be set by a plugin.
         $Data = array('Provider' => '', 'ProviderName' => '', 'UniqueID' => '', 'FullName' => '', 'Name' => '', 'Email' => '', 'Photo' => '', 'Target' => $this->target());
         $this->Form->setData($Data);
         $this->Form->addHidden('Target', $this->Request->get('Target', '/'));
     }
     // The different providers can check to see if they are being used and modify the data array accordingly.
     $this->EventArguments = array($Method);
     // Fire ConnectData event & error handling.
     $currentData = $this->Form->formValues();
     // Filter the form data for users here. SSO plugins must reset validated data each postback.
     $filteredData = Gdn::userModel()->filterForm($currentData, true);
     $filteredData = array_replace($filteredData, arrayTranslate($currentData, ['TransientKey', 'hpt']));
     unset($filteredData['Roles'], $filteredData['RoleID']);
     $this->Form->formValues($filteredData);
     try {
         $this->EventArguments['Form'] = $this->Form;
         $this->fireEvent('ConnectData');
         $this->fireEvent('AfterConnectData');
     } catch (Gdn_UserException $Ex) {
         $this->Form->addError($Ex);
         return $this->render('ConnectError');
     } catch (Exception $Ex) {
         if (Debug()) {
             $this->Form->addError($Ex);
         } else {
             $this->Form->addError('There was an error fetching the connection data.');
         }
         return $this->render('ConnectError');
     }
     if (!UserModel::noEmail()) {
         if (!$this->Form->getFormValue('Email') || $this->Form->getFormValue('EmailVisible')) {
             $this->Form->setFormValue('EmailVisible', true);
             $this->Form->addHidden('EmailVisible', true);
             if ($IsPostBack) {
                 $this->Form->setFormValue('Email', val('Email', $currentData));
             }
         }
     }
     $FormData = $this->Form->formValues();
     // debug
     // Make sure the minimum required data has been provided to the connect.
     if (!$this->Form->getFormValue('Provider')) {
         $this->Form->addError('ValidateRequired', t('Provider'));
     }
     if (!$this->Form->getFormValue('UniqueID')) {
         $this->Form->addError('ValidateRequired', t('UniqueID'));
     }
     if (!$this->data('Verified')) {
         // Whatever event handler catches this must Set the data 'Verified' to true to prevent a random site from connecting without credentials.
         // This must be done EVERY postback and is VERY important.
         $this->Form->addError('The connection data has not been verified.');
     }
     if ($this->Form->errorCount() > 0) {
         return $this->render();
     }
     $UserModel = Gdn::userModel();
     // Check to see if there is an existing user associated with the information above.
     $Auth = $UserModel->getAuthentication($this->Form->getFormValue('UniqueID'), $this->Form->getFormValue('Provider'));
     $UserID = val('UserID', $Auth);
     // Check to synchronise roles upon connecting.
     if (($this->data('Trusted') || c('Garden.SSO.SyncRoles')) && $this->Form->getFormValue('Roles', null) !== null) {
         $SaveRoles = $SaveRolesRegister = true;
         // Translate the role names to IDs.
         $Roles = $this->Form->getFormValue('Roles', null);
         $Roles = RoleModel::getByName($Roles);
         $RoleIDs = array_keys($Roles);
         if (empty($RoleIDs)) {
             // The user must have at least one role. This protects that.
             $RoleIDs = $this->UserModel->newUserRoleIDs();
         }
         if (c('Garden.SSO.SyncRolesBehavior') === 'register') {
             $SaveRoles = false;
         }
         $this->Form->setFormValue('RoleID', $RoleIDs);
     } else {
         $SaveRoles = false;
         $SaveRolesRegister = false;
     }
     if ($UserID) {
         // The user is already connected.
         $this->Form->setFormValue('UserID', $UserID);
         if (c('Garden.Registration.ConnectSynchronize', true)) {
             $User = Gdn::userModel()->getID($UserID, DATASET_TYPE_ARRAY);
             $Data = $this->Form->formValues();
             // Don't overwrite the user photo if the user uploaded a new one.
             $Photo = val('Photo', $User);
             if (!val('Photo', $Data) || $Photo && !isUrl($Photo)) {
                 unset($Data['Photo']);
             }
             // Synchronize the user's data.
             $UserModel->save($Data, array('NoConfirmEmail' => true, 'FixUnique' => true, 'SaveRoles' => $SaveRoles));
         }
         // Always save the attributes because they may contain authorization information.
         if ($Attributes = $this->Form->getFormValue('Attributes')) {
             $UserModel->saveAttribute($UserID, $Attributes);
         }
         // Sign the user in.
         Gdn::session()->start($UserID, true, (bool) $this->Form->getFormValue('RememberMe', true));
         Gdn::userModel()->fireEvent('AfterSignIn');
         //         $this->_setRedirect(TRUE);
         $this->_setRedirect($this->Request->get('display') == 'popup');
     } elseif ($this->Form->getFormValue('Name') || $this->Form->getFormValue('Email')) {
         $NameUnique = c('Garden.Registration.NameUnique', true);
         $EmailUnique = c('Garden.Registration.EmailUnique', true);
         $AutoConnect = c('Garden.Registration.AutoConnect');
         if ($IsPostBack && $this->Form->getFormValue('ConnectName')) {
             $searchName = $this->Form->getFormValue('ConnectName');
         } else {
             $searchName = $this->Form->getFormValue('Name');
         }
         // Get the existing users that match the name or email of the connection.
         $Search = false;
         if ($searchName && $NameUnique) {
             $UserModel->SQL->orWhere('Name', $searchName);
             $Search = true;
         }
         if ($this->Form->getFormValue('Email') && ($EmailUnique || $AutoConnect)) {
             $UserModel->SQL->orWhere('Email', $this->Form->getFormValue('Email'));
             $Search = true;
         }
         if (is_numeric($UserSelect)) {
             $UserModel->SQL->orWhere('UserID', $UserSelect);
             $Search = true;
         }
         if ($Search) {
             $ExistingUsers = $UserModel->getWhere()->resultArray();
         } else {
             $ExistingUsers = array();
         }
         // Check to automatically link the user.
         if ($AutoConnect && count($ExistingUsers) > 0) {
             if ($IsPostBack && $this->Form->getFormValue('ConnectName')) {
                 $this->Form->setFormValue('Name', $this->Form->getFormValue('ConnectName'));
             }
             foreach ($ExistingUsers as $Row) {
                 if (strcasecmp($this->Form->getFormValue('Email'), $Row['Email']) === 0) {
                     $UserID = $Row['UserID'];
                     $this->Form->setFormValue('UserID', $UserID);
                     $Data = $this->Form->formValues();
                     if (c('Garden.Registration.ConnectSynchronize', true)) {
                         // Don't overwrite a photo if the user has already uploaded one.
                         $Photo = val('Photo', $Row);
                         if (!val('Photo', $Data) || $Photo && !stringBeginsWith($Photo, 'http')) {
                             unset($Data['Photo']);
                         }
                         $UserModel->save($Data, array('NoConfirmEmail' => true, 'FixUnique' => true, 'SaveRoles' => $SaveRoles));
                     }
                     if ($Attributes = $this->Form->getFormValue('Attributes')) {
                         $UserModel->saveAttribute($UserID, $Attributes);
                     }
                     // Save the userauthentication link.
                     $UserModel->saveAuthentication(array('UserID' => $UserID, 'Provider' => $this->Form->getFormValue('Provider'), 'UniqueID' => $this->Form->getFormValue('UniqueID')));
                     // Sign the user in.
                     Gdn::session()->start($UserID, true, (bool) $this->Form->getFormValue('RememberMe', true));
                     Gdn::userModel()->fireEvent('AfterSignIn');
                     //         $this->_setRedirect(TRUE);
                     $this->_setRedirect($this->Request->get('display') == 'popup');
                     $this->render();
                     return;
                 }
             }
         }
         $CurrentUserID = Gdn::session()->UserID;
         // Massage the existing users.
         foreach ($ExistingUsers as $Index => $UserRow) {
             if ($EmailUnique && $UserRow['Email'] == $this->Form->getFormValue('Email')) {
                 $EmailFound = $UserRow;
                 break;
             }
             if ($UserRow['Name'] == $this->Form->getFormValue('Name')) {
                 $NameFound = $UserRow;
             }
             if ($CurrentUserID > 0 && $UserRow['UserID'] == $CurrentUserID) {
                 unset($ExistingUsers[$Index]);
                 $CurrentUserFound = true;
             }
         }
         if (isset($EmailFound)) {
             // The email address was found and can be the only user option.
             $ExistingUsers = array($UserRow);
             $this->setData('NoConnectName', true);
         } elseif (isset($CurrentUserFound)) {
             $ExistingUsers = array_merge(array('UserID' => 'current', 'Name' => sprintf(t('%s (Current)'), Gdn::session()->User->Name)), $ExistingUsers);
         }
         if (!isset($NameFound) && !$IsPostBack) {
             $this->Form->setFormValue('ConnectName', $this->Form->getFormValue('Name'));
         }
         $this->setData('ExistingUsers', $ExistingUsers);
         if (UserModel::noEmail()) {
             $EmailValid = true;
         } else {
             $EmailValid = validateRequired($this->Form->getFormValue('Email'));
         }
         if ((!$UserSelect || $UserSelect == 'other') && $this->Form->getFormValue('Name') && $EmailValid && (!is_array($ExistingUsers) || count($ExistingUsers) == 0)) {
             // There is no existing user with the suggested name so we can just create the user.
             $User = $this->Form->formValues();
             $User['Password'] = randomString(50);
             // some password is required
             $User['HashMethod'] = 'Random';
             $User['Source'] = $this->Form->getFormValue('Provider');
             $User['SourceID'] = $this->Form->getFormValue('UniqueID');
             $User['Attributes'] = $this->Form->getFormValue('Attributes', null);
             $User['Email'] = $this->Form->getFormValue('ConnectEmail', $this->Form->getFormValue('Email', null));
             $UserID = $UserModel->register($User, array('CheckCaptcha' => false, 'ValidateEmail' => false, 'NoConfirmEmail' => true, 'SaveRoles' => $SaveRolesRegister));
             $User['UserID'] = $UserID;
             $this->Form->setValidationResults($UserModel->validationResults());
             if ($UserID) {
                 $UserModel->saveAuthentication(array('UserID' => $UserID, 'Provider' => $this->Form->getFormValue('Provider'), 'UniqueID' => $this->Form->getFormValue('UniqueID')));
                 $this->Form->setFormValue('UserID', $UserID);
                 $this->Form->setFormValue('UserSelect', false);
                 Gdn::session()->start($UserID, true, (bool) $this->Form->getFormValue('RememberMe', true));
                 Gdn::userModel()->fireEvent('AfterSignIn');
                 // Send the welcome email.
                 if (c('Garden.Registration.SendConnectEmail', false)) {
                     try {
                         $UserModel->sendWelcomeEmail($UserID, '', 'Connect', array('ProviderName' => $this->Form->getFormValue('ProviderName', $this->Form->getFormValue('Provider', 'Unknown'))));
                     } catch (Exception $Ex) {
                         // Do nothing if emailing doesn't work.
                     }
                 }
                 $this->_setRedirect(true);
             }
         }
     }
     // Save the user's choice.
     if ($IsPostBack) {
         // The user has made their decision.
         $PasswordHash = new Gdn_PasswordHash();
         if (!$UserSelect || $UserSelect == 'other') {
             // The user entered a username.
             $ConnectNameEntered = true;
             if ($this->Form->validateRule('ConnectName', 'ValidateRequired')) {
                 $ConnectName = $this->Form->getFormValue('ConnectName');
                 $User = false;
                 if (c('Garden.Registration.NameUnique')) {
                     // Check to see if there is already a user with the given name.
                     $User = $UserModel->getWhere(array('Name' => $ConnectName))->firstRow(DATASET_TYPE_ARRAY);
                 }
                 if (!$User) {
                     $this->Form->validateRule('ConnectName', 'ValidateUsername');
                 }
             }
         } else {
             // The user selected an existing user.
             $ConnectNameEntered = false;
             if ($UserSelect == 'current') {
                 if (Gdn::session()->UserID == 0) {
                     // This shouldn't happen, but a use could sign out in another browser and click submit on this form.
                     $this->Form->addError('@You were unexpectedly signed out.');
                 } else {
                     $UserSelect = Gdn::session()->UserID;
                 }
             }
             $User = $UserModel->getID($UserSelect, DATASET_TYPE_ARRAY);
         }
         if (isset($User) && $User) {
             // Make sure the user authenticates.
             if (!$User['UserID'] == Gdn::session()->UserID) {
                 if ($this->Form->validateRule('ConnectPassword', 'ValidateRequired', sprintf(t('ValidateRequired'), t('Password')))) {
                     try {
                         if (!$PasswordHash->checkPassword($this->Form->getFormValue('ConnectPassword'), $User['Password'], $User['HashMethod'], $this->Form->getFormValue('ConnectName'))) {
                             if ($ConnectNameEntered) {
                                 $this->Form->addError('The username you entered has already been taken.');
                             } else {
                                 $this->Form->addError('The password you entered is incorrect.');
                             }
                         }
                     } catch (Gdn_UserException $Ex) {
                         $this->Form->addError($Ex);
                     }
                 }
             }
         } elseif ($this->Form->errorCount() == 0) {
             // The user doesn't exist so we need to add another user.
             $User = $this->Form->formValues();
             $User['Name'] = $User['ConnectName'];
             $User['Password'] = randomString(50);
             // some password is required
             $User['HashMethod'] = 'Random';
             $UserID = $UserModel->register($User, array('CheckCaptcha' => false, 'NoConfirmEmail' => true, 'SaveRoles' => $SaveRolesRegister));
             $User['UserID'] = $UserID;
             $this->Form->setValidationResults($UserModel->validationResults());
             if ($UserID && c('Garden.Registration.SendConnectEmail', false)) {
                 // Send the welcome email.
                 $UserModel->sendWelcomeEmail($UserID, '', 'Connect', array('ProviderName' => $this->Form->getFormValue('ProviderName', $this->Form->getFormValue('Provider', 'Unknown'))));
             }
         }
         if ($this->Form->errorCount() == 0) {
             // Save the authentication.
             if (isset($User) && val('UserID', $User)) {
                 $UserModel->saveAuthentication(array('UserID' => $User['UserID'], 'Provider' => $this->Form->getFormValue('Provider'), 'UniqueID' => $this->Form->getFormValue('UniqueID')));
                 $this->Form->setFormValue('UserID', $User['UserID']);
             }
             // Sign the appropriate user in.
             Gdn::session()->start($this->Form->getFormValue('UserID'), true, (bool) $this->Form->getFormValue('RememberMe', true));
             Gdn::userModel()->fireEvent('AfterSignIn');
             $this->_setRedirect(true);
         }
     }
     $this->render();
 }
コード例 #8
0
 /**
  * Create or update a comment.
  *
  * @since 2.0.0
  * @access public
  *
  * @param int $DiscussionID Unique ID to add the comment to. If blank, this method will throw an error.
  */
 public function comment($DiscussionID = '')
 {
     // Get $DiscussionID from RequestArgs if valid
     if ($DiscussionID == '' && count($this->RequestArgs)) {
         if (is_numeric($this->RequestArgs[0])) {
             $DiscussionID = $this->RequestArgs[0];
         }
     }
     // If invalid $DiscussionID, get from form.
     $this->Form->setModel($this->CommentModel);
     $DiscussionID = is_numeric($DiscussionID) ? $DiscussionID : $this->Form->getFormValue('DiscussionID', 0);
     // Set discussion data
     $this->DiscussionID = $DiscussionID;
     $this->Discussion = $Discussion = $this->DiscussionModel->getID($DiscussionID);
     // Is this an embedded comment being posted to a discussion that doesn't exist yet?
     $vanilla_type = $this->Form->getFormValue('vanilla_type', '');
     $vanilla_url = $this->Form->getFormValue('vanilla_url', '');
     $vanilla_category_id = $this->Form->getFormValue('vanilla_category_id', '');
     $Attributes = array('ForeignUrl' => $vanilla_url);
     $vanilla_identifier = $this->Form->getFormValue('vanilla_identifier', '');
     $isEmbeddedComments = $vanilla_url != '' && $vanilla_identifier != '';
     // Only allow vanilla identifiers of 32 chars or less - md5 if larger
     if (strlen($vanilla_identifier) > 32) {
         $Attributes['vanilla_identifier'] = $vanilla_identifier;
         $vanilla_identifier = md5($vanilla_identifier);
     }
     if (!$Discussion && $isEmbeddedComments) {
         $Discussion = $Discussion = $this->DiscussionModel->getForeignID($vanilla_identifier, $vanilla_type);
         if ($Discussion) {
             $this->DiscussionID = $DiscussionID = $Discussion->DiscussionID;
             $this->Form->setValue('DiscussionID', $DiscussionID);
         }
     }
     // If so, create it!
     if (!$Discussion && $isEmbeddedComments) {
         // Add these values back to the form if they exist!
         $this->Form->addHidden('vanilla_identifier', $vanilla_identifier);
         $this->Form->addHidden('vanilla_type', $vanilla_type);
         $this->Form->addHidden('vanilla_url', $vanilla_url);
         $this->Form->addHidden('vanilla_category_id', $vanilla_category_id);
         $PageInfo = fetchPageInfo($vanilla_url);
         if (!($Title = $this->Form->getFormValue('Name'))) {
             $Title = val('Title', $PageInfo, '');
             if ($Title == '') {
                 $Title = t('Undefined discussion subject.');
                 if (!empty($PageInfo['Exception']) && $PageInfo['Exception'] === "Couldn't connect to host.") {
                     $Title .= ' ' . t('Page timed out.');
                 }
             }
         }
         $Description = val('Description', $PageInfo, '');
         $Images = val('Images', $PageInfo, array());
         $LinkText = t('EmbededDiscussionLinkText', 'Read the full story here');
         if (!$Description && count($Images) == 0) {
             $Body = formatString('<p><a href="{Url}">{LinkText}</a></p>', array('Url' => $vanilla_url, 'LinkText' => $LinkText));
         } else {
             $Body = formatString('
         <div class="EmbeddedContent">{Image}<strong>{Title}</strong>
            <p>{Excerpt}</p>
            <p><a href="{Url}">{LinkText}</a></p>
            <div class="ClearFix"></div>
         </div>', array('Title' => $Title, 'Excerpt' => $Description, 'Image' => count($Images) > 0 ? img(val(0, $Images), array('class' => 'LeftAlign')) : '', 'Url' => $vanilla_url, 'LinkText' => $LinkText));
         }
         if ($Body == '') {
             $Body = $vanilla_url;
         }
         if ($Body == '') {
             $Body = t('Undefined discussion body.');
         }
         // Validate the CategoryID for inserting.
         $Category = CategoryModel::categories($vanilla_category_id);
         if (!$Category) {
             $vanilla_category_id = c('Vanilla.Embed.DefaultCategoryID', 0);
             if ($vanilla_category_id <= 0) {
                 // No default category defined, so grab the first non-root category and use that.
                 $vanilla_category_id = $this->DiscussionModel->SQL->select('CategoryID')->from('Category')->where('CategoryID >', 0)->get()->firstRow()->CategoryID;
                 // No categories in the db? default to 0
                 if (!$vanilla_category_id) {
                     $vanilla_category_id = 0;
                 }
             }
         } else {
             $vanilla_category_id = $Category['CategoryID'];
         }
         $EmbedUserID = c('Garden.Embed.UserID');
         if ($EmbedUserID) {
             $EmbedUser = Gdn::userModel()->getID($EmbedUserID);
         }
         if (!$EmbedUserID || !$EmbedUser) {
             $EmbedUserID = Gdn::userModel()->getSystemUserID();
         }
         $EmbeddedDiscussionData = array('InsertUserID' => $EmbedUserID, 'DateInserted' => Gdn_Format::toDateTime(), 'DateUpdated' => Gdn_Format::toDateTime(), 'CategoryID' => $vanilla_category_id, 'ForeignID' => $vanilla_identifier, 'Type' => $vanilla_type, 'Name' => $Title, 'Body' => $Body, 'Format' => 'Html', 'Attributes' => dbencode($Attributes));
         $this->EventArguments['Discussion'] =& $EmbeddedDiscussionData;
         $this->fireEvent('BeforeEmbedDiscussion');
         $DiscussionID = $this->DiscussionModel->SQL->insert('Discussion', $EmbeddedDiscussionData);
         $ValidationResults = $this->DiscussionModel->validationResults();
         if (count($ValidationResults) == 0 && $DiscussionID > 0) {
             $this->Form->addHidden('DiscussionID', $DiscussionID);
             // Put this in the form so reposts won't cause new discussions.
             $this->Form->setFormValue('DiscussionID', $DiscussionID);
             // Put this in the form values so it is used when saving comments.
             $this->setJson('DiscussionID', $DiscussionID);
             $this->Discussion = $Discussion = $this->DiscussionModel->getID($DiscussionID, DATASET_TYPE_OBJECT, array('Slave' => false));
             // Update the category discussion count
             if ($vanilla_category_id > 0) {
                 $this->DiscussionModel->updateDiscussionCount($vanilla_category_id, $DiscussionID);
             }
         }
     }
     // If no discussion was found, error out
     if (!$Discussion) {
         $this->Form->addError(t('Failed to find discussion for commenting.'));
     }
     /**
      * Special care is taken for embedded comments.  Since we don't currently use an advanced editor for these
      * comments, we may need to apply certain filters and fixes to the data to maintain its intended display
      * with the input format (e.g. maintaining newlines).
      */
     if ($isEmbeddedComments) {
         $inputFormatter = $this->Form->getFormValue('Format', c('Garden.InputFormatter'));
         switch ($inputFormatter) {
             case 'Wysiwyg':
                 $this->Form->setFormValue('Body', nl2br($this->Form->getFormValue('Body')));
                 break;
         }
     }
     $PermissionCategoryID = val('PermissionCategoryID', $Discussion);
     // Setup head
     $this->addJsFile('jquery.autosize.min.js');
     $this->addJsFile('autosave.js');
     $this->addJsFile('post.js');
     // Setup comment model, $CommentID, $DraftID
     $Session = Gdn::session();
     $CommentID = isset($this->Comment) && property_exists($this->Comment, 'CommentID') ? $this->Comment->CommentID : '';
     $DraftID = isset($this->Comment) && property_exists($this->Comment, 'DraftID') ? $this->Comment->DraftID : '';
     $this->EventArguments['CommentID'] = $CommentID;
     $this->EventArguments['DraftID'] = $DraftID;
     // Determine whether we are editing
     $Editing = $CommentID > 0 || $DraftID > 0;
     $this->EventArguments['Editing'] = $Editing;
     // If closed, cancel & go to discussion
     if ($Discussion && $Discussion->Closed == 1 && !$Editing && !$Session->checkPermission('Vanilla.Discussions.Close', true, 'Category', $PermissionCategoryID)) {
         redirect(DiscussionUrl($Discussion));
     }
     // Add hidden IDs to form
     $this->Form->addHidden('DiscussionID', $DiscussionID);
     $this->Form->addHidden('CommentID', $CommentID);
     $this->Form->addHidden('DraftID', $DraftID, true);
     // Check permissions
     if ($Discussion && $Editing) {
         // Permission to edit
         if ($this->Comment->InsertUserID != $Session->UserID) {
             $this->permission('Vanilla.Comments.Edit', true, 'Category', $Discussion->PermissionCategoryID);
         }
         // Make sure that content can (still) be edited.
         $EditContentTimeout = c('Garden.EditContentTimeout', -1);
         $CanEdit = $EditContentTimeout == -1 || strtotime($this->Comment->DateInserted) + $EditContentTimeout > time();
         if (!$CanEdit) {
             $this->permission('Vanilla.Comments.Edit', true, 'Category', $Discussion->PermissionCategoryID);
         }
         // Make sure only moderators can edit closed things
         if ($Discussion->Closed) {
             $this->permission('Vanilla.Comments.Edit', true, 'Category', $Discussion->PermissionCategoryID);
         }
         $this->Form->setFormValue('CommentID', $CommentID);
     } elseif ($Discussion) {
         // Permission to add
         $this->permission('Vanilla.Comments.Add', true, 'Category', $Discussion->PermissionCategoryID);
     }
     if ($this->Form->authenticatedPostBack()) {
         // Save as a draft?
         $FormValues = $this->Form->formValues();
         $FormValues = $this->CommentModel->filterForm($FormValues);
         if (!$Editing) {
             unset($FormValues['CommentID']);
         }
         if ($DraftID == 0) {
             $DraftID = $this->Form->getFormValue('DraftID', 0);
         }
         $Type = GetIncomingValue('Type');
         $Draft = $Type == 'Draft';
         $this->EventArguments['Draft'] = $Draft;
         $Preview = $Type == 'Preview';
         if ($Draft) {
             $DraftID = $this->DraftModel->save($FormValues);
             $this->Form->addHidden('DraftID', $DraftID, true);
             $this->Form->setValidationResults($this->DraftModel->validationResults());
         } elseif (!$Preview) {
             // Fix an undefined title if we can.
             if ($this->Form->getFormValue('Name') && val('Name', $Discussion) == t('Undefined discussion subject.')) {
                 $Set = array('Name' => $this->Form->getFormValue('Name'));
                 if (isset($vanilla_url) && $vanilla_url && strpos(val('Body', $Discussion), t('Undefined discussion subject.')) !== false) {
                     $LinkText = t('EmbededDiscussionLinkText', 'Read the full story here');
                     $Set['Body'] = formatString('<p><a href="{Url}">{LinkText}</a></p>', array('Url' => $vanilla_url, 'LinkText' => $LinkText));
                 }
                 $this->DiscussionModel->setField(val('DiscussionID', $Discussion), $Set);
             }
             $Inserted = !$CommentID;
             $CommentID = $this->CommentModel->save($FormValues);
             // The comment is now half-saved.
             if (is_numeric($CommentID) && $CommentID > 0) {
                 if (in_array($this->deliveryType(), array(DELIVERY_TYPE_ALL, DELIVERY_TYPE_DATA))) {
                     $this->CommentModel->save2($CommentID, $Inserted, true, true);
                 } else {
                     $this->jsonTarget('', url("/post/comment2.json?commentid={$CommentID}&inserted={$Inserted}"), 'Ajax');
                 }
                 // $Discussion = $this->DiscussionModel->getID($DiscussionID);
                 $Comment = $this->CommentModel->getID($CommentID, DATASET_TYPE_OBJECT, array('Slave' => false));
                 $this->EventArguments['Discussion'] = $Discussion;
                 $this->EventArguments['Comment'] = $Comment;
                 $this->fireEvent('AfterCommentSave');
             } elseif ($CommentID === SPAM || $CommentID === UNAPPROVED) {
                 $this->StatusMessage = t('CommentRequiresApprovalStatus', 'Your comment will appear after it is approved.');
             }
             $this->Form->setValidationResults($this->CommentModel->validationResults());
             if ($CommentID > 0 && $DraftID > 0) {
                 $this->DraftModel->delete($DraftID);
             }
         }
         // Handle non-ajax requests first:
         if ($this->_DeliveryType == DELIVERY_TYPE_ALL) {
             if ($this->Form->errorCount() == 0) {
                 // Make sure that this form knows what comment we are editing.
                 if ($CommentID > 0) {
                     $this->Form->addHidden('CommentID', $CommentID);
                 }
                 // If the comment was not a draft
                 if (!$Draft) {
                     // Redirect to the new comment.
                     if ($CommentID > 0) {
                         redirect("discussion/comment/{$CommentID}/#Comment_{$CommentID}");
                     } elseif ($CommentID == SPAM) {
                         $this->setData('DiscussionUrl', DiscussionUrl($Discussion));
                         $this->View = 'Spam';
                     }
                 } elseif ($Preview) {
                     // If this was a preview click, create a comment shell with the values for this comment
                     $this->Comment = new stdClass();
                     $this->Comment->InsertUserID = $Session->User->UserID;
                     $this->Comment->InsertName = $Session->User->Name;
                     $this->Comment->InsertPhoto = $Session->User->Photo;
                     $this->Comment->DateInserted = Gdn_Format::date();
                     $this->Comment->Body = val('Body', $FormValues, '');
                     $this->Comment->Format = val('Format', $FormValues, c('Garden.InputFormatter'));
                     $this->addAsset('Content', $this->fetchView('preview'));
                 } else {
                     // If this was a draft save, notify the user about the save
                     $this->informMessage(sprintf(t('Draft saved at %s'), Gdn_Format::date()));
                 }
             }
         } else {
             // Handle ajax-based requests
             if ($this->Form->errorCount() > 0) {
                 // Return the form errors
                 $this->errorMessage($this->Form->errors());
             } else {
                 // Make sure that the ajax request form knows about the newly created comment or draft id
                 $this->setJson('CommentID', $CommentID);
                 $this->setJson('DraftID', $DraftID);
                 if ($Preview) {
                     // If this was a preview click, create a comment shell with the values for this comment
                     $this->Comment = new stdClass();
                     $this->Comment->InsertUserID = $Session->User->UserID;
                     $this->Comment->InsertName = $Session->User->Name;
                     $this->Comment->InsertPhoto = $Session->User->Photo;
                     $this->Comment->DateInserted = Gdn_Format::date();
                     $this->Comment->Body = val('Body', $FormValues, '');
                     $this->Comment->Format = val('Format', $FormValues, c('Garden.InputFormatter'));
                     $this->View = 'preview';
                 } elseif (!$Draft) {
                     // If the comment was not a draft
                     // If Editing a comment
                     if ($Editing) {
                         // Just reload the comment in question
                         $this->Offset = 1;
                         $Comments = $this->CommentModel->getIDData($CommentID, array('Slave' => false));
                         $this->setData('Comments', $Comments);
                         $this->setData('Discussion', $Discussion);
                         // Load the discussion
                         $this->ControllerName = 'discussion';
                         $this->View = 'comments';
                         // Also define the discussion url in case this request came from the post screen and needs to be redirected to the discussion
                         $this->setJson('DiscussionUrl', DiscussionUrl($this->Discussion) . '#Comment_' . $CommentID);
                     } else {
                         // If the comment model isn't sorted by DateInserted or CommentID then we can't do any fancy loading of comments.
                         $OrderBy = valr('0.0', $this->CommentModel->orderBy());
                         //                     $Redirect = !in_array($OrderBy, array('c.DateInserted', 'c.CommentID'));
                         //							$DisplayNewCommentOnly = $this->Form->getFormValue('DisplayNewCommentOnly');
                         //                     if (!$Redirect) {
                         //                        // Otherwise load all new comments that the user hasn't seen yet
                         //                        $LastCommentID = $this->Form->getFormValue('LastCommentID');
                         //                        if (!is_numeric($LastCommentID))
                         //                           $LastCommentID = $CommentID - 1; // Failsafe back to this new comment if the lastcommentid was not defined properly
                         //
                         //                        // Don't reload the first comment if this new comment is the first one.
                         //                        $this->Offset = $LastCommentID == 0 ? 1 : $this->CommentModel->GetOffset($LastCommentID);
                         //                        // Do not load more than a single page of data...
                         //                        $Limit = c('Vanilla.Comments.PerPage', 30);
                         //
                         //                        // Redirect if the new new comment isn't on the same page.
                         //                        $Redirect |= !$DisplayNewCommentOnly && PageNumber($this->Offset, $Limit) != PageNumber($Discussion->CountComments - 1, $Limit);
                         //                     }
                         //                     if ($Redirect) {
                         //                        // The user posted a comment on a page other than the last one, so just redirect to the last page.
                         //                        $this->RedirectUrl = Gdn::request()->Url("discussion/comment/$CommentID/#Comment_$CommentID", true);
                         //                     } else {
                         //                        // Make sure to load all new comments since the page was last loaded by this user
                         //								if ($DisplayNewCommentOnly)
                         $this->Offset = $this->CommentModel->GetOffset($CommentID);
                         $Comments = $this->CommentModel->GetIDData($CommentID, array('Slave' => false));
                         $this->setData('Comments', $Comments);
                         $this->setData('NewComments', true);
                         $this->ClassName = 'DiscussionController';
                         $this->ControllerName = 'discussion';
                         $this->View = 'comments';
                         //                     }
                         // Make sure to set the user's discussion watch records
                         $CountComments = $this->CommentModel->getCount($DiscussionID);
                         $Limit = is_object($this->data('Comments')) ? $this->data('Comments')->numRows() : $Discussion->CountComments;
                         $Offset = $CountComments - $Limit;
                         $this->CommentModel->SetWatch($this->Discussion, $Limit, $Offset, $CountComments);
                     }
                 } else {
                     // If this was a draft save, notify the user about the save
                     $this->informMessage(sprintf(t('Draft saved at %s'), Gdn_Format::date()));
                 }
                 // And update the draft count
                 $UserModel = Gdn::userModel();
                 $CountDrafts = $UserModel->getAttribute($Session->UserID, 'CountDrafts', 0);
                 $this->setJson('MyDrafts', t('My Drafts'));
                 $this->setJson('CountDrafts', $CountDrafts);
             }
         }
     } elseif ($this->Request->isPostBack()) {
         throw new Gdn_UserException(t('Invalid CSRF token.', 'Invalid CSRF token. Please try again.'), 401);
     } else {
         // Load form
         if (isset($this->Comment)) {
             $this->Form->setData((array) $this->Comment);
         }
     }
     // Include data for FireEvent
     if (property_exists($this, 'Discussion')) {
         $this->EventArguments['Discussion'] = $this->Discussion;
     }
     if (property_exists($this, 'Comment')) {
         $this->EventArguments['Comment'] = $this->Comment;
     }
     $this->fireEvent('BeforeCommentRender');
     if ($this->deliveryType() == DELIVERY_TYPE_DATA) {
         if ($this->data('Comments') instanceof Gdn_DataSet) {
             $Comment = $this->data('Comments')->firstRow(DATASET_TYPE_ARRAY);
             if ($Comment) {
                 $Photo = $Comment['InsertPhoto'];
                 if (strpos($Photo, '//') === false) {
                     $Photo = Gdn_Upload::url(changeBasename($Photo, 'n%s'));
                 }
                 $Comment['InsertPhoto'] = $Photo;
             }
             $this->Data = array('Comment' => $Comment);
         }
         $this->RenderData($this->Data);
     } else {
         require_once $this->fetchViewLocation('helper_functions', 'Discussion');
         // Render default view.
         $this->render();
     }
 }
コード例 #9
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 = Gdn_Format::unserialize($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();
 }
コード例 #10
0
 /**
  * SSO facilitator page. Plugins use event `ConnectData` to complete SSO connections.
  *
  * Users only see this page for non-seamless connections that prompt them to finish connecting
  * by entering a username and/or password (and possibly email).
  *
  * @since 2.0.0
  * @access public
  *
  * @param string $Method Used to register multiple providers on ConnectData event.
  */
 public function connect($Method)
 {
     // Basic page setup.
     $this->addJsFile('entry.js');
     $this->View = 'connect';
     $this->addDefinition('Username already exists.', t('Username already exists.'));
     $this->addDefinition('Choose a name to identify yourself on the site.', t('Choose a name to identify yourself on the site.'));
     // Determine what step in the process we're at.
     $IsPostBack = $this->Form->isPostBack() && $this->Form->getFormValue('Connect', null) !== null;
     $UserSelect = $this->Form->getFormValue('UserSelect');
     /**
      * When a user is connecting through SSO she is prompted to choose a username.
      * If she chooses an existing username, she is prompted to enter the password to claim it.
      * Setting AllowConnect = false disables that workflow, forcing the user to choose a unique username.
      */
     $allowConnect = c('Garden.Registration.AllowConnect', true);
     $this->setData('AllowConnect', $allowConnect);
     $this->addDefinition('AllowConnect', $allowConnect);
     if (!$IsPostBack) {
         // Initialize data array that can be set by a plugin.
         $Data = ['Provider' => '', 'ProviderName' => '', 'UniqueID' => '', 'FullName' => '', 'Name' => '', 'Email' => '', 'Photo' => '', 'Target' => $this->target()];
         $this->Form->setData($Data);
         $this->Form->addHidden('Target', $this->Request->get('Target', '/'));
     }
     // SSO providers can check to see if they are being used and modify the data array accordingly.
     $this->EventArguments = [$Method];
     // Filter the form data for users.
     // SSO plugins must reset validated data each postback.
     $currentData = $this->Form->formValues();
     $filteredData = Gdn::userModel()->filterForm($currentData, true);
     $filteredData = array_replace($filteredData, arrayTranslate($currentData, ['TransientKey', 'hpt']));
     unset($filteredData['Roles'], $filteredData['RoleID']);
     $this->Form->formValues($filteredData);
     // Fire ConnectData event & error handling.
     try {
         // Where your SSO plugin does magic.
         $this->EventArguments['Form'] = $this->Form;
         $this->fireEvent('ConnectData');
         $this->fireEvent('AfterConnectData');
     } catch (Gdn_UserException $Ex) {
         // Your SSO magic said no.
         $this->Form->addError($Ex);
         return $this->render('ConnectError');
     } catch (Exception $Ex) {
         // Your SSO magic blew up.
         if (debug()) {
             $this->Form->addError($Ex);
         } else {
             $this->Form->addError('There was an error fetching the connection data.');
         }
         return $this->render('ConnectError');
     }
     // Allow a provider to not send an email address but require one be manually entered.
     if (!UserModel::noEmail()) {
         $emailProvided = $this->Form->getFormValue('Email');
         $emailRequested = $this->Form->getFormValue('EmailVisible');
         if (!$emailProvided || $emailRequested) {
             $this->Form->setFormValue('EmailVisible', true);
             $this->Form->addHidden('EmailVisible', true);
             if ($IsPostBack) {
                 $this->Form->setFormValue('Email', val('Email', $currentData));
             }
         }
         if ($IsPostBack && $emailRequested) {
             $this->Form->validateRule('Email', 'ValidateRequired');
             $this->Form->validateRule('Email', 'ValidateEmail');
         }
     }
     // Make sure the minimum required data has been provided by the connection.
     if (!$this->Form->getFormValue('Provider')) {
         $this->Form->addError('ValidateRequired', t('Provider'));
     }
     if (!$this->Form->getFormValue('UniqueID')) {
         $this->Form->addError('ValidateRequired', t('UniqueID'));
     }
     if (!$this->data('Verified')) {
         // Whatever event handler catches this must set the data 'Verified' = true
         // to prevent a random site from connecting without credentials.
         // This must be done EVERY postback and is VERY important.
         $this->Form->addError(t('The connection data has not been verified.'));
     }
     // If we've accrued errors, stop here and show them.
     if ($this->Form->errorCount() > 0) {
         $this->render();
         return;
     }
     // Check if we need to sync roles
     if (($this->data('Trusted') || c('Garden.SSO.SyncRoles')) && $this->Form->getFormValue('Roles', null) !== null) {
         $SaveRoles = $SaveRolesRegister = true;
         // Translate the role names to IDs.
         $Roles = $this->Form->getFormValue('Roles', null);
         $Roles = RoleModel::getByName($Roles);
         $RoleIDs = array_keys($Roles);
         // Ensure user has at least one role.
         if (empty($RoleIDs)) {
             $RoleIDs = $this->UserModel->newUserRoleIDs();
         }
         // Allow role syncing to only happen on first connect.
         if (c('Garden.SSO.SyncRolesBehavior') === 'register') {
             $SaveRoles = false;
         }
         $this->Form->setFormValue('RoleID', $RoleIDs);
     } else {
         $SaveRoles = false;
         $SaveRolesRegister = false;
     }
     $UserModel = Gdn::userModel();
     // Find an existing user associated with this provider & uniqueid.
     $Auth = $UserModel->getAuthentication($this->Form->getFormValue('UniqueID'), $this->Form->getFormValue('Provider'));
     $UserID = val('UserID', $Auth);
     // The user is already in the UserAuthentication table
     if ($UserID) {
         $this->Form->setFormValue('UserID', $UserID);
         // Update their info.
         if (c('Garden.Registration.ConnectSynchronize', true)) {
             $User = Gdn::userModel()->getID($UserID, DATASET_TYPE_ARRAY);
             $Data = $this->Form->formValues();
             // Don't overwrite the user photo if the user uploaded a new one.
             $Photo = val('Photo', $User);
             if (!val('Photo', $Data) || $Photo && !isUrl($Photo)) {
                 unset($Data['Photo']);
             }
             // Synchronize the user's data.
             $UserModel->save($Data, ['NoConfirmEmail' => true, 'FixUnique' => true, 'SaveRoles' => $SaveRoles]);
             $this->EventArguments['UserID'] = $UserID;
             $this->fireEvent('AfterConnectSave');
         }
         // Always save the attributes because they may contain authorization information.
         if ($Attributes = $this->Form->getFormValue('Attributes')) {
             $UserModel->saveAttribute($UserID, $Attributes);
         }
         // Sign the user in.
         Gdn::session()->start($UserID, true, (bool) $this->Form->getFormValue('RememberMe', true));
         Gdn::userModel()->fireEvent('AfterSignIn');
         // Send them on their way.
         $this->_setRedirect(Gdn::request()->get('display') === 'popup');
         // If a name of email has been provided
     } elseif ($this->Form->getFormValue('Name') || $this->Form->getFormValue('Email')) {
         // Decide how to handle our first time connecting.
         $NameUnique = c('Garden.Registration.NameUnique', true);
         $EmailUnique = c('Garden.Registration.EmailUnique', true);
         $AutoConnect = c('Garden.Registration.AutoConnect');
         // Decide which name to search for.
         if ($IsPostBack && $this->Form->getFormValue('ConnectName')) {
             $searchName = $this->Form->getFormValue('ConnectName');
         } else {
             $searchName = $this->Form->getFormValue('Name');
         }
         // Find existing users that match the name or email of the connection.
         // First, discover if we have search criteria.
         $Search = false;
         $ExistingUsers = [];
         if ($searchName && $NameUnique) {
             $UserModel->SQL->orWhere('Name', $searchName);
             $Search = true;
         }
         if ($this->Form->getFormValue('Email') && ($EmailUnique || $AutoConnect)) {
             $UserModel->SQL->orWhere('Email', $this->Form->getFormValue('Email'));
             $Search = true;
         }
         if (is_numeric($UserSelect)) {
             $UserModel->SQL->orWhere('UserID', $UserSelect);
             $Search = true;
         }
         // Now do the search if we found some criteria.
         if ($Search) {
             $ExistingUsers = $UserModel->getWhere()->resultArray();
         }
         // Get the email and decide if we can safely find a match.
         $submittedEmail = $this->Form->getFormValue('Email');
         $canMatchEmail = strlen($submittedEmail) > 0 && !UserModel::noEmail();
         // Check to automatically link the user.
         if ($AutoConnect && count($ExistingUsers) > 0) {
             if ($IsPostBack && $this->Form->getFormValue('ConnectName')) {
                 $this->Form->setFormValue('Name', $this->Form->getFormValue('ConnectName'));
             }
             if ($canMatchEmail) {
                 // Check each existing user for an exact email match.
                 foreach ($ExistingUsers as $Row) {
                     if (strcasecmp($submittedEmail, $Row['Email']) === 0) {
                         // Add the UserID to the form, then get the unified user data set from it.
                         $UserID = $Row['UserID'];
                         $this->Form->setFormValue('UserID', $UserID);
                         $Data = $this->Form->formValues();
                         // User synchronization.
                         if (c('Garden.Registration.ConnectSynchronize', true)) {
                             // Don't overwrite a photo if the user has already uploaded one.
                             $Photo = val('Photo', $Row);
                             if (!val('Photo', $Data) || $Photo && !stringBeginsWith($Photo, 'http')) {
                                 unset($Data['Photo']);
                             }
                             // Update the user.
                             $UserModel->save($Data, ['NoConfirmEmail' => true, 'FixUnique' => true, 'SaveRoles' => $SaveRoles]);
                             $this->EventArguments['UserID'] = $UserID;
                             $this->fireEvent('AfterConnectSave');
                         }
                         // Always save the attributes because they may contain authorization information.
                         if ($Attributes = $this->Form->getFormValue('Attributes')) {
                             $UserModel->saveAttribute($UserID, $Attributes);
                         }
                         // Save the user authentication association.
                         $UserModel->saveAuthentication(['UserID' => $UserID, 'Provider' => $this->Form->getFormValue('Provider'), 'UniqueID' => $this->Form->getFormValue('UniqueID')]);
                         // Sign the user in.
                         Gdn::session()->start($UserID, true, (bool) $this->Form->getFormValue('RememberMe', true));
                         Gdn::userModel()->fireEvent('AfterSignIn');
                         $this->_setRedirect(Gdn::request()->get('display') === 'popup');
                         $this->render();
                         return;
                     }
                 }
             }
         }
         // Did not autoconnect!
         // Explore alternatives for a first-time connection.
         // This will be zero for a guest.
         $CurrentUserID = Gdn::session()->UserID;
         // Evaluate the existing users for matches.
         foreach ($ExistingUsers as $Index => $UserRow) {
             if ($EmailUnique && $canMatchEmail && $UserRow['Email'] == $submittedEmail) {
                 // An email match overrules any other options.
                 $EmailFound = $UserRow;
                 break;
             }
             // Detect a simple name match.
             if ($UserRow['Name'] == $this->Form->getFormValue('Name')) {
                 $NameFound = $UserRow;
             }
             // Detect if we have a match on the current user session.
             if ($CurrentUserID > 0 && $UserRow['UserID'] == $CurrentUserID) {
                 unset($ExistingUsers[$Index]);
                 $CurrentUserFound = true;
             }
         }
         // Handle special cases for what we matched on.
         if (isset($EmailFound)) {
             // The email address was found and can be the only user option.
             $ExistingUsers = [$UserRow];
             $this->setData('NoConnectName', true);
         } elseif (isset($CurrentUserFound)) {
             // If we're already logged in to Vanilla, assume that's an option we want.
             $ExistingUsers = array_merge(['UserID' => 'current', 'Name' => sprintf(t('%s (Current)'), Gdn::session()->User->Name)], $ExistingUsers);
         }
         // Pre-populate our ConnectName field with the passed name if we couldn't match it.
         if (!isset($NameFound) && !$IsPostBack) {
             $this->Form->setFormValue('ConnectName', $this->Form->getFormValue('Name'));
         }
         // Block connecting to an existing user if it's disallowed.
         if (!$allowConnect) {
             // Make sure photo of existing user doesn't show on the form.
             $this->Form->setFormValue("Photo", null);
             // Ignore existing users found.
             $ExistingUsers = [];
         }
         // Set our final answer on matched users.
         $this->setData('ExistingUsers', $ExistingUsers);
         // Validate our email address if we have one.
         if (UserModel::noEmail()) {
             $emailValid = true;
         } else {
             $emailValid = validateRequired($this->Form->getFormValue('Email'));
         }
         // Set some nice variable names for logic clarity.
         $noMatches = !is_array($ExistingUsers) || count($ExistingUsers) == 0;
         $didNotPickUser = !$UserSelect || $UserSelect == 'other';
         $haveName = $this->Form->getFormValue('Name');
         // Should we create a new user?
         if ($didNotPickUser && $haveName && $emailValid && $noMatches) {
             // Create the user.
             $User = $this->Form->formValues();
             $User['Password'] = randomString(16);
             // Required field.
             $User['HashMethod'] = 'Random';
             $User['Source'] = $this->Form->getFormValue('Provider');
             $User['SourceID'] = $this->Form->getFormValue('UniqueID');
             $User['Attributes'] = $this->Form->getFormValue('Attributes', null);
             $User['Email'] = $this->Form->getFormValue('ConnectEmail', $this->Form->getFormValue('Email', null));
             $User['Name'] = $this->Form->getFormValue('ConnectName', $this->Form->getFormValue('Name', null));
             $UserID = $UserModel->register($User, ['CheckCaptcha' => false, 'ValidateEmail' => false, 'NoConfirmEmail' => true, 'SaveRoles' => $SaveRolesRegister]);
             $User['UserID'] = $UserID;
             $this->EventArguments['UserID'] = $UserID;
             $this->fireEvent('AfterConnectSave');
             $this->Form->setValidationResults($UserModel->validationResults());
             // Save the association to the new user.
             if ($UserID) {
                 $UserModel->saveAuthentication(['UserID' => $UserID, 'Provider' => $this->Form->getFormValue('Provider'), 'UniqueID' => $this->Form->getFormValue('UniqueID')]);
                 $this->Form->setFormValue('UserID', $UserID);
                 $this->Form->setFormValue('UserSelect', false);
                 // Sign in as the new user.
                 Gdn::session()->start($UserID, true, (bool) $this->Form->getFormValue('RememberMe', true));
                 Gdn::userModel()->fireEvent('AfterSignIn');
                 // Send the welcome email.
                 if (c('Garden.Registration.SendConnectEmail', false)) {
                     try {
                         $providerName = $this->Form->getFormValue('ProviderName', $this->Form->getFormValue('Provider', 'Unknown'));
                         $UserModel->sendWelcomeEmail($UserID, '', 'Connect', ['ProviderName' => $providerName]);
                     } catch (Exception $Ex) {
                         // Do nothing if emailing doesn't work.
                     }
                 }
                 // Move along.
                 $this->_setRedirect(Gdn::request()->get('display') === 'popup');
             }
         }
     }
     // Finished our connection logic.
     // Save the user's choice.
     if ($IsPostBack) {
         $PasswordHash = new Gdn_PasswordHash();
         if (!$UserSelect || $UserSelect == 'other') {
             // The user entered a username. Validate it.
             $ConnectNameEntered = true;
             if ($this->Form->validateRule('ConnectName', 'ValidateRequired')) {
                 $ConnectName = $this->Form->getFormValue('ConnectName');
                 $User = false;
                 if (c('Garden.Registration.NameUnique')) {
                     // Check to see if there is already a user with the given name.
                     $User = $UserModel->getWhere(array('Name' => $ConnectName))->firstRow(DATASET_TYPE_ARRAY);
                 }
                 if (!$User) {
                     // Using a new username, so validate it.
                     $this->Form->validateRule('ConnectName', 'ValidateUsername');
                 }
             }
         } else {
             // The user selected an existing user.
             $ConnectNameEntered = false;
             if ($UserSelect == 'current') {
                 if (Gdn::session()->UserID == 0) {
                     // This should never happen, but a user could click submit on a stale form.
                     $this->Form->addError('@You were unexpectedly signed out.');
                 } else {
                     $UserSelect = Gdn::session()->UserID;
                 }
             }
             $User = $UserModel->getID($UserSelect, DATASET_TYPE_ARRAY);
         }
         // End user selection.
         if (isset($User) && $User) {
             // Make sure the user authenticates.
             if (!$User['UserID'] == Gdn::session()->UserID && $allowConnect) {
                 $hasPassword = $this->Form->validateRule('ConnectPassword', 'ValidateRequired', sprintf(t('ValidateRequired'), t('Password')));
                 if ($hasPassword) {
                     // Validate their password.
                     try {
                         $password = $this->Form->getFormValue('ConnectPassword');
                         $name = $this->Form->getFormValue('ConnectName');
                         if (!$PasswordHash->checkPassword($password, $User['Password'], $User['HashMethod'], $name)) {
                             if ($ConnectNameEntered) {
                                 $this->Form->addError('The username you entered has already been taken.');
                             } else {
                                 $this->Form->addError('The password you entered is incorrect.');
                             }
                         }
                     } catch (Gdn_UserException $Ex) {
                         $this->Form->addError($Ex);
                     }
                 }
             }
         } elseif ($this->Form->errorCount() == 0) {
             // The user doesn't exist so we need to add another user.
             $User = $this->Form->formValues();
             $User['Name'] = $User['ConnectName'];
             $User['Password'] = randomString(16);
             // Required field.
             $User['HashMethod'] = 'Random';
             $UserID = $UserModel->register($User, ['CheckCaptcha' => false, 'NoConfirmEmail' => true, 'SaveRoles' => $SaveRolesRegister]);
             $User['UserID'] = $UserID;
             $this->EventArguments['UserID'] = $UserID;
             $this->fireEvent('AfterConnectSave');
             $this->Form->setValidationResults($UserModel->validationResults());
             // Send the welcome email.
             if ($UserID && c('Garden.Registration.SendConnectEmail', false)) {
                 $providerName = $this->Form->getFormValue('ProviderName', $this->Form->getFormValue('Provider', 'Unknown'));
                 $UserModel->sendWelcomeEmail($UserID, '', 'Connect', ['ProviderName' => $providerName]);
             }
         }
         // Save the user authentication association.
         if ($this->Form->errorCount() == 0) {
             if (isset($User) && val('UserID', $User)) {
                 $UserModel->saveAuthentication(['UserID' => $User['UserID'], 'Provider' => $this->Form->getFormValue('Provider'), 'UniqueID' => $this->Form->getFormValue('UniqueID')]);
                 $this->Form->setFormValue('UserID', $User['UserID']);
             }
             // Sign the user in.
             Gdn::session()->start($this->Form->getFormValue('UserID'), true, (bool) $this->Form->getFormValue('RememberMe', true));
             Gdn::userModel()->fireEvent('AfterSignIn');
             // Move along.
             $this->_setRedirect(Gdn::request()->get('display') === 'popup');
         }
     }
     // End of user choice processing.
     $this->render();
 }
コード例 #11
0
ファイル: class.oauth2.php プロジェクト: vanilla/vanilla
 /**
  * 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);
 }
コード例 #12
0
 /**
  *
  *
  * @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');
 }