/** * Configuration of registration settings. */ public function Registration($RedirectUrl = '') { $this->Permission('Garden.Registration.Manage'); if (!C('Garden.Registration.Manage', TRUE)) { return Gdn::Dispatcher()->Dispatch('Default404'); } $this->AddSideMenu('dashboard/settings/registration'); $this->AddJsFile('registration.js'); $this->Title(T('Registration')); // Create a model to save configuration settings $Validation = new Gdn_Validation(); $ConfigurationModel = new Gdn_ConfigurationModel($Validation); $ConfigurationModel->SetField(array('Garden.Registration.Method' => 'Captcha', 'Garden.Registration.CaptchaPrivateKey', 'Garden.Registration.CaptchaPublicKey', 'Garden.Registration.InviteExpiration')); // Set the model on the forms. $this->Form->SetModel($ConfigurationModel); // Load roles with sign-in permission $RoleModel = new RoleModel(); $this->RoleData = $RoleModel->GetByPermission('Garden.SignIn.Allow'); // Get the currently selected default roles // $this->ExistingRoleData = Gdn::Config('Garden.Registration.DefaultRoles'); // if (is_array($this->ExistingRoleData) === FALSE) // $this->ExistingRoleData = array(); // Get currently selected InvitationOptions $this->ExistingRoleInvitations = Gdn::Config('Garden.Registration.InviteRoles'); if (is_array($this->ExistingRoleInvitations) === FALSE) { $this->ExistingRoleInvitations = array(); } // Get the currently selected Expiration Length $this->InviteExpiration = Gdn::Config('Garden.Registration.InviteExpiration', ''); // Registration methods. $this->RegistrationMethods = array('Captcha' => "New users fill out a simple form and are granted access immediately.", 'Approval' => "New users are reviewed and approved by an administrator (that's you!).", 'Invitation' => "Existing members send invitations to new members."); // Options for how many invitations a role can send out per month. $this->InvitationOptions = array('0' => T('None'), '1' => '1', '2' => '2', '5' => '5', '-1' => T('Unlimited')); // Options for when invitations should expire. $this->InviteExpirationOptions = array('-1 week' => T('1 week after being sent'), '-2 weeks' => T('2 weeks after being sent'), '-1 month' => T('1 month after being sent'), 'FALSE' => T('never')); if ($this->Form->AuthenticatedPostBack() === FALSE) { $this->Form->SetData($ConfigurationModel->Data); } else { // Define some validation rules for the fields being saved $ConfigurationModel->Validation->ApplyRule('Garden.Registration.Method', 'Required'); // if($this->Form->GetValue('Garden.Registration.Method') != 'Closed') // $ConfigurationModel->Validation->ApplyRule('Garden.Registration.DefaultRoles', 'RequiredArray'); // Define the Garden.Registration.RoleInvitations setting based on the postback values $InvitationRoleIDs = $this->Form->GetValue('InvitationRoleID'); $InvitationCounts = $this->Form->GetValue('InvitationCount'); $this->ExistingRoleInvitations = ArrayCombine($InvitationRoleIDs, $InvitationCounts); $ConfigurationModel->ForceSetting('Garden.Registration.InviteRoles', $this->ExistingRoleInvitations); // Save! if ($this->Form->Save() !== FALSE) { $this->StatusMessage = T("Your settings have been saved."); if ($RedirectUrl != '') { $this->RedirectUrl = $RedirectUrl; } } } $this->Render(); }
/** * Enabling and disabling categories from list. * * @since 2.0.0 * @access public */ public function ManageCategories() { // Check permission $this->Permission('Garden.Settings.Manage'); $this->AddSideMenu('vanilla/settings/managecategories'); $this->AddJsFile('categories.js'); $this->AddJsFile('js/library/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('js/library/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('js/library/nestedSortable.1.3.4/jquery.ui.nestedSortable.js'); $this->Title(T('Categories')); // Get category data $this->SetData('CategoryData', $this->CategoryModel->GetAll('TreeLeft'), TRUE); // Enable/Disable Categories if (Gdn::Session()->ValidateTransientKey(GetValue(1, $this->RequestArgs))) { $Toggle = GetValue(0, $this->RequestArgs, ''); if ($Toggle == 'enable') { SaveToConfig('Vanilla.Categories.Use', TRUE); } else { if ($Toggle == 'disable') { SaveToConfig('Vanilla.Categories.Use', FALSE); } } Redirect('vanilla/settings/managecategories'); } // 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(); }
/** * 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; 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(); try { $this->FireEvent('ConnectData'); } 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', GetValue('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 = GetValue('UserID', $Auth); // Check to synchronise roles upon connecting. if (($this->Data('Trusted') || C('Garden.SSO.SynchRoles')) && $this->Form->GetFormValue('Roles', NULL) !== NULL) { $SaveRoles = 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(); } $this->Form->SetFormValue('RoleID', $RoleIDs); } else { $SaveRoles = 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 = GetValue('Photo', $User); if (!GetValue('Photo', $Data) || $Photo && !StringBeginsWith($Photo, 'http')) { 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, 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'); // Get the existing users that match the name or email of the connection. $Search = FALSE; if ($this->Form->GetFormValue('Name') && $NameUnique) { $UserModel->SQL->OrWhere('Name', $this->Form->GetFormValue('Name')); $Search = TRUE; } if ($this->Form->GetFormValue('Email') && ($EmailUnique || $AutoConnect)) { $UserModel->SQL->OrWhere('Email', $this->Form->GetFormValue('Email')); $Search = TRUE; } if ($Search) { $ExistingUsers = $UserModel->GetWhere()->ResultArray(); } else { $ExistingUsers = array(); } // Check to automatically link the user. if ($AutoConnect && count($ExistingUsers) > 0) { foreach ($ExistingUsers as $Row) { if ($this->Form->GetFormValue('Email') == $Row['Email']) { $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 = GetValue('Photo', $Row); if (!GetValue('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, 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 ($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->InsertForBasic($User, FALSE, array('ValidateEmail' => FALSE, 'NoConfirmEmail' => TRUE, 'SaveRoles' => $SaveRoles)); $UserID = $UserModel->Register($User, array('CheckCaptcha' => FALSE, 'ValidateEmail' => FALSE, 'NoConfirmEmail' => TRUE, 'SaveRoles' => $SaveRoles)); $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); Gdn::Session()->Start($UserID, TRUE, 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(); $UserSelect = $this->Form->GetFormValue('UserSelect'); 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 uexpectidly 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' => $SaveRoles)); $User['UserID'] = $UserID; $this->Form->SetValidationResults($UserModel->ValidationResults()); if ($UserID) { // // Add the user to the default roles. // $UserModel->SaveRoles($UserID, C('Garden.Registration.DefaultRoles')); // 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) && GetValue('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, TRUE)); Gdn::UserModel()->FireEvent('AfterSignIn'); $this->_SetRedirect(TRUE); } } $this->Render(); }
/** * Create or update a comment. * * @since 2.0.0 * @access public * * @param int $DiscussionID Unique ID to add the comment to. If blank, this method will throw an error. */ public function Comment($DiscussionID = '') { // Get $DiscussionID from RequestArgs if valid if ($DiscussionID == '' && count($this->RequestArgs)) { if (is_numeric($this->RequestArgs[0])) { $DiscussionID = $this->RequestArgs[0]; } } // If invalid $DiscussionID, get from form. $this->Form->SetModel($this->CommentModel); $DiscussionID = is_numeric($DiscussionID) ? $DiscussionID : $this->Form->GetFormValue('DiscussionID', 0); // Set discussion data $this->DiscussionID = $DiscussionID; $this->Discussion = $Discussion = $this->DiscussionModel->GetID($DiscussionID); // Is this an embedded comment being posted to a discussion that doesn't exist yet? $vanilla_type = $this->Form->GetFormValue('vanilla_type', ''); $vanilla_url = $this->Form->GetFormValue('vanilla_url', ''); $vanilla_category_id = $this->Form->GetFormValue('vanilla_category_id', ''); $Attributes = array('ForeignUrl' => $vanilla_url); $vanilla_identifier = $this->Form->GetFormValue('vanilla_identifier', ''); // Only allow vanilla identifiers of 32 chars or less - md5 if larger if (strlen($vanilla_identifier) > 32) { $Attributes['vanilla_identifier'] = $vanilla_identifier; $vanilla_identifier = md5($vanilla_identifier); } if (!$Discussion && $vanilla_url != '' && $vanilla_identifier != '') { $Discussion = $Discussion = $this->DiscussionModel->GetForeignID($vanilla_identifier, $vanilla_type); if ($Discussion) { $this->DiscussionID = $DiscussionID = $Discussion->DiscussionID; $this->Form->SetValue('DiscussionID', $DiscussionID); } } // If so, create it! if (!$Discussion && $vanilla_url != '' && $vanilla_identifier != '') { // Add these values back to the form if they exist! $this->Form->AddHidden('vanilla_identifier', $vanilla_identifier); $this->Form->AddHidden('vanilla_type', $vanilla_type); $this->Form->AddHidden('vanilla_url', $vanilla_url); $this->Form->AddHidden('vanilla_category_id', $vanilla_category_id); $PageInfo = FetchPageInfo($vanilla_url); if (!($Title = $this->Form->GetFormValue('Name'))) { $Title = GetValue('Title', $PageInfo, ''); if ($Title == '') { $Title = T('Undefined discussion subject.'); } } $Description = GetValue('Description', $PageInfo, ''); $Images = GetValue('Images', $PageInfo, array()); $LinkText = T('EmbededDiscussionLinkText', 'Read the full story here'); if (!$Description && count($Images) == 0) { $Body = FormatString('<p><a href="{Url}">{LinkText}</a></p>', array('Url' => $vanilla_url, 'LinkText' => $LinkText)); } else { $Body = FormatString(' <div class="EmbeddedContent">{Image}<strong>{Title}</strong> <p>{Excerpt}</p> <p><a href="{Url}">{LinkText}</a></p> <div class="ClearFix"></div> </div>', array('Title' => $Title, 'Excerpt' => $Description, 'Image' => count($Images) > 0 ? Img(GetValue(0, $Images), array('class' => 'LeftAlign')) : '', 'Url' => $vanilla_url, 'LinkText' => $LinkText)); } if ($Body == '') { $Body = $vanilla_url; } if ($Body == '') { $Body = T('Undefined discussion body.'); } // Validate the CategoryID for inserting. $Category = CategoryModel::Categories($vanilla_category_id); if (!$Category) { $vanilla_category_id = C('Vanilla.Embed.DefaultCategoryID', 0); if ($vanilla_category_id <= 0) { // No default category defined, so grab the first non-root category and use that. $vanilla_category_id = $this->DiscussionModel->SQL->Select('CategoryID')->From('Category')->Where('CategoryID >', 0)->Get()->FirstRow()->CategoryID; // No categories in the db? default to 0 if (!$vanilla_category_id) { $vanilla_category_id = 0; } } } else { $vanilla_category_id = $Category['CategoryID']; } $EmbedUserID = C('Garden.Embed.UserID'); if ($EmbedUserID) { $EmbedUser = Gdn::UserModel()->GetID($EmbedUserID); } if (!$EmbedUserID || !$EmbedUser) { $EmbedUserID = Gdn::UserModel()->GetSystemUserID(); } $EmbeddedDiscussionData = array('InsertUserID' => $EmbedUserID, 'DateInserted' => Gdn_Format::ToDateTime(), 'DateUpdated' => Gdn_Format::ToDateTime(), 'CategoryID' => $vanilla_category_id, 'ForeignID' => $vanilla_identifier, 'Type' => $vanilla_type, 'Name' => $Title, 'Body' => $Body, 'Format' => 'Html', 'Attributes' => serialize($Attributes)); $this->EventArguments['Discussion'] = $EmbeddedDiscussionData; $this->FireEvent('BeforeEmbedDiscussion'); $DiscussionID = $this->DiscussionModel->SQL->Insert('Discussion', $EmbeddedDiscussionData); $ValidationResults = $this->DiscussionModel->ValidationResults(); if (count($ValidationResults) == 0 && $DiscussionID > 0) { $this->Form->AddHidden('DiscussionID', $DiscussionID); // Put this in the form so reposts won't cause new discussions. $this->Form->SetFormValue('DiscussionID', $DiscussionID); // Put this in the form values so it is used when saving comments. $this->SetJson('DiscussionID', $DiscussionID); $this->Discussion = $Discussion = $this->DiscussionModel->GetID($DiscussionID, DATASET_TYPE_OBJECT, array('Slave' => FALSE)); // Update the category discussion count if ($vanilla_category_id > 0) { $this->DiscussionModel->UpdateDiscussionCount($vanilla_category_id, $DiscussionID); } } } // If no discussion was found, error out if (!$Discussion) { $this->Form->AddError(T('Failed to find discussion for commenting.')); } $PermissionCategoryID = GetValue('PermissionCategoryID', $Discussion); // Setup head $this->AddJsFile('jquery.autosize.min.js'); $this->AddJsFile('post.js'); $this->AddJsFile('autosave.js'); // Setup comment model, $CommentID, $DraftID $Session = Gdn::Session(); $CommentID = isset($this->Comment) && property_exists($this->Comment, 'CommentID') ? $this->Comment->CommentID : ''; $DraftID = isset($this->Comment) && property_exists($this->Comment, 'DraftID') ? $this->Comment->DraftID : ''; $this->EventArguments['CommentID'] = $CommentID; $this->EventArguments['DraftID'] = $DraftID; // Determine whether we are editing $Editing = $CommentID > 0 || $DraftID > 0; $this->EventArguments['Editing'] = $Editing; // If closed, cancel & go to discussion if ($Discussion && $Discussion->Closed == 1 && !$Editing && !$Session->CheckPermission('Vanilla.Discussions.Close', TRUE, 'Category', $PermissionCategoryID)) { Redirect(DiscussionUrl($Discussion)); } // Add hidden IDs to form $this->Form->AddHidden('DiscussionID', $DiscussionID); $this->Form->AddHidden('CommentID', $CommentID); $this->Form->AddHidden('DraftID', $DraftID, TRUE); // Check permissions if ($Discussion && $Editing) { // Permisssion to edit if ($this->Comment->InsertUserID != $Session->UserID) { $this->Permission('Vanilla.Comments.Edit', TRUE, 'Category', $Discussion->PermissionCategoryID); } // Make sure that content can (still) be edited. $EditContentTimeout = C('Garden.EditContentTimeout', -1); $CanEdit = $EditContentTimeout == -1 || strtotime($this->Comment->DateInserted) + $EditContentTimeout > time(); if (!$CanEdit) { $this->Permission('Vanilla.Comments.Edit', TRUE, 'Category', $Discussion->PermissionCategoryID); } // Make sure only moderators can edit closed things if ($Discussion->Closed) { $this->Permission('Vanilla.Comments.Edit', TRUE, 'Category', $Discussion->PermissionCategoryID); } $this->Form->SetFormValue('CommentID', $CommentID); } else { if ($Discussion) { // Permission to add $this->Permission('Vanilla.Comments.Add', TRUE, 'Category', $Discussion->PermissionCategoryID); } } if (!$this->Form->IsPostBack()) { // Form was validly submitted if (isset($this->Comment)) { $this->Form->SetData((array) $this->Comment); } } else { // Save as a draft? $FormValues = $this->Form->FormValues(); $FormValues = $this->CommentModel->FilterForm($FormValues); if ($DraftID == 0) { $DraftID = $this->Form->GetFormValue('DraftID', 0); } $Type = GetIncomingValue('Type'); $Draft = $Type == 'Draft'; $this->EventArguments['Draft'] = $Draft; $Preview = $Type == 'Preview'; if ($Draft) { $DraftID = $this->DraftModel->Save($FormValues); $this->Form->AddHidden('DraftID', $DraftID, TRUE); $this->Form->SetValidationResults($this->DraftModel->ValidationResults()); } else { if (!$Preview) { // Fix an undefined title if we can. if ($this->Form->GetFormValue('Name') && GetValue('Name', $Discussion) == T('Undefined discussion subject.')) { $Set = array('Name' => $this->Form->GetFormValue('Name')); if (isset($vanilla_url) && $vanilla_url && strpos(GetValue('Body', $Discussion), T('Undefined discussion subject.')) !== FALSE) { $LinkText = T('EmbededDiscussionLinkText', 'Read the full story here'); $Set['Body'] = FormatString('<p><a href="{Url}">{LinkText}</a></p>', array('Url' => $vanilla_url, 'LinkText' => $LinkText)); } $this->DiscussionModel->SetField(GetValue('DiscussionID', $Discussion), $Set); } $Inserted = !$CommentID; $CommentID = $this->CommentModel->Save($FormValues); // The comment is now half-saved. if (is_numeric($CommentID) && $CommentID > 0) { if ($this->_DeliveryType == DELIVERY_TYPE_ALL) { $this->CommentModel->Save2($CommentID, $Inserted, TRUE, TRUE); } else { $this->JsonTarget('', Url("/vanilla/post/comment2.json?commentid={$CommentID}&inserted={$Inserted}"), 'Ajax'); } // $Discussion = $this->DiscussionModel->GetID($DiscussionID); $Comment = $this->CommentModel->GetID($CommentID, DATASET_TYPE_OBJECT, array('Slave' => FALSE)); $this->EventArguments['Discussion'] = $Discussion; $this->EventArguments['Comment'] = $Comment; $this->FireEvent('AfterCommentSave'); } elseif ($CommentID === SPAM || $CommentID === UNAPPROVED) { $this->StatusMessage = T('CommentRequiresApprovalStatus', 'Your comment will appear after it is approved.'); } $this->Form->SetValidationResults($this->CommentModel->ValidationResults()); if ($CommentID > 0 && $DraftID > 0) { $this->DraftModel->Delete($DraftID); } } } // Handle non-ajax requests first: if ($this->_DeliveryType == DELIVERY_TYPE_ALL) { if ($this->Form->ErrorCount() == 0) { // Make sure that this form knows what comment we are editing. if ($CommentID > 0) { $this->Form->AddHidden('CommentID', $CommentID); } // If the comment was not a draft if (!$Draft) { // Redirect to the new comment. if ($CommentID > 0) { Redirect("discussion/comment/{$CommentID}/#Comment_{$CommentID}"); } elseif ($CommentID == SPAM) { $this->SetData('DiscussionUrl', DiscussionUrl($Discussion)); $this->View = 'Spam'; } } elseif ($Preview) { // If this was a preview click, create a comment shell with the values for this comment $this->Comment = new stdClass(); $this->Comment->InsertUserID = $Session->User->UserID; $this->Comment->InsertName = $Session->User->Name; $this->Comment->InsertPhoto = $Session->User->Photo; $this->Comment->DateInserted = Gdn_Format::Date(); $this->Comment->Body = ArrayValue('Body', $FormValues, ''); $this->Comment->Format = GetValue('Format', $FormValues, C('Garden.InputFormatter')); $this->AddAsset('Content', $this->FetchView('preview')); } else { // If this was a draft save, notify the user about the save $this->InformMessage(sprintf(T('Draft saved at %s'), Gdn_Format::Date())); } } } else { // Handle ajax-based requests if ($this->Form->ErrorCount() > 0) { // Return the form errors $this->ErrorMessage($this->Form->Errors()); } else { // Make sure that the ajax request form knows about the newly created comment or draft id $this->SetJson('CommentID', $CommentID); $this->SetJson('DraftID', $DraftID); if ($Preview) { // If this was a preview click, create a comment shell with the values for this comment $this->Comment = new stdClass(); $this->Comment->InsertUserID = $Session->User->UserID; $this->Comment->InsertName = $Session->User->Name; $this->Comment->InsertPhoto = $Session->User->Photo; $this->Comment->DateInserted = Gdn_Format::Date(); $this->Comment->Body = ArrayValue('Body', $FormValues, ''); $this->View = 'preview'; } elseif (!$Draft) { // If the comment was not a draft // If Editing a comment if ($Editing) { // Just reload the comment in question $this->Offset = 1; $Comments = $this->CommentModel->GetIDData($CommentID, array('Slave' => FALSE)); $this->SetData('Comments', $Comments); $this->SetData('Discussion', $Discussion); // Load the discussion $this->ControllerName = 'discussion'; $this->View = 'comments'; // Also define the discussion url in case this request came from the post screen and needs to be redirected to the discussion $this->SetJson('DiscussionUrl', DiscussionUrl($this->Discussion) . '#Comment_' . $CommentID); } else { // If the comment model isn't sorted by DateInserted or CommentID then we can't do any fancy loading of comments. $OrderBy = GetValueR('0.0', $this->CommentModel->OrderBy()); // $Redirect = !in_array($OrderBy, array('c.DateInserted', 'c.CommentID')); // $DisplayNewCommentOnly = $this->Form->GetFormValue('DisplayNewCommentOnly'); // if (!$Redirect) { // // Otherwise load all new comments that the user hasn't seen yet // $LastCommentID = $this->Form->GetFormValue('LastCommentID'); // if (!is_numeric($LastCommentID)) // $LastCommentID = $CommentID - 1; // Failsafe back to this new comment if the lastcommentid was not defined properly // // // Don't reload the first comment if this new comment is the first one. // $this->Offset = $LastCommentID == 0 ? 1 : $this->CommentModel->GetOffset($LastCommentID); // // Do not load more than a single page of data... // $Limit = C('Vanilla.Comments.PerPage', 30); // // // Redirect if the new new comment isn't on the same page. // $Redirect |= !$DisplayNewCommentOnly && PageNumber($this->Offset, $Limit) != PageNumber($Discussion->CountComments - 1, $Limit); // } // if ($Redirect) { // // The user posted a comment on a page other than the last one, so just redirect to the last page. // $this->RedirectUrl = Gdn::Request()->Url("discussion/comment/$CommentID/#Comment_$CommentID", TRUE); // } else { // // Make sure to load all new comments since the page was last loaded by this user // if ($DisplayNewCommentOnly) $this->Offset = $this->CommentModel->GetOffset($CommentID); $Comments = $this->CommentModel->GetIDData($CommentID, array('Slave' => FALSE)); $this->SetData('Comments', $Comments); $this->SetData('NewComments', TRUE); $this->ClassName = 'DiscussionController'; $this->ControllerName = 'discussion'; $this->View = 'comments'; // } // Make sure to set the user's discussion watch records $CountComments = $this->CommentModel->GetCount($DiscussionID); $Limit = is_object($this->Data('Comments')) ? $this->Data('Comments')->NumRows() : $Discussion->CountComments; $Offset = $CountComments - $Limit; $this->CommentModel->SetWatch($this->Discussion, $Limit, $Offset, $CountComments); } } else { // If this was a draft save, notify the user about the save $this->InformMessage(sprintf(T('Draft saved at %s'), Gdn_Format::Date())); } // And update the draft count $UserModel = Gdn::UserModel(); $CountDrafts = $UserModel->GetAttribute($Session->UserID, 'CountDrafts', 0); $this->SetJson('MyDrafts', T('My Drafts')); $this->SetJson('CountDrafts', $CountDrafts); } } } // Include data for FireEvent if (property_exists($this, 'Discussion')) { $this->EventArguments['Discussion'] = $this->Discussion; } if (property_exists($this, 'Comment')) { $this->EventArguments['Comment'] = $this->Comment; } $this->FireEvent('BeforeCommentRender'); if ($this->DeliveryType() == DELIVERY_TYPE_DATA) { $Comment = $this->Data('Comments')->FirstRow(DATASET_TYPE_ARRAY); if ($Comment) { $Photo = $Comment['InsertPhoto']; if (strpos($Photo, '//') === FALSE) { $Photo = Gdn_Upload::Url(ChangeBasename($Photo, 'n%s')); } $Comment['InsertPhoto'] = $Photo; } $this->Data = array('Comment' => $Comment); $this->RenderData($this->Data); } else { require_once $this->FetchViewLocation('helper_functions', 'Discussion'); // Render default view. $this->Render(); } }
/** * Edit a user account. * * @since 2.0.0 * @access public * @param int $UserID Unique ID. */ public function Edit($UserID) { $this->Permission('Garden.Users.Edit'); // Page setup $this->AddJsFile('user.js'); $this->Title(T('Edit User')); $this->AddSideMenu('dashboard/user'); // Only admins can reassign roles $RoleModel = new RoleModel(); $AllRoles = $RoleModel->GetArray(); $RoleData = CheckPermission('Garden.Settings.Manage') ? $AllRoles : array(); $UserModel = new UserModel(); $User = $UserModel->GetID($UserID, DATASET_TYPE_ARRAY); // Determine if username can be edited $CanEditUsername = (bool) C("Garden.Profile.EditUsernames") || Gdn::Session()->CheckPermission('Garden.Users.Edit'); $this->SetData('_CanEditUsername', $CanEditUsername); // Determine if emails can be edited $CanEditEmail = Gdn::Session()->CheckPermission('Garden.Users.Edit'); $this->SetData('_CanEditEmail', $CanEditEmail); // Decide if they have ability to confirm users $Confirmed = (bool) GetValueR('Confirmed', $User); $CanConfirmEmail = UserModel::RequireConfirmEmail() && Gdn::Session()->CheckPermission('Garden.Users.Edit'); $this->SetData('_CanConfirmEmail', $CanConfirmEmail); $this->SetData('_EmailConfirmed', $Confirmed); $User['ConfirmEmail'] = (int) $Confirmed; // Determine whether user being edited is privileged (can escalate permissions) $UserModel = new UserModel(); $EditingPrivilegedUser = $UserModel->CheckPermission($User, 'Garden.Settings.Manage'); // Determine our password reset options // Anyone with user editing my force reset over email $this->ResetOptions = array(0 => T('Keep current password.'), 'Auto' => T('Force user to reset their password and send email notification.')); // Only admins may manually reset passwords for other admins if (CheckPermission('Garden.Settings.Manage') || !$EditingPrivilegedUser) { $this->ResetOptions['Manual'] = T('Manually set user password. No email notification.'); } // Set the model on the form. $this->Form->SetModel($UserModel); // Make sure the form knows which item we are editing. $this->Form->AddHidden('UserID', $UserID); try { $AllowEditing = TRUE; $this->EventArguments['AllowEditing'] =& $AllowEditing; $this->EventArguments['TargetUser'] =& $User; // These are all the 'effective' roles for this edit action. This list can // be trimmed down from the real list to allow subsets of roles to be // edited. $this->EventArguments['RoleData'] =& $RoleData; $UserRoleData = $UserModel->GetRoles($UserID)->ResultArray(); $RoleIDs = ConsolidateArrayValuesByKey($UserRoleData, 'RoleID'); $RoleNames = ConsolidateArrayValuesByKey($UserRoleData, 'Name'); $UserRoleData = ArrayCombine($RoleIDs, $RoleNames); $this->EventArguments['UserRoleData'] =& $UserRoleData; $this->FireEvent("BeforeUserEdit"); $this->SetData('AllowEditing', $AllowEditing); $this->Form->SetData($User); if ($this->Form->AuthenticatedPostBack()) { if (!$CanEditUsername) { $this->Form->SetFormValue("Name", $User['Name']); } // Allow mods to confirm/unconfirm emails $this->Form->RemoveFormValue('Confirmed'); $Confirmation = $this->Form->GetFormValue('ConfirmEmail', null); $Confirmation = !is_null($Confirmation) ? (bool) $Confirmation : null; if ($CanConfirmEmail && is_bool($Confirmation)) { $this->Form->SetFormValue('Confirmed', (int) $Confirmation); } $ResetPassword = $this->Form->GetValue('ResetPassword', FALSE); // If we're an admin or this isn't a privileged user, allow manual setting of password $AllowManualReset = CheckPermission('Garden.Settings.Manage') || !$EditingPrivilegedUser; if ($ResetPassword == 'Manual' && $AllowManualReset) { // If a new password was specified, add it to the form's collection $NewPassword = $this->Form->GetValue('NewPassword', ''); $this->Form->SetFormValue('Password', $NewPassword); } // Role changes // These are the new roles the editing user wishes to apply to the target // user, adjusted for his ability to affect those roles $RequestedRoles = $this->Form->GetFormValue('RoleID'); if (!is_array($RequestedRoles)) { $RequestedRoles = array(); } $RequestedRoles = array_flip($RequestedRoles); $UserNewRoles = array_intersect_key($RoleData, $RequestedRoles); // These roles will stay turned on regardless of the form submission contents // because the editing user does not have permission to modify them $ImmutableRoles = array_diff_key($AllRoles, $RoleData); $UserImmutableRoles = array_intersect_key($ImmutableRoles, $UserRoleData); // Apply immutable roles foreach ($UserImmutableRoles as $IMRoleID => $IMRoleName) { $UserNewRoles[$IMRoleID] = $IMRoleName; } // Put the data back into the forum object as if the user had submitted // this themselves $this->Form->SetFormValue('RoleID', array_keys($UserNewRoles)); if ($this->Form->Save(array('SaveRoles' => TRUE)) !== FALSE) { if ($this->Form->GetValue('ResetPassword', '') == 'Auto') { $UserModel->PasswordRequest($User['Email']); $UserModel->SetField($UserID, 'HashMethod', 'Reset'); } $this->InformMessage(T('Your changes have been saved.')); } $UserRoleData = $UserNewRoles; } } catch (Exception $Ex) { $this->Form->AddError($Ex); } $this->SetData('User', $User); $this->SetData('Roles', $RoleData); $this->SetData('UserRoles', $UserRoleData); $this->Render(); }
/** * @param Gdn_Controller $Sender * @param array $Args */ protected function Settings_AddEdit($Sender, $Args) { $client_id = $Sender->Request->Get('client_id'); Gdn::Locale()->SetTranslation('AuthenticationKey', 'Client ID'); Gdn::Locale()->SetTranslation('AssociationSecret', 'Secret'); Gdn::Locale()->SetTranslation('AuthenticateUrl', 'Authentication Url'); $Form = new Gdn_Form(); $Sender->Form = $Form; if ($Form->AuthenticatedPostBack()) { if ($Form->GetFormValue('Generate') || $Sender->Request->Post('Generate')) { $Form->SetFormValue('AuthenticationKey', mt_rand()); $Form->SetFormValue('AssociationSecret', md5(mt_rand())); $Sender->SetFormSaved(FALSE); } else { $Form->ValidateRule('AuthenticationKey', 'ValidateRequired'); // $Form->ValidateRule('AuthenticationKey', 'regex:`^[a-z0-9_-]+$`i', T('The client id must contain only letters, numbers and dashes.')); $Form->ValidateRule('AssociationSecret', 'ValidateRequired'); $Form->ValidateRule('AuthenticateUrl', 'ValidateRequired'); $Values = $Form->FormValues(); // $Values = ArrayTranslate($Values, array('Name', 'AuthenticationKey', 'URL', 'AssociationSecret', 'AuthenticateUrl', 'SignInUrl', 'RegisterUrl', 'SignOutUrl', 'IsDefault')); $Values['AuthenticationSchemeAlias'] = 'jsconnect'; $Values['AssociationHashMethod'] = 'md5'; $Values['Attributes'] = serialize(array('HashType' => $Form->GetFormValue('HashType'), 'TestMode' => $Form->GetFormValue('TestMode'), 'Trusted' => $Form->GetFormValue('Trusted', 0))); if ($Form->ErrorCount() == 0) { if ($client_id) { Gdn::SQL()->Put('UserAuthenticationProvider', $Values, array('AuthenticationKey' => $client_id)); } else { Gdn::SQL()->Options('Ignore', TRUE)->Insert('UserAuthenticationProvider', $Values); } $Sender->RedirectUrl = Url('/settings/jsconnect'); } } } else { if ($client_id) { $Provider = self::GetProvider($client_id); TouchValue('Trusted', $Provider, 1); } else { $Provider = array(); } $Form->SetData($Provider); } $Sender->SetData('Title', sprintf(T($client_id ? 'Edit %s' : 'Add %s'), T('Connection'))); $Sender->Render('Settings_AddEdit', '', 'plugins/jsconnect'); }
/** * Create or update a 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); // If closed, cancel & go to discussion if ($Discussion->Closed == 1) Redirect('discussion/'.$DiscussionID.'/'.Gdn_Format::Url($Discussion->Name)); // Setup head $this->AddJsFile('jquery.autogrow.js'); $this->AddJsFile('post.js'); $this->AddJsFile('autosave.js'); // Setup comment model, $CommentID, $DraftID $Session = Gdn::Session(); $CommentID = isset($this->Comment) && property_exists($this->Comment, 'CommentID') ? $this->Comment->CommentID : ''; $DraftID = isset($this->Comment) && property_exists($this->Comment, 'DraftID') ? $this->Comment->DraftID : ''; $this->EventArguments['CommentID'] = $CommentID; $this->EventArguments['DraftID'] = $DraftID; // Determine whether we are editing $Editing = $CommentID > 0 || $DraftID > 0; $this->EventArguments['Editing'] = $Editing; // Add hidden IDs to form $this->Form->AddHidden('DiscussionID', $DiscussionID); $this->Form->AddHidden('CommentID', $CommentID); $this->Form->AddHidden('DraftID', $DraftID, TRUE); // Check permissions if ($Editing) { // Permisssion to edit if ($this->Comment->InsertUserID != $Session->UserID) $this->Permission('Vanilla.Comments.Edit', TRUE, 'Category', $Discussion->PermissionCategoryID); // Make sure that content can (still) be edited. $EditContentTimeout = C('Garden.EditContentTimeout', -1); $CanEdit = $EditContentTimeout == -1 || strtotime($this->Comment->DateInserted) + $EditContentTimeout > time(); if (!$CanEdit) $this->Permission('Vanilla.Comments.Edit', TRUE, 'Category', $Discussion->PermissionCategoryID); } else { // Permission to add $this->Permission('Vanilla.Comments.Add', TRUE, 'Category', $Discussion->PermissionCategoryID); } if ($this->Form->AuthenticatedPostBack() === FALSE) { // Form was validly submitted if (isset($this->Comment)) $this->Form->SetData($this->Comment); } else { // Save as a draft? $FormValues = $this->Form->FormValues(); if ($DraftID == 0) $DraftID = $this->Form->GetFormValue('DraftID', 0); $Type = GetIncomingValue('Type'); $Draft = $Type == 'Draft'; $this->EventArguments['Draft'] = $Draft; $Preview = $Type == 'Preview'; if ($Draft) { $DraftID = $this->DraftModel->Save($FormValues); $this->Form->AddHidden('DraftID', $DraftID, TRUE); $this->Form->SetValidationResults($this->DraftModel->ValidationResults()); } else if (!$Preview) { $Inserted = !$CommentID; $CommentID = $this->CommentModel->Save($FormValues); // The comment is now half-saved. if (is_numeric($CommentID) && $CommentID > 0) { if ($this->_DeliveryType == DELIVERY_TYPE_ALL) { $this->CommentModel->Save2($CommentID, $Inserted, TRUE, TRUE); } else { $this->JsonTarget('', Url("/vanilla/post/comment2/$CommentID/$Inserted"), 'Ajax'); } // $Discussion = $this->DiscussionModel->GetID($DiscussionID); $Comment = $this->CommentModel->GetID($CommentID); $this->EventArguments['Discussion'] = $Discussion; $this->EventArguments['Comment'] = $Comment; $this->FireEvent('AfterCommentSave'); } elseif ($CommentID === SPAM) { $this->StatusMessage = T('Your post has been flagged for moderation.'); } $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', '/discussion/'.$DiscussionID.'/'.Gdn_Format::Url($Discussion->Name)); $this->View = 'Spam'; } } elseif ($Preview) { // If this was a preview click, create a comment shell with the values for this comment $this->Comment = new stdClass(); $this->Comment->InsertUserID = $Session->User->UserID; $this->Comment->InsertName = $Session->User->Name; $this->Comment->InsertPhoto = $Session->User->Photo; $this->Comment->DateInserted = Gdn_Format::Date(); $this->Comment->Body = ArrayValue('Body', $FormValues, ''); $this->AddAsset('Content', $this->FetchView('preview')); } else { // If this was a draft save, notify the user about the save $this->InformMessage(sprintf(T('Draft saved at %s'), Gdn_Format::Date())); } } } else { // Handle ajax-based requests if ($this->Form->ErrorCount() > 0) { // Return the form errors $this->ErrorMessage($this->Form->Errors()); } else { // Make sure that the ajax request form knows about the newly created comment or draft id $this->SetJson('CommentID', $CommentID); $this->SetJson('DraftID', $DraftID); if ($Preview) { // If this was a preview click, create a comment shell with the values for this comment $this->Comment = new stdClass(); $this->Comment->InsertUserID = $Session->User->UserID; $this->Comment->InsertName = $Session->User->Name; $this->Comment->InsertPhoto = $Session->User->Photo; $this->Comment->DateInserted = Gdn_Format::Date(); $this->Comment->Body = ArrayValue('Body', $FormValues, ''); $this->View = 'preview'; } elseif (!$Draft) { // If the comment was not a draft // If Editing a comment if ($Editing) { // Just reload the comment in question $this->Offset = 1; $this->SetData('CommentData', $this->CommentModel->GetIDData($CommentID), TRUE); // 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', Url('/discussion/'.$DiscussionID.'/'.Gdn_Format::Url($this->Discussion->Name).'/#Comment_'.$CommentID)); } else { // If the comment model isn't sorted by DateInserted or CommentID then we can't do any fancy loading of comments. $OrderBy = GetValueR('0.0', $this->CommentModel->OrderBy()); $Redirect = !in_array($OrderBy, array('c.DateInserted', 'c.CommentID')); $DisplayNewCommentOnly = $this->Form->GetFormValue('DisplayNewCommentOnly'); if (!$Redirect) { // Otherwise load all new comments that the user hasn't seen yet $LastCommentID = $this->Form->GetFormValue('LastCommentID'); if (!is_numeric($LastCommentID)) $LastCommentID = $CommentID - 1; // Failsafe back to this new comment if the lastcommentid was not defined properly // Don't reload the first comment if this new comment is the first one. $this->Offset = $LastCommentID == 0 ? 1 : $this->CommentModel->GetOffset($LastCommentID); // Do not load more than a single page of data... $Limit = C('Vanilla.Comments.PerPage', 50); // 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); $this->CommentData = NULL; } else { // Make sure to load all new comments since the page was last loaded by this user if ($DisplayNewCommentOnly) $this->SetData('CommentData', $this->CommentModel->GetIDData($CommentID), TRUE); else $this->SetData('CommentData', $this->CommentModel->GetNew($DiscussionID, $LastCommentID), TRUE); $this->SetData('NewComments', TRUE); $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->CommentData) ? $this->CommentData->NumRows() : $Discussion->CountComments; $Offset = $CountComments - $Limit; $this->CommentModel->SetWatch($this->Discussion, $Limit, $Offset, $CountComments); } } else { // If this was a draft save, notify the user about the save $this->InformMessage(sprintf(T('Draft saved at %s'), Gdn_Format::Date())); } // And update the draft count $UserModel = Gdn::UserModel(); $CountDrafts = $UserModel->GetAttribute($Session->UserID, 'CountDrafts', 0); $this->SetJson('MyDrafts', T('My Drafts')); $this->SetJson('CountDrafts', $CountDrafts); } } } // Include data for FireEvent if (property_exists($this,'Discussion')) $this->EventArguments['Discussion'] = $this->Discussion; if (property_exists($this,'Comment')) $this->EventArguments['Comment'] = $this->Comment; $this->FireEvent('BeforeCommentRender'); // Render default view $this->Render(); }
protected function _AddEdit($Sender, $PocketID = FALSE) { $Form = new Gdn_Form(); $PocketModel = new Gdn_Model('Pocket'); $Form->SetModel($PocketModel); $Sender->ConditionModule = new ConditionModule($Sender); $Sender->Form = $Form; if ($Form->AuthenticatedPostBack()) { // Save the pocket. if ($PocketID !== FALSE) { $Form->SetFormValue('PocketID', $PocketID); } // Convert the form data into a format digestable by the database. $Repeat = $Form->GetFormValue('RepeatType'); switch ($Repeat) { case Pocket::REPEAT_EVERY: $PocketModel->Validation->ApplyRule('EveryFrequency', 'Integer'); $PocketModel->Validation->ApplyRule('EveryBegin', 'Integer'); $Frequency = $Form->GetFormValue('EveryFrequency', 1); if (!$Frequency || !ValidateInteger($Frequency) || $Frequency < 1) { $Frequency = 1; } $Repeat .= ' ' . $Frequency; if ($Form->GetFormValue('EveryBegin', 1) > 1) { $Repeat .= ',' . $Form->GetFormValue('EveryBegin'); } break; case Pocket::REPEAT_INDEX: $PocketModel->Validation->AddRule('IntegerArray', 'function:ValidateIntegerArray'); $PocketModel->Validation->ApplyRule('Indexes', 'IntegerArray'); $Indexes = explode(',', $Form->GetFormValue('Indexes', '')); $Indexes = array_map('trim', $Indexes); $Repeat .= ' ' . implode(',', $Indexes); break; default: break; } $Form->SetFormValue('Repeat', $Repeat); $Form->SetFormValue('Sort', 0); $Form->SetFormValue('Format', 'Raw'); $Condition = Gdn_Condition::ToString($Sender->ConditionModule->Conditions(TRUE)); $Form->SetFormValue('Condition', $Condition); if ($Form->GetFormValue('Ad', 0)) { $Form->SetFormValue('Type', Pocket::TYPE_AD); } else { $Form->SetFormValue('Type', Pocket::TYPE_DEFAULT); } $Saved = $Form->Save(); if ($Saved) { $Sender->StatusMessage = T('Your changes have been saved.'); $Sender->RedirectUrl = Url('settings/pockets'); } } else { if ($PocketID !== FALSE) { // Load the pocket. $Pocket = $PocketModel->GetWhere(array('PocketID' => $PocketID))->FirstRow(DATASET_TYPE_ARRAY); if (!$Pocket) { return Gdn::Dispatcher()->Dispatch('Default404'); } // Convert some of the pocket data into a format digestable by the form. list($RepeatType, $RepeatFrequency) = Pocket::ParseRepeat($Pocket['Repeat']); $Pocket['RepeatType'] = $RepeatType; $Pocket['EveryFrequency'] = GetValue(0, $RepeatFrequency, 1); $Pocket['EveryBegin'] = GetValue(1, $RepeatFrequency, 1); $Pocket['Indexes'] = implode(',', $RepeatFrequency); $Pocket['Ad'] = $Pocket['Type'] == Pocket::TYPE_AD; $Sender->ConditionModule->Conditions(Gdn_Condition::FromString($Pocket['Condition'])); $Form->SetData($Pocket); } else { // Default the repeat. $Form->SetFormValue('RepeatType', Pocket::REPEAT_ONCE); } } $Sender->Form = $Form; $Sender->SetData('Locations', $this->Locations); $Sender->SetData('LocationsArray', $this->GetLocationsArray()); $Sender->SetData('Pages', array('' => '(' . T('All') . ')', 'activity' => 'activity', 'comments' => 'comments', 'dashboard' => 'dashboard', 'discussions' => 'discussions', 'inbox' => 'inbox', 'profile' => 'profile')); return $Sender->Render('AddEdit', '', 'plugins/Pockets'); }
/** * Edit a user account. * * @since 2.0.0 * @access public * @param int $UserID Unique ID. */ public function Edit($UserID) { $this->Permission('Garden.Users.Edit'); // Page setup $this->AddJsFile('user.js'); $this->Title(T('Edit User')); $this->AddSideMenu('dashboard/user'); // Determine if username can be edited $this->CanEditUsername = TRUE; $this->CanEditUsername = $this->CanEditUsername & Gdn::Config("Garden.Profile.EditUsernames"); $this->CanEditUsername = $this->CanEditUsername | Gdn::Session()->CheckPermission('Garden.Users.Edit'); $RoleModel = new RoleModel(); $AllRoles = $RoleModel->GetArray(); // By default, people with access here can freely assign all roles $this->RoleData = $AllRoles; $UserModel = new UserModel(); $this->User = $UserModel->GetID($UserID); // Set the model on the form. $this->Form->SetModel($UserModel); // Make sure the form knows which item we are editing. $this->Form->AddHidden('UserID', $UserID); try { $AllowEditing = TRUE; $this->EventArguments['AllowEditing'] =& $AllowEditing; $this->EventArguments['TargetUser'] =& $this->User; // These are all the 'effective' roles for this edit action. This list can // be trimmed down from the real list to allow subsets of roles to be // edited. $this->EventArguments['RoleData'] =& $this->RoleData; $UserRoleData = $UserModel->GetRoles($UserID)->ResultArray(); $RoleIDs = ConsolidateArrayValuesByKey($UserRoleData, 'RoleID'); $RoleNames = ConsolidateArrayValuesByKey($UserRoleData, 'Name'); $this->UserRoleData = ArrayCombine($RoleIDs, $RoleNames); $this->EventArguments['UserRoleData'] =& $this->UserRoleData; $this->FireEvent("BeforeUserEdit"); $this->SetData('AllowEditing', $AllowEditing); if (!$this->Form->AuthenticatedPostBack()) { $this->Form->SetData($this->User); } else { if (!$this->CanEditUsername) { $this->Form->SetFormValue("Name", $this->User->Name); } // If a new password was specified, add it to the form's collection $ResetPassword = $this->Form->GetValue('ResetPassword', FALSE); $NewPassword = $this->Form->GetValue('NewPassword', ''); if ($ResetPassword == 'Manual') { $this->Form->SetFormValue('Password', $NewPassword); } // Role changes // These are the new roles the editing user wishes to apply to the target // user, adjusted for his ability to affect those roles $RequestedRoles = $this->Form->GetFormValue('RoleID'); if (!is_array($RequestedRoles)) { $RequestedRoles = array(); } $RequestedRoles = array_flip($RequestedRoles); $UserNewRoles = array_intersect_key($this->RoleData, $RequestedRoles); // These roles will stay turned on regardless of the form submission contents // because the editing user does not have permission to modify them $ImmutableRoles = array_diff_key($AllRoles, $this->RoleData); $UserImmutableRoles = array_intersect_key($ImmutableRoles, $this->UserRoleData); // Apply immutable roles foreach ($UserImmutableRoles as $IMRoleID => $IMRoleName) { $UserNewRoles[$IMRoleID] = $IMRoleName; } // Put the data back into the forum object as if the user had submitted // this themselves $this->Form->SetFormValue('RoleID', array_keys($UserNewRoles)); if ($this->Form->Save(array('SaveRoles' => TRUE)) !== FALSE) { if ($this->Form->GetValue('ResetPassword', '') == 'Auto') { $UserModel->PasswordRequest($this->User->Email); $UserModel->SetField($UserID, 'HashMethod', 'Reset'); } $this->InformMessage(T('Your changes have been saved.')); } $this->UserRoleData = $UserNewRoles; } } catch (Exception $Ex) { $this->Form->AddError($Ex); } $this->Render(); }
/** * 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 $this->Preferences = array('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.'))); // 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 = GetValue('0', $NameParts); $SubName = GetValue('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] = GetValue($Pref, $MetaPrefs, FALSE); } else { $CurrentPrefs[$Pref] = GetValue($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]); } 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(); }