/// <summary> /// On btnVote click event handler. /// </summary> protected void btnVote_OnClick(object sender, EventArgs e) { // Check banned ip if (!BannedIPInfoProvider.IsAllowed(SiteContext.CurrentSiteName, BanControlEnum.AllNonComplete)) { lblInfo.CssClass = "ErrorMessage"; lblInfo.Text = GetString("General.BannedIP"); return; } if (pi != null) { // Indicates whether user voted or not bool voted = false; // Indicates wheter all forms of all open-ended answers can be saved bool formsAreValid = true; List <int> selectedAnswers = new List <int>(); // List of poll answers (in case of multiple answers) for activity logging StringBuilder pollAnswerIDs = new StringBuilder(); // Check if user has already voted if ((CheckVoted) && (PollInfoProvider.HasVoted(pi.PollID))) { errMessage = GetString("Polls.UserHasVoted"); voted = true; } else if (isOpened) { // Get poll answers DataSet ds = Answers; if (!DataHelper.DataSourceIsEmpty(ds)) { DataRowCollection rows = ds.Tables[0].Rows; CMSCheckBox chkItem = null; CMSRadioButton radItem = null; bool selected = false; PollAnswerInfo pai = null; BizForm bizItem = null; foreach (DataRow row in rows) { pai = new PollAnswerInfo(row); if ((pai != null) && (pai.AnswerEnabled)) { selected = false; // Find specific controls and update pollanswerinfo if controls are checked if (pi.PollAllowMultipleAnswers) { // Find checkbox chkItem = (CMSCheckBox)pnlAnswer.FindControl("chk" + pai.AnswerID); if (chkItem != null) { selected = chkItem.Checked; } } else { // Find radiobutton radItem = (CMSRadioButton)pnlAnswer.FindControl("rad" + pai.AnswerID); if (radItem != null) { selected = radItem.Checked; } } if ((selected) && (pai.AnswerCount < Int32.MaxValue)) { bool canBeSaved = false; bizItem = (BizForm)pnlAnswer.FindControl("frm" + pai.AnswerID); if (bizItem == null) { canBeSaved = true; } else if (bizItem != null) { // Validate form data canBeSaved = bizItem.ValidateData(); } if (canBeSaved) { selectedAnswers.Add(pai.AnswerID); } else { formsAreValid = false; } } } } if (formsAreValid) { if (selectedAnswers.Count > 0) { foreach (int aid in selectedAnswers) { // Set the vote PollAnswerInfoProvider.Vote(aid); // Save the bizform data bizItem = (BizForm)pnlAnswer.FindControl("frm" + aid); if (bizItem != null) { if (bizItem != null) { bizItem.SaveData(null, false); } } // Save all selected answers (for activity logging) pollAnswerIDs.Append(aid); pollAnswerIDs.Append(ActivityPollVoting.POLL_ANSWER_SEPARATOR); } voted = true; } else { // Set error message if no answer selected lblInfo.CssClass = "ErrorMessage"; lblInfo.Text = GetString("Polls.DidNotVoted"); } } if (voted) { LogActivity(pi, pollAnswerIDs.ToString()); } if ((CheckVoted) && (voted)) { // Create cookie about user's voting PollInfoProvider.SetVoted(pi.PollID); } } } if (voted) { // Clear cache if it's used Answers = null; // Reload poll control ReloadData(true); if (OnAfterVoted != null) { OnAfterVoted(this, EventArgs.Empty); } } } }
/// <summary> /// UniGrid action buttons event handler. /// </summary> protected void gridDocs_OnAction(string actionName, object actionArgument) { switch (actionName.ToLowerCSafe()) { // Edit document case "edit": // Check group's permission to edit document if allowed if (CheckGroupPermission("editpages")) { editDoc.NodeID = ValidationHelper.GetInteger(actionArgument, 0); editDoc.Action = "edit"; editDoc.CheckPermissions = CheckPermissions; editDoc.AllowDelete = AllowDelete && CheckGroupPermission("deletepages"); pnlEdit.Visible = true; pnlList.Visible = false; } break; // Delete document case "delete": // Check banned IP if (!BannedIPInfoProvider.IsAllowed(SiteContext.CurrentSiteName, BanControlEnum.AllNonComplete)) { AddAlert(GetString("general.bannedip")); return; } TreeProvider tree = new TreeProvider(MembershipContext.AuthenticatedUser); // Delete specified node int documentId = ValidationHelper.GetInteger(actionArgument, 0); TreeNode node = DocumentHelper.GetDocument(documentId, tree); if (node != null) { // Check user's permission to delete document if allowed bool hasUserDeletePermission = !CheckPermissions || IsUserAuthorizedToDeleteDocument(node); // Check group's permission to delete document if allowed hasUserDeletePermission &= CheckGroupPermission("deletepages"); if (hasUserDeletePermission) { DocumentHelper.DeleteDocument(node, tree); if (LogActivity) { Activity activity = new ActivityUserContributionDelete(node, node.GetDocumentName(), AnalyticsContext.ActivityEnvironmentVariables); activity.Log(); } // Fire OnAfterDelete RaiseOnAfterDelete(); ReloadData(); } // Access denied - not authorized to delete the document else { AddAlert(String.Format(GetString("cmsdesk.notauthorizedtodeletedocument"), node.NodeAliasPath)); } } break; } }
protected void btnOk_Click(object sender, EventArgs e) { // Let the parent control now new message is being saved if (OnBeforeMessageSaved != null) { OnBeforeMessageSaved(); } // Check if message board is opened if (!IsBoardOpen()) { return; } // Check banned IP if (!BannedIPInfoProvider.IsAllowed(SiteContext.CurrentSiteName, BanControlEnum.AllNonComplete)) { ShowError(GetString("General.BannedIP")); return; } // Validate form string errorMessage = ValidateForm(); if (errorMessage == String.Empty) { // Check flooding when message being inserted through the LiveSite if (CheckFloodProtection && IsLiveSite && FloodProtectionHelper.CheckFlooding(SiteContext.CurrentSiteName, MembershipContext.AuthenticatedUser)) { ShowError(GetString("General.FloodProtection")); return; } var currentUser = MembershipContext.AuthenticatedUser; BoardMessageInfo message; if (MessageID > 0) { // Get message info message = BoardMessageInfoProvider.GetBoardMessageInfo(MessageID); MessageBoardID = message.MessageBoardID; } else { // Create new info message = new BoardMessageInfo(); // User IP address message.MessageUserInfo.IPAddress = RequestContext.UserHostAddress; // User agent message.MessageUserInfo.Agent = Request.UserAgent; } // Setup message info message.MessageEmail = txtEmail.Text.Trim(); message.MessageText = txtMessage.Text.Trim(); // Handle message URL string url = txtURL.Text.Trim(); if (!String.IsNullOrEmpty(url)) { string protocol = URLHelper.GetProtocol(url); if (String.IsNullOrEmpty(protocol)) { url = "http://" + url; } } message.MessageURL = TextHelper.LimitLength(url, txtURL.MaxLength); message.MessageURL = message.MessageURL.ToLowerCSafe().Replace("javascript", "_javascript"); message.MessageUserName = TextHelper.LimitLength(txtUserName.Text.Trim(), txtUserName.MaxLength); if ((message.MessageID <= 0) && (!currentUser.IsPublic())) { message.MessageUserID = currentUser.UserID; if (!plcUserName.Visible) { message.MessageUserName = GetDefaultUserName(); } } message.MessageIsSpam = ValidationHelper.GetBoolean(chkSpam.Checked, false); if (BoardProperties.EnableContentRating && (ratingControl != null) && (ratingControl.GetCurrentRating() > 0)) { message.MessageRatingValue = ratingControl.CurrentRating; // Update document rating, remember rating in cookie TreeProvider.RememberRating(DocumentContext.CurrentDocument); } BoardInfo boardInfo; // If there is message board if (MessageBoardID > 0) { // Load message board boardInfo = Board; } else { // Create new message board according to webpart properties boardInfo = new BoardInfo(BoardProperties); BoardInfoProvider.SetBoardInfo(boardInfo); // Update information on current message board MessageBoardID = boardInfo.BoardID; // Set board-role relationship BoardRoleInfoProvider.SetBoardRoles(MessageBoardID, BoardProperties.BoardRoles); // Set moderators BoardModeratorInfoProvider.SetBoardModerators(MessageBoardID, BoardProperties.BoardModerators); } if (boardInfo != null) { if (BoardInfoProvider.IsUserAuthorizedToAddMessages(boardInfo)) { // If the very new message is inserted if (MessageID == 0) { // If creating message set inserted to now and assign to board message.MessageInserted = DateTime.Now; message.MessageBoardID = MessageBoardID; // Handle auto approve action bool isAuthorized = BoardInfoProvider.IsUserAuthorizedToManageMessages(boardInfo); if (isAuthorized) { message.MessageApprovedByUserID = currentUser.UserID; message.MessageApproved = true; } else { // Is board moderated ? message.MessageApprovedByUserID = 0; message.MessageApproved = !boardInfo.BoardModerated; } } else { if (chkApproved.Checked) { // Set current user as approver message.MessageApproved = true; message.MessageApprovedByUserID = currentUser.UserID; } else { message.MessageApproved = false; message.MessageApprovedByUserID = 0; } } if (!AdvancedMode) { if (!BadWordInfoProvider.CanUseBadWords(MembershipContext.AuthenticatedUser, SiteContext.CurrentSiteName)) { // Columns to check Dictionary <string, int> collumns = new Dictionary <string, int>(); collumns.Add("MessageText", 0); collumns.Add("MessageUserName", 250); // Perform bad words check bool validateUserName = plcUserName.Visible; errorMessage = BadWordsHelper.CheckBadWords(message, collumns, "MessageApproved", "MessageApprovedByUserID", message.MessageText, currentUser.UserID, () => ValidateMessage(message, validateUserName)); // Additionally check empty fields if (errorMessage == string.Empty) { if (!ValidateMessage(message, validateUserName)) { errorMessage = GetString("board.messageedit.emptybadword"); } } } } // Subscribe this user to message board if (chkSubscribe.Checked) { string email = message.MessageEmail; // Check for duplicate e-mails DataSet ds = BoardSubscriptionInfoProvider.GetSubscriptions("((SubscriptionApproved = 1) OR (SubscriptionApproved IS NULL)) AND SubscriptionBoardID=" + MessageBoardID + " AND SubscriptionEmail='" + SqlHelper.GetSafeQueryString(email, false) + "'", null); if (DataHelper.DataSourceIsEmpty(ds)) { BoardSubscriptionInfo bsi = new BoardSubscriptionInfo(); bsi.SubscriptionBoardID = MessageBoardID; bsi.SubscriptionEmail = email; if (!currentUser.IsPublic()) { bsi.SubscriptionUserID = currentUser.UserID; } BoardSubscriptionInfoProvider.Subscribe(bsi, DateTime.Now, true, true); ClearForm(); if (bsi.SubscriptionApproved) { ShowConfirmation(GetString("board.subscription.beensubscribed")); Service <ICurrentContactMergeService> .Entry().UpdateCurrentContactEmail(bsi.SubscriptionEmail, MembershipContext.AuthenticatedUser); LogSubscribingActivity(bsi, boardInfo); } else { string confirmation = GetString("general.subscribed.doubleoptin"); int optInInterval = BoardInfoProvider.DoubleOptInInterval(SiteContext.CurrentSiteName); if (optInInterval > 0) { confirmation += "<br />" + String.Format(GetString("general.subscription_timeintervalwarning"), optInInterval); } ShowConfirmation(confirmation); } } else { errorMessage = GetString("board.subscription.emailexists"); } } if (errorMessage == "") { try { // Save message info BoardMessageInfoProvider.SetBoardMessageInfo(message); Service <ICurrentContactMergeService> .Entry().UpdateCurrentContactEmail(message.MessageEmail, MembershipContext.AuthenticatedUser); LogCommentActivity(message, boardInfo); if (BoardProperties.EnableContentRating && (ratingControl != null) && (ratingControl.GetCurrentRating() > 0)) { LogRatingActivity(ratingControl.CurrentRating); } // If the message is not approved let the user know message is waiting for approval if (message.MessageApproved == false) { ShowInformation(GetString("board.messageedit.waitingapproval")); } // Rise after message saved event if (OnAfterMessageSaved != null) { OnAfterMessageSaved(message); } // Hide message form if user has rated and empty rating is not allowed if (BoardProperties.CheckIfUserRated) { if (!BoardProperties.AllowEmptyRating && TreeProvider.HasRated(DocumentContext.CurrentDocument)) { pnlMessageEdit.Visible = false; lblAlreadyrated.Visible = true; } else { // Hide rating form if user has rated if (BoardProperties.EnableContentRating && (ratingControl != null) && ratingControl.GetCurrentRating() > 0) { plcRating.Visible = false; } } } // Clear form content ClearForm(); } catch (Exception ex) { errorMessage = ex.Message; } } } else if (String.IsNullOrEmpty(errorMessage)) { errorMessage = ResHelper.GetString("general.actiondenied"); } } } if (!String.IsNullOrEmpty(errorMessage)) { ShowError(errorMessage); } }
protected void btnSendMessage_Click(object sender, EventArgs e) { // This is because of ASP.NET default behaviour // The first empty line was trimmed after each postback if (BBEditor.Text.StartsWith("\n")) { BBEditor.Text = "\n" + BBEditor.Text; } // Flood protection if (!FloodProtectionHelper.CheckFlooding(CMSContext.CurrentSiteName, CMSContext.CurrentUser)) { CurrentUserInfo currentUser = CMSContext.CurrentUser; // Check banned IP if (BannedIPInfoProvider.IsAllowed(CMSContext.CurrentSiteName, BanControlEnum.AllNonComplete)) { int recipientId = ucMessageUserSelector.Visible ? ucMessageUserSelector.SelectedUserID : ValidationHelper.GetInteger(hdnUserId.Value, 0); string message = string.Empty; string nickName = HTMLHelper.HTMLEncode(txtFrom.Text.Trim()); if (!ValidateBody(DiscussionMacroHelper.RemoveTags(ucBBEditor.Text))) { message = GetString("SendMessage.EmptyBody"); } // Check sender nick name if anonymous if (isAnonymousUser && (nickName == string.Empty)) { message = GetString("SendMesage.NoNickName"); } UserInfo recipient = null; // Check recipient if (recipientId == 0) { if (string.IsNullOrEmpty(ucMessageUserSelector.UserNameTextBox.Text.Trim())) { message = GetString("SendMesage.NoRecipient"); } else { message = GetString("SendMesage.UserDoesntExists"); } } else { recipient = UserInfoProvider.GetUserInfo(recipientId); // Normal users can't send message to user from other site except for global admin if (!recipient.IsInSite(CMSContext.CurrentSiteName) && !currentUser.IsGlobalAdministrator) { message = GetString("SendMesage.UserDoesntExists"); } int defRecipientId = ValidationHelper.GetInteger(DefaultRecipient, 0); // If default recipient selected and is same as message recipient, skip check on hidden users if (recipient.UserID != defRecipientId) { // Hide hidden, disabled and not approved user for all users except for global admins and public user for all users if ((IsLiveSite && (!recipient.Enabled || recipient.UserIsHidden || recipient.UserSettings.UserWaitingForApproval) && !currentUser.IsGlobalAdministrator) || (recipient.UserName.ToLower() == "public")) { message = GetString("SendMesage.UserDoesntExists"); } } } if (message == string.Empty) { // Send message try { // Check if current user is in recipient's ignore list bool isIgnored = IgnoreListInfoProvider.IsInIgnoreList(recipientId, currentUser.UserID); Message = new MessageInfo(); Message.MessageBody = ucBBEditor.Text; string subject = (txtSubject.Text.Trim() == string.Empty) ? GetString("Messaging.NoSubject") : txtSubject.Text.Trim(); Message.MessageSubject = TextHelper.LimitLength(subject, 200); Message.MessageRecipientUserID = recipientId; Message.MessageRecipientNickName = TextHelper.LimitLength(Functions.GetFormattedUserName(recipient.UserName, recipient.FullName, recipient.UserNickName, IsLiveSite), 200); Message.MessageSent = DateTime.Now; // Anonymous user if (isAnonymousUser) { Message.MessageSenderNickName = TextHelper.LimitLength(nickName, 200); Message.MessageSenderDeleted = true; } else { Message.MessageSenderUserID = currentUser.UserID; Message.MessageSenderNickName = TextHelper.LimitLength(Functions.GetFormattedUserName(currentUser.UserName, currentUser.FullName, currentUser.UserNickName, IsLiveSite), 200); // If the user is ignored, delete message automatically if (isIgnored) { Message.MessageRecipientDeleted = true; } } string error = string.Empty; // Check bad words if (!BadWordInfoProvider.CanUseBadWords(currentUser, CMSContext.CurrentSiteName)) { // Prepare columns to check Dictionary <string, int> columns = new Dictionary <string, int>(); columns.Add("MessageSubject", 200); columns.Add("MessageBody", 0); columns.Add("MessageSenderNickName", 200); columns.Add("MessageRecipientNickName", 200); // Perform bad word check error = BadWordsHelper.CheckBadWords(Message, columns, currentUser.UserID); } if (error != string.Empty) { lblSendError.Visible = true; lblSendError.Text = error; } else { // Check message subject, if empty set no subject text if (Message.MessageSubject.Trim() == string.Empty) { Message.MessageSubject = GetString("Messaging.NoSubject"); } // Whole text has been removed if (!ValidateBody(Message.MessageBody)) { lblSendError.Visible = true; lblSendError.Text = GetString("SendMessage.EmptyBodyBadWords"); } else { // Save the message MessageInfoProvider.SetMessageInfo(Message); // Send notification email, if not ignored if (!isIgnored) { MessageInfoProvider.SendNotificationEmail(Message, recipient, currentUser, CMSContext.CurrentSiteName); } lblSendInfo.Visible = true; lblSendInfo.Text = GetString("SendMesage.MessageSent"); MessageId = 0; ucMessageUserSelector.SelectedUserID = 0; } } } catch (Exception ex) { lblSendError.Visible = true; lblSendError.Text = ex.Message; ErrorMessage = ex.Message; } } // Error in the form else { lblSendError.Visible = true; lblSendError.Text = message; ErrorMessage = message; } } else { lblSendError.Visible = true; lblSendError.Text = GetString("General.BannedIP"); } } else { lblSendError.Visible = true; lblSendError.Text = GetString("General.FloodProtection"); } // External event if (SendButtonClick != null) { SendButtonClick(sender, e); } }
/// <summary> /// OK click handler (Proceed registration). /// </summary> private void btnRegister_Click(object sender, EventArgs e) { if ((PageManager.ViewMode == ViewModeEnum.Design) || (HideOnCurrentPage) || (!IsVisible)) { // Do not process return; } // Ban IP addresses which are blocked for registration if (!BannedIPInfoProvider.IsAllowed(CurrentSiteName, BanControlEnum.Registration)) { ShowError(GetString("banip.ipisbannedregistration")); return; } // Check if captcha is required and verify captcha text if (DisplayCaptcha && !captchaElem.IsValid()) { // Display error message if captcha text is not valid ShowError(GetString("Webparts_Membership_RegistrationForm.captchaError")); return; } string userName = String.Empty; string nickName = String.Empty; string emailValue = String.Empty; // Check duplicate user // 1. Find appropriate control and get its value (i.e. user name) // 2. Try to find user info FormEngineUserControl txtUserName = formUser.FieldControls["UserName"]; if (txtUserName != null) { userName = ValidationHelper.GetString(txtUserName.Value, String.Empty); } FormEngineUserControl txtEmail = formUser.FieldControls["Email"]; if (txtEmail != null) { emailValue = ValidationHelper.GetString(txtEmail.Value, String.Empty); } // If user name and e-mail aren't filled stop processing and display error. if (string.IsNullOrEmpty(userName)) { userName = emailValue; if (String.IsNullOrEmpty(emailValue)) { formUser.StopProcessing = true; formUser.DisplayErrorLabel("Email", GetString("customregistrationform.usernameandemail")); return; } // Set username after data retrieval in case the username control is hidden (visible field hidden in custom layout) formUser.OnBeforeSave += (s, args) => formUser.Data.SetValue("UserName", userName); } FormEngineUserControl txtNickName = formUser.FieldControls["UserNickName"]; if (txtNickName != null) { nickName = ValidationHelper.GetString(txtNickName.Value, String.Empty); } // Test if "global" or "site" user exists. SiteInfo si = SiteContext.CurrentSite; UserInfo siteui = UserInfoProvider.GetUserInfo(UserInfoProvider.EnsureSitePrefixUserName(userName, si)); if ((UserInfoProvider.GetUserInfo(userName) != null) || (siteui != null)) { ShowError(GetString("Webparts_Membership_RegistrationForm.UserAlreadyExists").Replace("%%name%%", HTMLHelper.HTMLEncode(Functions.GetFormattedUserName(userName, true)))); return; } // Check for reserved user names like administrator, sysadmin, ... if (UserInfoProvider.NameIsReserved(CurrentSiteName, userName)) { ShowError(GetString("Webparts_Membership_RegistrationForm.UserNameReserved").Replace("%%name%%", HTMLHelper.HTMLEncode(Functions.GetFormattedUserName(userName, true)))); return; } if (UserInfoProvider.NameIsReserved(CurrentSiteName, nickName)) { ShowError(GetString("Webparts_Membership_RegistrationForm.UserNameReserved").Replace("%%name%%", HTMLHelper.HTMLEncode(nickName))); return; } // Check limitations for site members if (!UserInfoProvider.LicenseVersionCheck(RequestContext.CurrentDomain, FeatureEnum.SiteMembers, ObjectActionEnum.Insert, false)) { ShowError(GetString("License.MaxItemsReachedSiteMember")); return; } // Check whether email is unique if it is required if (!UserInfoProvider.IsEmailUnique(emailValue, SiteList, 0)) { formUser.DisplayErrorLabel("Email", GetString("UserInfo.EmailAlreadyExist")); return; } formUser.SaveData(null, String.IsNullOrEmpty(DisplayMessage.Trim())); }
/// <summary> /// OK click handler (Proceed registration). /// </summary> protected void btnOK_Click(object sender, EventArgs e) { if (PortalContext.IsDesignMode(PortalContext.ViewMode) || (HideOnCurrentPage) || (!IsVisible)) { // Do not process } else { String siteName = SiteContext.CurrentSiteName; #region "Banned IPs" // Ban IP addresses which are blocked for registration if (!BannedIPInfoProvider.IsAllowed(siteName, BanControlEnum.Registration)) { lblError.Visible = true; lblError.Text = GetString("banip.ipisbannedregistration"); return; } #endregion #region "Check Email & password" string[] siteList = { siteName }; // If AssignToSites field set if (!String.IsNullOrEmpty(AssignToSites)) { siteList = AssignToSites.Split(';'); } // Check whether user with same email does not exist UserInfo ui = UserInfoProvider.GetUserInfo(txtEmail.Text); SiteInfo si = SiteContext.CurrentSite; UserInfo siteui = UserInfoProvider.GetUserInfo(UserInfoProvider.EnsureSitePrefixUserName(txtEmail.Text, si)); if ((ui != null) || (siteui != null)) { lblError.Visible = true; lblError.Text = GetString("Webparts_Membership_RegistrationForm.UserAlreadyExists").Replace("%%name%%", HTMLHelper.HTMLEncode(txtEmail.Text)); return; } // Check whether password is same if (passStrength.Text != txtConfirmPassword.Text) { lblError.Visible = true; lblError.Text = GetString("Webparts_Membership_RegistrationForm.PassworDoNotMatch"); return; } if ((PasswordMinLength > 0) && (passStrength.Text.Length < PasswordMinLength)) { lblError.Visible = true; lblError.Text = String.Format(GetString("Webparts_Membership_RegistrationForm.PasswordMinLength"), PasswordMinLength.ToString()); return; } if (!passStrength.IsValid()) { lblError.Visible = true; lblError.Text = AuthenticationHelper.GetPolicyViolationMessage(SiteContext.CurrentSiteName); return; } if (!ValidationHelper.IsEmail(txtEmail.Text.ToLowerCSafe())) { lblError.Visible = true; lblError.Text = GetString("Webparts_Membership_RegistrationForm.EmailIsNotValid"); return; } #endregion #region "Captcha" // Check if captcha is required and verifiy captcha text if (DisplayCaptcha && !scCaptcha.IsValid()) { // Display error message if catcha text is not valid lblError.Visible = true; lblError.Text = GetString("Webparts_Membership_RegistrationForm.captchaError"); return; } #endregion #region "User properties" ui = new UserInfo(); ui.PreferredCultureCode = ""; ui.Email = txtEmail.Text.Trim(); ui.FirstName = txtFirstName.Text.Trim(); ui.LastName = txtLastName.Text.Trim(); ui.FullName = UserInfoProvider.GetFullName(ui.FirstName, String.Empty, ui.LastName); ui.MiddleName = ""; ui.UserMFRequired = chkUseMultiFactorAutentization.Checked; // User name as put by user (no site prefix included) String plainUserName = txtEmail.Text.Trim(); ui.UserName = plainUserName; // Ensure site prefixes if (UserInfoProvider.UserNameSitePrefixEnabled(siteName)) { ui.UserName = UserInfoProvider.EnsureSitePrefixUserName(txtEmail.Text.Trim(), si); } ui.Enabled = EnableUserAfterRegistration; ui.UserURLReferrer = MembershipContext.AuthenticatedUser.URLReferrer; ui.UserCampaign = Service <ICampaignService> .Entry().CampaignCode; ui.SetPrivilegeLevel(UserPrivilegeLevelEnum.None); ui.UserSettings.UserRegistrationInfo.IPAddress = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]; ui.UserSettings.UserRegistrationInfo.Agent = HttpContext.Current.Request.UserAgent; // Check whether confirmation is required bool requiresConfirmation = SettingsKeyInfoProvider.GetBoolValue(siteName + ".CMSRegistrationEmailConfirmation"); bool requiresAdminApprove = false; if (!requiresConfirmation) { // If confirmation is not required check whether administration approval is reqiures if ((requiresAdminApprove = SettingsKeyInfoProvider.GetBoolValue(siteName + ".CMSRegistrationAdministratorApproval"))) { ui.Enabled = false; ui.UserSettings.UserWaitingForApproval = true; } } else { // EnableUserAfterRegistration is overrided by requiresConfirmation - user needs to be confirmed before enable ui.Enabled = false; } // Set user's starting alias path if (!String.IsNullOrEmpty(StartingAliasPath)) { ui.UserStartingAliasPath = MacroResolver.ResolveCurrentPath(StartingAliasPath); } #endregion #region "Reserved names" // Check for reserved user names like administrator, sysadmin, ... if (UserInfoProvider.NameIsReserved(siteName, plainUserName)) { lblError.Visible = true; lblError.Text = GetString("Webparts_Membership_RegistrationForm.UserNameReserved").Replace("%%name%%", HTMLHelper.HTMLEncode(Functions.GetFormattedUserName(ui.UserName, true))); return; } if (UserInfoProvider.NameIsReserved(siteName, plainUserName)) { lblError.Visible = true; lblError.Text = GetString("Webparts_Membership_RegistrationForm.UserNameReserved").Replace("%%name%%", HTMLHelper.HTMLEncode(ui.UserNickName)); return; } #endregion #region "License limitations" string errorMessage = String.Empty; UserInfoProvider.CheckLicenseLimitation(ui, ref errorMessage); if (!String.IsNullOrEmpty(errorMessage)) { lblError.Visible = true; lblError.Text = errorMessage; return; } #endregion // Check whether email is unique if it is required if (!UserInfoProvider.IsEmailUnique(txtEmail.Text.Trim(), siteList, 0)) { lblError.Visible = true; lblError.Text = GetString("UserInfo.EmailAlreadyExist"); return; } // Set password UserInfoProvider.SetPassword(ui, passStrength.Text); #region "Welcome Emails (confirmation, waiting for approval)" bool error = false; EmailTemplateInfo template = null; string emailSubject = null; // Send welcome message with username and password, with confirmation link, user must confirm registration if (requiresConfirmation) { template = EmailTemplateProvider.GetEmailTemplate("RegistrationConfirmation", siteName); emailSubject = EmailHelper.GetSubject(template, GetString("RegistrationForm.RegistrationConfirmationEmailSubject")); } // Send welcome message with username and password, with information that user must be approved by administrator else if (SendWelcomeEmail) { if (requiresAdminApprove) { template = EmailTemplateProvider.GetEmailTemplate("Membership.RegistrationWaitingForApproval", siteName); emailSubject = EmailHelper.GetSubject(template, GetString("RegistrationForm.RegistrationWaitingForApprovalSubject")); } // Send welcome message with username and password, user can logon directly else { template = EmailTemplateProvider.GetEmailTemplate("Membership.Registration", siteName); emailSubject = EmailHelper.GetSubject(template, GetString("RegistrationForm.RegistrationSubject")); } } if (template != null) { // Create relation between contact and user. This ensures that contact will be correctly recognized when user approves registration (if approval is required) int contactId = ModuleCommands.OnlineMarketingGetCurrentContactID(); if (contactId > 0) { ModuleCommands.OnlineMarketingCreateRelation(ui.UserID, 0, contactId); } var resolver = MembershipResolvers.GetMembershipRegistrationResolver(ui, passStrength.Text, AuthenticationHelper.GetRegistrationApprovalUrl(ApprovalPage, ui.UserGUID, siteName, NotifyAdministrator)); // Email message EmailMessage email = new EmailMessage(); email.EmailFormat = EmailFormatEnum.Default; email.Recipients = ui.Email; email.From = EmailHelper.GetSender(template, SettingsKeyInfoProvider.GetValue(siteName + ".CMSNoreplyEmailAddress")); // Enable macro encoding for body resolver.Settings.EncodeResolvedValues = true; email.Body = resolver.ResolveMacros(template.TemplateText); // Disable macro encoding for plaintext body and subject email.PlainTextBody = resolver.ResolveMacros(template.TemplatePlainText); email.Subject = resolver.ResolveMacros(emailSubject); email.CcRecipients = template.TemplateCc; email.BccRecipients = template.TemplateBcc; try { EmailHelper.ResolveMetaFileImages(email, template.TemplateID, EmailTemplateInfo.OBJECT_TYPE, ObjectAttachmentsCategories.TEMPLATE); // Send the e-mail immediately EmailSender.SendEmail(siteName, email, true); } catch (Exception ex) { EventLogProvider.LogException("E", "RegistrationForm - SendEmail", ex); error = true; } } // If there was some error, user must be deleted if (error) { lblError.Visible = true; lblError.Text = GetString("RegistrationForm.UserWasNotCreated"); // Email was not send, user can't be approved - delete it UserInfoProvider.DeleteUser(ui); return; } #endregion #region "Administrator notification email" // Notify administrator if enabled and e-mail confirmation is not required if (!requiresConfirmation && NotifyAdministrator && (FromAddress != String.Empty) && (ToAddress != String.Empty)) { EmailTemplateInfo mEmailTemplate = null; MacroResolver resolver = MembershipResolvers.GetRegistrationResolver(ui); if (SettingsKeyInfoProvider.GetBoolValue(siteName + ".CMSRegistrationAdministratorApproval")) { mEmailTemplate = EmailTemplateProvider.GetEmailTemplate("Registration.Approve", siteName); } else { mEmailTemplate = EmailTemplateProvider.GetEmailTemplate("Registration.New", siteName); } if (mEmailTemplate == null) { // Log missing e-mail template EventLogProvider.LogEvent(EventType.ERROR, "RegistrationForm", "GetEmailTemplate", eventUrl: RequestContext.RawURL); } else { EmailMessage message = new EmailMessage(); message.EmailFormat = EmailFormatEnum.Default; message.From = EmailHelper.GetSender(mEmailTemplate, FromAddress); message.Recipients = ToAddress; // Enable macro encoding for body resolver.Settings.EncodeResolvedValues = true; message.Body = resolver.ResolveMacros(mEmailTemplate.TemplateText); // Disable macro encoding for plaintext body and subject resolver.Settings.EncodeResolvedValues = false; message.PlainTextBody = resolver.ResolveMacros(mEmailTemplate.TemplatePlainText); message.Subject = resolver.ResolveMacros(EmailHelper.GetSubject(mEmailTemplate, GetString("RegistrationForm.EmailSubject"))); message.CcRecipients = mEmailTemplate.TemplateCc; message.BccRecipients = mEmailTemplate.TemplateBcc; try { // Attach template meta-files to e-mail EmailHelper.ResolveMetaFileImages(message, mEmailTemplate.TemplateID, EmailTemplateInfo.OBJECT_TYPE, ObjectAttachmentsCategories.TEMPLATE); EmailSender.SendEmail(siteName, message); } catch { EventLogProvider.LogEvent(EventType.ERROR, "Membership", "RegistrationEmail"); } } } #endregion #region "Web analytics" // Track successful registration conversion if (TrackConversionName != String.Empty) { if (AnalyticsHelper.AnalyticsEnabled(siteName) && !AnalyticsHelper.IsIPExcluded(siteName, RequestContext.UserHostAddress)) { // Log conversion HitLogProvider.LogConversions(siteName, LocalizationContext.PreferredCultureCode, TrackConversionName, 0, ConversionValue); } } // Log registered user if confirmation is not required if (!requiresConfirmation) { AnalyticsHelper.LogRegisteredUser(siteName, ui); } #endregion #region "On-line marketing - activity" // Log registered user if confirmation is not required if (!requiresConfirmation) { Activity activity = new ActivityRegistration(ui, DocumentContext.CurrentDocument, AnalyticsContext.ActivityEnvironmentVariables); if (activity.Data != null) { activity.Data.ContactID = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui); activity.Log(); } // Log login activity if (ui.Enabled) { // Log activity int contactID = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui); Activity activityLogin = new ActivityUserLogin(contactID, ui, DocumentContext.CurrentDocument, AnalyticsContext.ActivityEnvironmentVariables); activityLogin.Log(); } } #endregion #region "Roles & authentication" string[] roleList = AssignRoles.Split(';'); foreach (string sn in siteList) { // Add new user to the current site UserInfoProvider.AddUserToSite(ui.UserName, sn); foreach (string roleName in roleList) { if (!String.IsNullOrEmpty(roleName)) { String s = roleName.StartsWithCSafe(".") ? "" : sn; // Add user to desired roles if (RoleInfoProvider.RoleExists(roleName, s)) { UserInfoProvider.AddUserToRole(ui.UserName, roleName, s); } } } } if (DisplayMessage.Trim() != String.Empty) { pnlForm.Visible = false; lblText.Visible = true; lblText.Text = DisplayMessage; } else { if (ui.Enabled) { AuthenticationHelper.AuthenticateUser(ui.UserName, true); } if (RedirectToURL != String.Empty) { URLHelper.Redirect(RedirectToURL); } else if (QueryHelper.GetString("ReturnURL", "") != String.Empty) { string url = QueryHelper.GetString("ReturnURL", ""); // Do url decode url = Server.UrlDecode(url); // Check that url is relative path or hash is ok if (url.StartsWithCSafe("~") || url.StartsWithCSafe("/") || QueryHelper.ValidateHash("hash", "aliaspath")) { URLHelper.Redirect(url); } // Absolute path with wrong hash else { URLHelper.Redirect(UIHelper.GetErrorPageUrl("dialogs.badhashtitle", "dialogs.badhashtext")); } } } #endregion lblError.Visible = false; } }
/// <summary> /// OK click handler (Proceed registration). /// </summary> protected void btnOK_Click(object sender, EventArgs e) { if ((this.PageManager.ViewMode == ViewModeEnum.Design) || (this.HideOnCurrentPage) || (!this.IsVisible)) { // Do not process } else { String siteName = CMSContext.CurrentSiteName; #region "Banned IPs" // Ban IP addresses which are blocked for registration if (!BannedIPInfoProvider.IsAllowed(siteName, BanControlEnum.Registration)) { lblError.Visible = true; lblError.Text = GetString("banip.ipisbannedregistration"); return; } #endregion #region "Check Email & password" // Check whether user with same email does not exist UserInfo ui = UserInfoProvider.GetUserInfo(txtEmail.Text); SiteInfo si = CMSContext.CurrentSite; UserInfo siteui = UserInfoProvider.GetUserInfo(UserInfoProvider.EnsureSitePrefixUserName(txtEmail.Text, si)); if ((ui != null) || (siteui != null)) { lblError.Visible = true; lblError.Text = GetString("Webparts_Membership_RegistrationForm.UserAlreadyExists").Replace("%%name%%", HTMLHelper.HTMLEncode(txtEmail.Text)); return; } // Check whether password is same if (passStrength.Text != txtConfirmPassword.Text) { lblError.Visible = true; lblError.Text = GetString("Webparts_Membership_RegistrationForm.PassworDoNotMatch"); return; } if ((this.PasswordMinLength > 0) && (passStrength.Text.Length < this.PasswordMinLength)) { lblError.Visible = true; lblError.Text = String.Format(GetString("Webparts_Membership_RegistrationForm.PasswordMinLength"), this.PasswordMinLength.ToString()); return; } if (!passStrength.IsValid()) { lblError.Visible = true; lblError.Text = UserInfoProvider.GetPolicyViolationMessage(CMSContext.CurrentSiteName); return; } if (!ValidationHelper.IsEmail(txtEmail.Text.ToLower())) { lblError.Visible = true; lblError.Text = GetString("Webparts_Membership_RegistrationForm.EmailIsNotValid"); return; } #endregion #region "Captcha" // Check if captcha is required if (this.DisplayCaptcha) { // Verifiy captcha text if (!scCaptcha.IsValid()) { // Display error message if catcha text is not valid lblError.Visible = true; lblError.Text = GetString("Webparts_Membership_RegistrationForm.captchaError"); return; } else { // Generate new captcha scCaptcha.GenerateNew(); } } #endregion #region "User properties" ui = new UserInfo(); ui.PreferredCultureCode = ""; ui.Email = txtEmail.Text.Trim(); ui.FirstName = txtFirstName.Text.Trim(); ui.FullName = txtFirstName.Text.Trim() + " " + txtLastName.Text.Trim(); ui.LastName = txtLastName.Text.Trim(); ui.MiddleName = ""; // User name as put by user (no site prefix included) String plainUserName = txtEmail.Text.Trim(); ui.UserName = plainUserName; // Ensure site prefixes if (UserInfoProvider.UserNameSitePrefixEnabled(siteName)) { ui.UserName = UserInfoProvider.EnsureSitePrefixUserName(txtEmail.Text.Trim(), si); } ui.Enabled = this.EnableUserAfterRegistration; ui.IsEditor = false; ui.IsGlobalAdministrator = false; ui.UserURLReferrer = CMSContext.CurrentUser.URLReferrer; ui.UserCampaign = CMSContext.Campaign; ui.UserSettings.UserRegistrationInfo.IPAddress = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]; ui.UserSettings.UserRegistrationInfo.Agent = HttpContext.Current.Request.UserAgent; // Check whether confirmation is required bool requiresConfirmation = SettingsKeyProvider.GetBoolValue(siteName + ".CMSRegistrationEmailConfirmation"); bool requiresAdminApprove = false; if (!requiresConfirmation) { // If confirmation is not required check whether administration approval is reqiures if ((requiresAdminApprove = SettingsKeyProvider.GetBoolValue(siteName + ".CMSRegistrationAdministratorApproval"))) { ui.Enabled = false; ui.UserSettings.UserWaitingForApproval = true; } } else { // EnableUserAfterRegistration is overrided by requiresConfirmation - user needs to be confirmed before enable ui.Enabled = false; } // Set user's starting alias path if (!String.IsNullOrEmpty(this.StartingAliasPath)) { ui.UserStartingAliasPath = CMSContext.ResolveCurrentPath(this.StartingAliasPath); } #endregion #region "Reserved names" // Check for reserved user names like administrator, sysadmin, ... if (UserInfoProvider.NameIsReserved(siteName, plainUserName)) { lblError.Visible = true; lblError.Text = GetString("Webparts_Membership_RegistrationForm.UserNameReserved").Replace("%%name%%", HTMLHelper.HTMLEncode(Functions.GetFormattedUserName(ui.UserName, true))); return; } if (UserInfoProvider.NameIsReserved(siteName, plainUserName)) { lblError.Visible = true; lblError.Text = GetString("Webparts_Membership_RegistrationForm.UserNameReserved").Replace("%%name%%", HTMLHelper.HTMLEncode(ui.UserNickName)); return; } #endregion #region "License limitations" // Check limitations for Global administrator if (ui.IsGlobalAdministrator) { if (!UserInfoProvider.LicenseVersionCheck(URLHelper.GetCurrentDomain(), FeatureEnum.GlobalAdmininistrators, VersionActionEnum.Insert, false)) { lblError.Visible = true; lblError.Text = GetString("License.MaxItemsReachedGlobal"); return; } } // Check limitations for editors if (ui.IsEditor) { if (!UserInfoProvider.LicenseVersionCheck(URLHelper.GetCurrentDomain(), FeatureEnum.Editors, VersionActionEnum.Insert, false)) { lblError.Visible = true; lblError.Text = GetString("License.MaxItemsReachedEditor"); return; } } // Check limitations for site members if (!UserInfoProvider.LicenseVersionCheck(URLHelper.GetCurrentDomain(), FeatureEnum.SiteMembers, VersionActionEnum.Insert, false)) { lblError.Visible = true; lblError.Text = GetString("License.MaxItemsReachedSiteMember"); return; } #endregion // Check whether email is unique if it is required string checkSites = (String.IsNullOrEmpty(this.AssignToSites)) ? siteName : this.AssignToSites; if (!UserInfoProvider.IsEmailUnique(txtEmail.Text.Trim(), checkSites, 0)) { lblError.Visible = true; lblError.Text = GetString("UserInfo.EmailAlreadyExist"); return; } // Set password UserInfoProvider.SetPassword(ui, passStrength.Text); #region "Welcome Emails (confirmation, waiting for approval)" bool error = false; EventLogProvider ev = new EventLogProvider(); EmailTemplateInfo template = null; string emailSubject = null; // Send welcome message with username and password, with confirmation link, user must confirm registration if (requiresConfirmation) { template = EmailTemplateProvider.GetEmailTemplate("RegistrationConfirmation", siteName); emailSubject = EmailHelper.GetSubject(template, GetString("RegistrationForm.RegistrationConfirmationEmailSubject")); } // Send welcome message with username and password, with information that user must be approved by administrator else if (this.SendWelcomeEmail) { if (requiresAdminApprove) { template = EmailTemplateProvider.GetEmailTemplate("Membership.RegistrationWaitingForApproval", siteName); emailSubject = EmailHelper.GetSubject(template, GetString("RegistrationForm.RegistrationWaitingForApprovalSubject")); } // Send welcome message with username and password, user can logon directly else { template = EmailTemplateProvider.GetEmailTemplate("Membership.Registration", siteName); emailSubject = EmailHelper.GetSubject(template, GetString("RegistrationForm.RegistrationSubject")); } } if (template != null) { // Rretrieve contact ID for confirmation e-mail int contactId = 0; if (ActivitySettingsHelper.ActivitiesEnabledAndModuleLoaded(siteName)) { // Check if loggin registration activity is enabled if (ActivitySettingsHelper.UserRegistrationEnabled(siteName)) { if (ActivitySettingsHelper.ActivitiesEnabledForThisUser(ui)) { contactId = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui); } } } // Prepare macro replacements string[,] replacements = new string[6, 2]; replacements[0, 0] = "confirmaddress"; replacements[0, 1] = (this.ApprovalPage != String.Empty) ? URLHelper.GetAbsoluteUrl(this.ApprovalPage) : URLHelper.GetAbsoluteUrl("~/CMSPages/Dialogs/UserRegistration.aspx"); replacements[0, 1] += "?userguid=" + ui.UserGUID + (contactId > 0?"&contactid=" + contactId.ToString():String.Empty); replacements[1, 0] = "username"; replacements[1, 1] = plainUserName; replacements[2, 0] = "password"; replacements[2, 1] = passStrength.Text; replacements[3, 0] = "Email"; replacements[3, 1] = txtEmail.Text; replacements[4, 0] = "FirstName"; replacements[4, 1] = txtFirstName.Text; replacements[5, 0] = "LastName"; replacements[5, 1] = txtLastName.Text; // Set resolver ContextResolver resolver = CMSContext.CurrentResolver; resolver.SourceParameters = replacements; resolver.EncodeResolvedValues = true; // Email message EmailMessage email = new EmailMessage(); email.EmailFormat = EmailFormatEnum.Default; email.Recipients = ui.Email; email.From = EmailHelper.GetSender(template, SettingsKeyProvider.GetStringValue(siteName + ".CMSNoreplyEmailAddress")); email.Body = resolver.ResolveMacros(template.TemplateText); resolver.EncodeResolvedValues = false; email.PlainTextBody = resolver.ResolveMacros(template.TemplatePlainText); email.Subject = resolver.ResolveMacros(emailSubject); email.CcRecipients = template.TemplateCc; email.BccRecipients = template.TemplateBcc; try { MetaFileInfoProvider.ResolveMetaFileImages(email, template.TemplateID, EmailObjectType.EMAILTEMPLATE, MetaFileInfoProvider.OBJECT_CATEGORY_TEMPLATE); // Send the e-mail immediately EmailSender.SendEmail(siteName, email, true); } catch (Exception ex) { ev.LogEvent("E", "RegistrationForm - SendEmail", ex); error = true; } } // If there was some error, user must be deleted if (error) { lblError.Visible = true; lblError.Text = GetString("RegistrationForm.UserWasNotCreated"); // Email was not send, user can't be approved - delete it UserInfoProvider.DeleteUser(ui); return; } #endregion #region "Administrator notification email" // Notify administrator if enabled and e-mail confirmation is not required if (!requiresConfirmation && this.NotifyAdministrator && (this.FromAddress != String.Empty) && (this.ToAddress != String.Empty)) { EmailTemplateInfo mEmailTemplate = null; if (requiresAdminApprove) { mEmailTemplate = EmailTemplateProvider.GetEmailTemplate("Registration.Approve", siteName); } else { mEmailTemplate = EmailTemplateProvider.GetEmailTemplate("Registration.New", siteName); } if (mEmailTemplate == null) { // Log missing e-mail template ev.LogEvent("E", DateTime.Now, "RegistrationForm", "GetEmailTemplate", HTTPHelper.GetAbsoluteUri()); } else { string[,] replacements = new string[4, 2]; replacements[0, 0] = "firstname"; replacements[0, 1] = ui.FirstName; replacements[1, 0] = "lastname"; replacements[1, 1] = ui.LastName; replacements[2, 0] = "email"; replacements[2, 1] = ui.Email; replacements[3, 0] = "username"; replacements[3, 1] = plainUserName; ContextResolver resolver = CMSContext.CurrentResolver; resolver.SourceParameters = replacements; resolver.EncodeResolvedValues = true; EmailMessage message = new EmailMessage(); message.EmailFormat = EmailFormatEnum.Default; message.From = EmailHelper.GetSender(mEmailTemplate, this.FromAddress); message.Recipients = this.ToAddress; message.Body = resolver.ResolveMacros(mEmailTemplate.TemplateText); resolver.EncodeResolvedValues = false; message.PlainTextBody = resolver.ResolveMacros(mEmailTemplate.TemplatePlainText); message.Subject = resolver.ResolveMacros(EmailHelper.GetSubject(mEmailTemplate, GetString("RegistrationForm.EmailSubject"))); message.CcRecipients = mEmailTemplate.TemplateCc; message.BccRecipients = mEmailTemplate.TemplateBcc; try { // Attach template meta-files to e-mail MetaFileInfoProvider.ResolveMetaFileImages(message, mEmailTemplate.TemplateID, EmailObjectType.EMAILTEMPLATE, MetaFileInfoProvider.OBJECT_CATEGORY_TEMPLATE); EmailSender.SendEmail(siteName, message); } catch { ev.LogEvent("E", DateTime.Now, "Membership", "RegistrationEmail", CMSContext.CurrentSite.SiteID); } } } #endregion #region "Web analytics" // Track successful registration conversion if (this.TrackConversionName != String.Empty) { if (AnalyticsHelper.AnalyticsEnabled(siteName) && AnalyticsHelper.TrackConversionsEnabled(siteName) && !AnalyticsHelper.IsIPExcluded(siteName, HTTPHelper.UserHostAddress)) { // Log conversion HitLogProvider.LogConversions(siteName, CMSContext.PreferredCultureCode, this.TrackConversionName, 0, ConversionValue); } } // Log registered user if confirmation is not required if (!requiresConfirmation) { AnalyticsHelper.LogRegisteredUser(siteName, ui); } #endregion #region "On-line marketing - activity" // Log registered user if confirmation is not required if (!requiresConfirmation) { if (ActivitySettingsHelper.ActivitiesEnabledAndModuleLoaded(siteName)) { int contactId = 0; // Log registration activity if (ActivitySettingsHelper.UserRegistrationEnabled(siteName)) { if (ActivitySettingsHelper.ActivitiesEnabledForThisUser(ui)) { contactId = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui); ActivityLogProvider.LogRegistrationActivity(contactId, ui, URLHelper.CurrentRelativePath, CMSContext.CurrentDocument.DocumentID, siteName, CMSContext.Campaign, CMSContext.CurrentDocument.DocumentCulture); } } // Log login activity if (ui.Enabled && ActivitySettingsHelper.UserLoginEnabled(siteName)) { if (contactId <= 0) { contactId = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui); } ActivityLogHelper.UpdateContactLastLogon(contactId); // Update last logon time if (ActivitySettingsHelper.ActivitiesEnabledForThisUser(ui)) { ActivityLogProvider.LogLoginActivity(contactId, ui, URLHelper.CurrentRelativePath, CMSContext.CurrentDocument.DocumentID, siteName, CMSContext.Campaign, CMSContext.CurrentDocument.DocumentCulture); } } } } #endregion #region "Roles & authentication" string[] roleList = this.AssignRoles.Split(';'); string[] siteList; // If AssignToSites field set if (!String.IsNullOrEmpty(this.AssignToSites)) { siteList = this.AssignToSites.Split(';'); } else // If not set user current site { siteList = new string[] { siteName }; } foreach (string sn in siteList) { // Add new user to the current site UserInfoProvider.AddUserToSite(ui.UserName, sn); foreach (string roleName in roleList) { if (!String.IsNullOrEmpty(roleName)) { String s = roleName.StartsWith(".") ? "" : siteName; // Add user to desired roles if (RoleInfoProvider.RoleExists(roleName, s)) { UserInfoProvider.AddUserToRole(ui.UserName, roleName, s); } } } } if (this.DisplayMessage.Trim() != String.Empty) { pnlForm.Visible = false; lblText.Visible = true; lblText.Text = this.DisplayMessage; } else { if (ui.Enabled) { CMSContext.AuthenticateUser(ui.UserName, true); } if (this.RedirectToURL != String.Empty) { URLHelper.Redirect(this.RedirectToURL); } else if (QueryHelper.GetString("ReturnURL", "") != String.Empty) { string url = QueryHelper.GetString("ReturnURL", ""); // Do url decode url = Server.UrlDecode(url); // Check that url is relative path or hash is ok if (url.StartsWith("~") || url.StartsWith("/") || QueryHelper.ValidateHash("hash")) { URLHelper.Redirect(url); } // Absolute path with wrong hash else { URLHelper.Redirect(ResolveUrl("~/CMSMessages/Error.aspx?title=" + ResHelper.GetString("general.badhashtitle") + "&text=" + ResHelper.GetString("general.badhashtext"))); } } } #endregion lblError.Visible = false; } }
/// <summary> /// On btnRegister click. /// </summary> protected void btnRegister_Click(object sender, EventArgs e) { string currentSiteName = SiteContext.CurrentSiteName; // Check banned IPs if (!BannedIPInfoProvider.IsAllowed(currentSiteName, BanControlEnum.AllNonComplete)) { lblError.Visible = true; lblError.Text = GetString("General.BannedIP"); return; } // Exit if problem occurs if (errorOccurs) { return; } string result = null; Validator val = new Validator(); // Check name fields if required if (RequireName) { result = val.NotEmpty(txtFirstName.Text.Trim(), GetString("eventmanager.firstnamerequired")) .NotEmpty(txtLastName.Text.Trim(), GetString("eventmanager.lastnamerequired")).Result; } // Check e-mail field if (string.IsNullOrEmpty(result)) { result = val.IsEmail(txtEmail.Text.Trim(), GetString("eventmanager.emailrequired")).Result; } // Check phone field if required if (RequirePhone && string.IsNullOrEmpty(result)) { result = val.NotEmpty(txtPhone.Text.Trim(), GetString("eventmanager.phonerequired")).Result; } if (string.IsNullOrEmpty(result)) { // Allow registration if opened if (IsRegistrationOpened) { if (EventNode != null) { if (!EventAttendeeInfoProvider.IsRegisteredForEvent(EventNode.NodeID, txtEmail.Text.Trim())) { // Add new attendant to the event EventAttendeeInfo eai = AddAttendantToEvent(); if (eai != null) { // Log activity Activity activity = new ActivityEventBooking(EventNode, EventNode.GetDocumentName(), eai, AnalyticsContext.ActivityEnvironmentVariables); activity.Log(); // Send invitation e-mail TimeZoneInfo tzi; TimeZoneMethods.GetDateTimeForControl(this, DateTime.Now, out tzi); EventProvider.SendInvitation(currentSiteName, EventNode, eai, tzi); lblRegInfo.Text = GetString("eventmanager.registrationsucceeded"); lblRegInfo.Visible = true; // Hide registration form pnlReg.Visible = false; } } else { // User is already registered lblError.Text = GetString("eventmanager.attendeeregistered"); lblError.Visible = true; } } else { // Event does not exist lblError.Text = GetString("eventmanager.eventnotexist"); lblError.Visible = true; // Hide registration form pnlReg.Visible = false; } } else { // Event registration is not opened lblError.Text = GetString("eventmanager.notopened"); lblError.Visible = true; // Hide registration form pnlReg.Visible = false; } } else { // Display error message lblError.Text = result; lblError.Visible = true; } }
/// <summary> /// Validate values in textboxes. /// </summary> public override bool IsValid() { Validator val = new Validator(); string result = null; if (plcAccount.Visible) { // Validate registration data if (radSignIn.Checked) { ScriptHelper.RegisterStartupScript(this, GetType(), "checkSignIn", ScriptHelper.GetScript("showHideForm('tblSignIn','" + radSignIn.ClientID + "');")); // Check banned IP if (!BannedIPInfoProvider.IsAllowed(SiteContext.CurrentSiteName, BanControlEnum.Login)) { result = GetString("banip.ipisbannedlogin"); } // Check user name if (string.IsNullOrEmpty(result)) { result = val.NotEmpty(txtUsername.Text.Trim(), GetString("ShoppingCartCheckRegistration.ErrorMissingUsername")).Result; } if (!string.IsNullOrEmpty(result)) { lblError.Text = result; lblError.Visible = true; return(false); } } // Check 'New registration' section else if (radNewReg.Checked) { ScriptHelper.RegisterStartupScript(this, GetType(), "checkRegistration", ScriptHelper.GetScript("showHideForm('tblRegistration','" + radNewReg.ClientID + "');")); // Check banned IP if (!BannedIPInfoProvider.IsAllowed(SiteContext.CurrentSiteName, BanControlEnum.Registration)) { result = GetString("banip.ipisbannedregistration"); } if (string.IsNullOrEmpty(result) && !BannedIPInfoProvider.IsAllowed(SiteContext.CurrentSiteName, BanControlEnum.Login)) { result = GetString("banip.ipisbannedlogin"); } // Check registration form if (string.IsNullOrEmpty(result)) { result = val.NotEmpty(txtFirstName1.Text.Trim(), GetString("ShoppingCartCheckRegistration.FirstNameErr")) .NotEmpty(txtLastName1.Text.Trim(), GetString("ShoppingCartCheckRegistration.LastNameErr")) .NotEmpty(txtEmail2.Text.Trim(), GetString("ShoppingCartCheckRegistration.EmailErr")) .NotEmpty(passStrength.Text.Trim(), GetString("ShoppingCartCheckRegistration.PsswdErr")).Result; } // Check company properties if (string.IsNullOrEmpty(result) && mRequireOrgTaxRegIDs && chkCorporateBody.Checked) { result = val.NotEmpty(txtCompany1.Text.Trim(), GetString("ShoppingCartCheckRegistration.CompanyErr")).Result; if ((result == "") && plcOrganizationID.Visible) { result = val.NotEmpty(txtOrganizationID.Text.Trim(), GetString("ShoppingCartCheckRegistration.OrganizationIDErr")).Result; } if ((result == "") && plcTaxRegistrationID.Visible) { result = val.NotEmpty(txtTaxRegistrationID.Text.Trim(), GetString("ShoppingCartCheckRegistration.TaxRegistrationIDErr")).Result; } } if (result == "") { if (!ValidationHelper.IsEmail(txtEmail2.Text.Trim(), true)) { lblEmail2Err.Text = GetString("ShoppingCartCheckRegistration.EmailErr"); lblEmail2Err.Visible = true; } // Password and confirmed password must be same if (passStrength.Text != txtConfirmPsswd.Text) { lblPsswdErr.Text = GetString("ShoppingCartCheckRegistration.DifferentPsswds"); lblPsswdErr.Visible = true; } // Check policy if (!passStrength.IsValid()) { lblPsswdErr.Text = AuthenticationHelper.GetPolicyViolationMessage(SiteContext.CurrentSiteName); lblPsswdErr.Visible = true; } if ((!DataHelper.IsEmpty(lblEmail2Err.Text.Trim())) || (!DataHelper.IsEmpty(lblPsswdErr.Text.Trim()))) { return(false); } } else { lblError.Text = result; lblError.Visible = true; return(false); } } // Check 'Continue as anonymous customer' section else if (radAnonymous.Checked) { ScriptHelper.RegisterStartupScript(this, GetType(), "checkAnonymous", ScriptHelper.GetScript("showHideForm('tblAnonymous','" + radAnonymous.ClientID + "');")); result = val.NotEmpty(txtFirstName2.Text.Trim(), GetString("ShoppingCartCheckRegistration.FirstNameErr")) .NotEmpty(txtLastName2.Text.Trim(), GetString("ShoppingCartCheckRegistration.LastNameErr")) .NotEmpty(txtEmail3.Text.Trim(), GetString("ShoppingCartCheckRegistration.EmailErr")).Result; if (result == "" && mRequireOrgTaxRegIDs && chkCorporateBody2.Checked) { result = val.NotEmpty(txtCompany2.Text.Trim(), ResHelper.GetString("ShoppingCartCheckRegistration.CompanyErr")).Result; // Check organization ID only if visible if ((result == "") && plcOrganizationID2.Visible) { result = val.NotEmpty(txtOrganizationID2.Text.Trim(), ResHelper.GetString("ShoppingCartCheckRegistration.OrganizationIDErr")).Result; } // Check tax ID only if visible if ((result == "") && plcTaxRegistrationID2.Visible) { result = val.NotEmpty(txtTaxRegistrationID2.Text.Trim(), ResHelper.GetString("ShoppingCartCheckRegistration.TaxRegistrationIDErr")).Result; } } if (result == "") { if (!ValidationHelper.IsEmail(txtEmail3.Text.Trim(), true)) { lblEmail3Err.Text = GetString("ShoppingCartCheckRegistration.EmailErr"); lblEmail3Err.Visible = true; return(false); } } else { lblError.Text = result; lblError.Visible = true; return(false); } } } else { // Validate customer data result = val.NotEmpty(txtEditFirst.Text.Trim(), GetString("ShoppingCartCheckRegistration.FirstNameErr")) .NotEmpty(txtEditLast.Text.Trim(), GetString("ShoppingCartCheckRegistration.LastNameErr")) .IsEmail(txtEditEmail.Text.Trim(), GetString("ShoppingCartCheckRegistration.EmailErr"), true).Result; if (result == "" && mRequireOrgTaxRegIDs && chkEditCorpBody.Checked) { result = val.NotEmpty(txtEditCompany.Text.Trim(), GetString("ShoppingCartCheckRegistration.CompanyErr")).Result; // Check organization id only if visible if ((result == "") && plcEditOrgID.Visible) { result = val.NotEmpty(txtEditOrgID.Text.Trim(), GetString("ShoppingCartCheckRegistration.OrganizationIDErr")).Result; } // Check tax id only if visible if ((result == "") && plcEditTaxRegID.Visible) { result = val.NotEmpty(txtEditTaxRegID.Text.Trim(), GetString("ShoppingCartCheckRegistration.TaxRegistrationIDErr")).Result; } } if (result == "") { return(true); } else { lblError.Text = result; lblError.Visible = true; return(false); } } return(true); }
/// <summary> /// Sets data to database. /// </summary> protected void btnOK_Click(object sender, EventArgs e) { // check 'Modify' permission CheckPermissions("Modify"); string errorMessage = new Validator().NotEmpty(txtIPAddress.Text, GetString("banip.IPAddressEmpty")).Result; // Check if regularized ip address doesn't overflow database column if (BannedIPInfoProvider.GetRegularIPAddress(txtIPAddress.Text).Length > 200) { errorMessage = GetString("banip.IPAddressInvalid"); } if (errorMessage == "") { BannedIPInfo bannedIPObj = BannedIPInfoProvider.GetBannedIPInfo(itemid); // if bannedIP doesnt already exist, create new one if (bannedIPObj == null) { bannedIPObj = new BannedIPInfo(); } bannedIPObj.IPAddressAllowed = radAllowIP.Checked; bannedIPObj.IPAddressBanType = drpIPAddressBanType.SelectedValue; bannedIPObj.IPAddressBanEnabled = chkIPAddressBanEnabled.Checked; bannedIPObj.IPAddress = txtIPAddress.Text.Trim(); // Make sure text is not too long if (txtIPAddressBanReason.Text.Length > 450) { txtIPAddressBanReason.Text = txtIPAddressBanReason.Text.Substring(0, 450); } bannedIPObj.IPAddressBanReason = txtIPAddressBanReason.Text.Trim(); if (SiteID == 0) { // For (global) set overriding from checkbox, otherwise is true bannedIPObj.IPAddressAllowOverride = (SelectedSiteID > 0) || chkIPAddressAllowOverride.Checked; // If site selected assign it to banned IP if (SelectedSiteID > 0) { bannedIPObj.IPAddressSiteID = SelectedSiteID; } } else { // default setting for editing from CMSDesk bannedIPObj.IPAddressAllowOverride = true; bannedIPObj.IPAddressSiteID = SiteID; } BannedIPInfoProvider.SetBannedIPInfo(bannedIPObj); URLHelper.Redirect("Bannedip_Edit.aspx?siteid=" + SiteID + "&selectedsiteid=" + SelectedSiteID + "&itemid=" + bannedIPObj.IPAddressID + "&saved=1"); } else { ShowError(errorMessage); } }
/// <summary> /// On chkCorporateBody checkbox checked changed. /// </summary> /// <summary> /// On chkCorporateBody2 checkbox checked changed. /// </summary> /// <summary> /// On chkEditCorpBody checkbox checked changed. /// </summary> /// <summary> /// Validate values in textboxes. /// </summary> public override bool IsValid() { Validator val = new Validator(); string result = null; if (plcAccount.Visible) { // Validate registration data if (radSignIn.Checked) { ScriptHelper.RegisterStartupScript(this, GetType(), "checkSignIn", ScriptHelper.GetScript("showHideForm('tblSignIn','" + radSignIn.ClientID + "');")); // Check banned IP if (!BannedIPInfoProvider.IsAllowed(SiteContext.CurrentSiteName, BanControlEnum.Login)) { result = GetString("banip.ipisbannedlogin"); } // Check user name if (string.IsNullOrEmpty(result)) { result = val.NotEmpty(txtUsername.Text.Trim(), GetString("ShoppingCartCheckRegistration.ErrorMissingUsername")).Result; } if (!string.IsNullOrEmpty(result)) { lblError.Text = result; lblError.Visible = true; return(false); } } // Check 'New registration' section else if (radNewReg.Checked) { ScriptHelper.RegisterStartupScript(this, GetType(), "checkRegistration", ScriptHelper.GetScript("showHideForm('tblRegistration','" + radNewReg.ClientID + "');")); // Check banned IP if (!BannedIPInfoProvider.IsAllowed(SiteContext.CurrentSiteName, BanControlEnum.Registration)) { result = GetString("banip.ipisbannedregistration"); } if (string.IsNullOrEmpty(result) && !BannedIPInfoProvider.IsAllowed(SiteContext.CurrentSiteName, BanControlEnum.Login)) { result = GetString("banip.ipisbannedlogin"); } // Check registration form if (string.IsNullOrEmpty(result)) { result = val.NotEmpty(txtFirstName1.Text.Trim(), GetString("ShoppingCartCheckRegistration.FirstNameErr")) .NotEmpty(txtLastName1.Text.Trim(), GetString("ShoppingCartCheckRegistration.LastNameErr")) .NotEmpty(txtEmail2.Text.Trim(), GetString("ShoppingCartCheckRegistration.EmailErr")) .NotEmpty(passStrength.Text.Trim(), GetString("ShoppingCartCheckRegistration.PsswdErr")).Result; } if (result == "") { if (!ValidationHelper.IsEmail(txtEmail2.Text.Trim())) { lblEmail2Err.Text = GetString("ShoppingCartCheckRegistration.EmailErr"); lblEmail2Err.Visible = true; } // Password and confirmed password must be same if (passStrength.Text != txtConfirmPsswd.Text) { lblPsswdErr.Text = GetString("ShoppingCartCheckRegistration.DifferentPsswds"); lblPsswdErr.Visible = true; } // Check policy if (!passStrength.IsValid()) { lblPsswdErr.Text = AuthenticationHelper.GetPolicyViolationMessage(SiteContext.CurrentSiteName); lblPsswdErr.Visible = true; } if ((!DataHelper.IsEmpty(lblEmail2Err.Text.Trim())) || (!DataHelper.IsEmpty(lblPsswdErr.Text.Trim()))) { return(false); } } else { lblError.Text = result; lblError.Visible = true; return(false); } } } else { if (result == "") { return(true); } else { lblError.Text = result; lblError.Visible = true; return(false); } } return(true); }
/// <summary> /// OK click handler (Proceed registration). /// </summary> private void btnRegister_Click(object sender, EventArgs e) { string currentSiteName = SiteContext.CurrentSiteName; string[] siteList = { currentSiteName }; // If AssignToSites field set if (!String.IsNullOrEmpty(AssignToSites)) { siteList = AssignToSites.Split(';'); } if ((PageManager.ViewMode == ViewModeEnum.Design) || (HideOnCurrentPage) || (!IsVisible)) { // Do not process } else { // Ban IP addresses which are blocked for registration if (!BannedIPInfoProvider.IsAllowed(currentSiteName, BanControlEnum.Registration)) { lblError.Visible = true; lblError.Text = GetString("banip.ipisbannedregistration"); return; } // Check if captcha is required and verify captcha text if (DisplayCaptcha && !captchaElem.IsValid()) { // Display error message if captcha text is not valid lblError.Visible = true; lblError.Text = GetString("Webparts_Membership_RegistrationForm.captchaError"); return; } string userName = String.Empty; string nickName = String.Empty; string firstName = String.Empty; string lastName = String.Empty; string emailValue = String.Empty; // Check duplicate user // 1. Find appropriate control and get its value (i.e. user name) // 2. Try to find user info FormEngineUserControl txtUserName = formUser.FieldControls["UserName"]; if (txtUserName != null) { userName = ValidationHelper.GetString(txtUserName.Value, String.Empty); } FormEngineUserControl txtEmail = formUser.FieldControls["Email"]; if (txtEmail != null) { emailValue = ValidationHelper.GetString(txtEmail.Value, String.Empty); } // If user name and e-mail aren't filled stop processing and display error. if (string.IsNullOrEmpty(userName)) { userName = emailValue; if (String.IsNullOrEmpty(emailValue)) { formUser.StopProcessing = true; lblError.Visible = true; lblError.Text = GetString("customregistrationform.usernameandemail"); return; } else { formUser.Data.SetValue("UserName", userName); } } FormEngineUserControl txtNickName = formUser.FieldControls["UserNickName"]; if (txtNickName != null) { nickName = ValidationHelper.GetString(txtNickName.Value, String.Empty); } FormEngineUserControl txtFirstName = formUser.FieldControls["FirstName"]; if (txtFirstName != null) { firstName = ValidationHelper.GetString(txtFirstName.Value, String.Empty); } FormEngineUserControl txtLastName = formUser.FieldControls["LastName"]; if (txtLastName != null) { lastName = ValidationHelper.GetString(txtLastName.Value, String.Empty); } // Test if "global" or "site" user exists. SiteInfo si = SiteContext.CurrentSite; UserInfo siteui = UserInfoProvider.GetUserInfo(UserInfoProvider.EnsureSitePrefixUserName(userName, si)); if ((UserInfoProvider.GetUserInfo(userName) != null) || (siteui != null)) { lblError.Visible = true; lblError.Text = GetString("Webparts_Membership_RegistrationForm.UserAlreadyExists").Replace("%%name%%", HTMLHelper.HTMLEncode(Functions.GetFormattedUserName(userName, true))); return; } // Check for reserved user names like administrator, sysadmin, ... if (UserInfoProvider.NameIsReserved(currentSiteName, userName)) { lblError.Visible = true; lblError.Text = GetString("Webparts_Membership_RegistrationForm.UserNameReserved").Replace("%%name%%", HTMLHelper.HTMLEncode(Functions.GetFormattedUserName(userName, true))); return; } if (UserInfoProvider.NameIsReserved(currentSiteName, nickName)) { lblError.Visible = true; lblError.Text = GetString("Webparts_Membership_RegistrationForm.UserNameReserved").Replace("%%name%%", HTMLHelper.HTMLEncode(nickName)); return; } // Check limitations for site members if (!UserInfoProvider.LicenseVersionCheck(RequestContext.CurrentDomain, FeatureEnum.SiteMembers, ObjectActionEnum.Insert, false)) { lblError.Visible = true; lblError.Text = GetString("License.MaxItemsReachedSiteMember"); return; } // Check whether email is unique if it is required if (!UserInfoProvider.IsEmailUnique(emailValue, siteList, 0)) { lblError.Visible = true; lblError.Text = GetString("UserInfo.EmailAlreadyExist"); return; } // Validate and save form with new user data if (!formUser.Save()) { // Return if saving failed return; } // Get user info from form UserInfo ui = (UserInfo)formUser.Info; // Add user prefix if settings is on // Ensure site prefixes if (UserInfoProvider.UserNameSitePrefixEnabled(currentSiteName)) { ui.UserName = UserInfoProvider.EnsureSitePrefixUserName(userName, si); } ui.Enabled = EnableUserAfterRegistration; ui.UserURLReferrer = MembershipContext.AuthenticatedUser.URLReferrer; ui.UserCampaign = AnalyticsHelper.Campaign; ui.SetPrivilegeLevel(UserPrivilegeLevelEnum.None); // Fill optionally full user name if (String.IsNullOrEmpty(ui.FullName)) { ui.FullName = UserInfoProvider.GetFullName(ui.FirstName, ui.MiddleName, ui.LastName); } // Ensure nick name if (ui.UserNickName.Trim() == String.Empty) { ui.UserNickName = Functions.GetFormattedUserName(ui.UserName, true); } ui.UserSettings.UserRegistrationInfo.IPAddress = RequestContext.UserHostAddress; ui.UserSettings.UserRegistrationInfo.Agent = HttpContext.Current.Request.UserAgent; ui.UserSettings.UserLogActivities = true; ui.UserSettings.UserShowIntroductionTile = true; // Check whether confirmation is required bool requiresConfirmation = SettingsKeyInfoProvider.GetBoolValue(currentSiteName + ".CMSRegistrationEmailConfirmation"); bool requiresAdminApprove = SettingsKeyInfoProvider.GetBoolValue(currentSiteName + ".CMSRegistrationAdministratorApproval"); if (!requiresConfirmation) { // If confirmation is not required check whether administration approval is reqiures if (requiresAdminApprove) { ui.Enabled = false; ui.UserSettings.UserWaitingForApproval = true; } } else { // EnableUserAfterRegistration is overrided by requiresConfirmation - user needs to be confirmed before enable ui.Enabled = false; } // Set user's starting alias path if (!String.IsNullOrEmpty(StartingAliasPath)) { ui.UserStartingAliasPath = MacroResolver.ResolveCurrentPath(StartingAliasPath); } // Get user password and save it in apropriate format after form save string password = ValidationHelper.GetString(ui.GetValue("UserPassword"), String.Empty); UserInfoProvider.SetPassword(ui, password); // Prepare macro data source for email resolver UserInfo userForMail = ui.Clone(); userForMail.SetValue("UserPassword", string.Empty); object[] data = new object[1]; data[0] = userForMail; // Prepare resolver for notification and welcome emails MacroResolver resolver = MacroContext.CurrentResolver; resolver.SetAnonymousSourceData(data); #region "Welcome Emails (confirmation, waiting for approval)" bool error = false; EmailTemplateInfo template = null; // Prepare macro replacements string[,] replacements = new string[6, 2]; replacements[0, 0] = "confirmaddress"; replacements[0, 1] = AuthenticationHelper.GetRegistrationApprovalUrl(ApprovalPage, ui.UserGUID, currentSiteName, NotifyAdministrator); replacements[1, 0] = "username"; replacements[1, 1] = userName; replacements[2, 0] = "password"; replacements[2, 1] = password; replacements[3, 0] = "Email"; replacements[3, 1] = emailValue; replacements[4, 0] = "FirstName"; replacements[4, 1] = firstName; replacements[5, 0] = "LastName"; replacements[5, 1] = lastName; // Set resolver resolver.SetNamedSourceData(replacements); // Email message EmailMessage emailMessage = new EmailMessage(); emailMessage.EmailFormat = EmailFormatEnum.Default; emailMessage.Recipients = ui.Email; // Send welcome message with username and password, with confirmation link, user must confirm registration if (requiresConfirmation) { template = EmailTemplateProvider.GetEmailTemplate("RegistrationConfirmation", currentSiteName); emailMessage.Subject = GetString("RegistrationForm.RegistrationConfirmationEmailSubject"); } // Send welcome message with username and password, with information that user must be approved by administrator else if (SendWelcomeEmail) { if (requiresAdminApprove) { template = EmailTemplateProvider.GetEmailTemplate("Membership.RegistrationWaitingForApproval", currentSiteName); emailMessage.Subject = GetString("RegistrationForm.RegistrationWaitingForApprovalSubject"); } // Send welcome message with username and password, user can logon directly else { template = EmailTemplateProvider.GetEmailTemplate("Membership.Registration", currentSiteName); emailMessage.Subject = GetString("RegistrationForm.RegistrationSubject"); } } if (template != null) { emailMessage.From = EmailHelper.GetSender(template, SettingsKeyInfoProvider.GetStringValue(currentSiteName + ".CMSNoreplyEmailAddress")); // Enable macro encoding for body resolver.Settings.EncodeResolvedValues = true; emailMessage.Body = resolver.ResolveMacros(template.TemplateText); // Disable macro encoding for plaintext body and subject resolver.Settings.EncodeResolvedValues = false; emailMessage.PlainTextBody = resolver.ResolveMacros(template.TemplatePlainText); emailMessage.Subject = resolver.ResolveMacros(EmailHelper.GetSubject(template, emailMessage.Subject)); emailMessage.CcRecipients = template.TemplateCc; emailMessage.BccRecipients = template.TemplateBcc; try { EmailHelper.ResolveMetaFileImages(emailMessage, template.TemplateID, EmailTemplateInfo.OBJECT_TYPE, ObjectAttachmentsCategories.TEMPLATE); // Send the e-mail immediately EmailSender.SendEmail(currentSiteName, emailMessage, true); } catch (Exception ex) { EventLogProvider.LogException("E", "RegistrationForm - SendEmail", ex); error = true; } } // If there was some error, user must be deleted if (error) { lblError.Visible = true; lblError.Text = GetString("RegistrationForm.UserWasNotCreated"); // Email was not send, user can't be approved - delete it UserInfoProvider.DeleteUser(ui); return; } #endregion #region "Administrator notification email" // Notify administrator if enabled and email confirmation is not required if (!requiresConfirmation && NotifyAdministrator && (FromAddress != String.Empty) && (ToAddress != String.Empty)) { EmailTemplateInfo mEmailTemplate = null; if (requiresAdminApprove) { mEmailTemplate = EmailTemplateProvider.GetEmailTemplate("Registration.Approve", currentSiteName); } else { mEmailTemplate = EmailTemplateProvider.GetEmailTemplate("Registration.New", currentSiteName); } if (mEmailTemplate == null) { EventLogProvider.LogEvent(EventType.ERROR, "RegistrationForm", "GetEmailTemplate", eventUrl: RequestContext.RawURL); } else { // E-mail template ok replacements = new string[4, 2]; replacements[0, 0] = "firstname"; replacements[0, 1] = ui.FirstName; replacements[1, 0] = "lastname"; replacements[1, 1] = ui.LastName; replacements[2, 0] = "email"; replacements[2, 1] = ui.Email; replacements[3, 0] = "username"; replacements[3, 1] = userName; // Set resolver resolver.SetNamedSourceData(replacements); // Enable macro encoding for body resolver.Settings.EncodeResolvedValues = true; EmailMessage message = new EmailMessage(); message.EmailFormat = EmailFormatEnum.Default; message.From = EmailHelper.GetSender(mEmailTemplate, FromAddress); message.Recipients = ToAddress; message.Body = resolver.ResolveMacros(mEmailTemplate.TemplateText); // Disable macro encoding for plaintext body and subject resolver.Settings.EncodeResolvedValues = false; message.Subject = resolver.ResolveMacros(EmailHelper.GetSubject(mEmailTemplate, GetString("RegistrationForm.EmailSubject"))); message.PlainTextBody = resolver.ResolveMacros(mEmailTemplate.TemplatePlainText); message.CcRecipients = mEmailTemplate.TemplateCc; message.BccRecipients = mEmailTemplate.TemplateBcc; try { // Attach template meta-files to e-mail EmailHelper.ResolveMetaFileImages(message, mEmailTemplate.TemplateID, EmailTemplateInfo.OBJECT_TYPE, ObjectAttachmentsCategories.TEMPLATE); EmailSender.SendEmail(currentSiteName, message); } catch { EventLogProvider.LogEvent(EventType.ERROR, "Membership", "RegistrationEmail"); } } } #endregion #region "Web analytics" // Track successful registration conversion if (TrackConversionName != String.Empty) { if (AnalyticsHelper.AnalyticsEnabled(currentSiteName) && AnalyticsHelper.TrackConversionsEnabled(currentSiteName) && !AnalyticsHelper.IsIPExcluded(currentSiteName, RequestContext.UserHostAddress)) { HitLogProvider.LogConversions(currentSiteName, LocalizationContext.PreferredCultureCode, TrackConversionName, 0, ConversionValue); } } // Log registered user if confirmation is not required if (!requiresConfirmation) { AnalyticsHelper.LogRegisteredUser(currentSiteName, ui); } #endregion #region "On-line marketing - activity" // Log registered user if confirmation is not required if (!requiresConfirmation) { Activity activity = new ActivityRegistration(ui, DocumentContext.CurrentDocument, AnalyticsContext.ActivityEnvironmentVariables); if (activity.Data != null) { activity.Data.ContactID = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui); activity.Log(); } // Log login activity if (ui.Enabled) { // Log activity int contactID = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui); Activity activityLogin = new ActivityUserLogin(contactID, ui, DocumentContext.CurrentDocument, AnalyticsContext.ActivityEnvironmentVariables); activityLogin.Log(); } } #endregion #region "Site and roles addition and authentication" string[] roleList = AssignRoles.Split(';'); foreach (string siteName in siteList) { // Add new user to the current site UserInfoProvider.AddUserToSite(ui.UserName, siteName); foreach (string roleName in roleList) { if (!String.IsNullOrEmpty(roleName)) { String sn = roleName.StartsWithCSafe(".") ? String.Empty : siteName; // Add user to desired roles if (RoleInfoProvider.RoleExists(roleName, sn)) { UserInfoProvider.AddUserToRole(ui.UserName, roleName, sn); } } } } if (DisplayMessage.Trim() != String.Empty) { pnlRegForm.Visible = false; lblInfo.Visible = true; lblInfo.Text = DisplayMessage; } else { if (ui.Enabled) { AuthenticationHelper.AuthenticateUser(ui.UserName, true); } string returnUrl = QueryHelper.GetString("ReturnURL", String.Empty); if (!String.IsNullOrEmpty(returnUrl) && (returnUrl.StartsWithCSafe("~") || returnUrl.StartsWithCSafe("/") || QueryHelper.ValidateHash("hash"))) { URLHelper.Redirect(HttpUtility.UrlDecode(returnUrl)); } else if (RedirectToURL != String.Empty) { URLHelper.Redirect(RedirectToURL); } } #endregion lblError.Visible = false; } }
/// <summary> /// On btnRegister click. /// </summary> protected void btnRegister_Click(object sender, EventArgs e) { string currentSiteName = CMSContext.CurrentSiteName; // Check banned ip if (!BannedIPInfoProvider.IsAllowed(currentSiteName, BanControlEnum.AllNonComplete)) { lblError.Visible = true; lblError.Text = GetString("General.BannedIP"); return; } // Exit if problem occurs if (errorOccurs) { return; } string result = null; Validator val = new Validator(); // Check name fields if required if (this.RequireName) { result = val.NotEmpty(txtFirstName.Text.Trim(), GetString("eventmanager.firstnamerequired")) .NotEmpty(txtLastName.Text.Trim(), GetString("eventmanager.lastnamerequired")).Result; } // Check e-mail field if (string.IsNullOrEmpty(result)) { result = val.IsEmail(txtEmail.Text.Trim(), GetString("eventmanager.emailrequired")).Result; } // Check phone field if required if (this.RequirePhone && string.IsNullOrEmpty(result)) { result = val.NotEmpty(txtPhone.Text.Trim(), GetString("eventmanager.phonerequired")).Result; } if (string.IsNullOrEmpty(result)) { DateTime now = DateTime.Now; // Allow registration if opened if ((openFrom == DataHelper.DATETIME_NOT_SELECTED || openFrom < now) && (openTo == DataHelper.DATETIME_NOT_SELECTED || now <= openTo) && (now <= eventDate)) { if (EventNode != null) { if (!EventAttendeeInfoProvider.IsRegisteredForEvent(EventNode.NodeID, txtEmail.Text.Trim())) { // Add new attendant to the event EventAttendeeInfo eai = AddAttendantToEvent(); if (eai != null) { // Log activity if ((CMSContext.ViewMode == ViewModeEnum.LiveSite) && ActivitySettingsHelper.ActivitiesEnabledAndModuleLoaded(currentSiteName) && ActivitySettingsHelper.ActivitiesEnabledForThisUser(CMSContext.CurrentUser) && ActivitySettingsHelper.EventBookingEnabled(currentSiteName)) { if (ValidationHelper.GetBoolean(EventNode.GetValue("EventLogActivity"), false)) { var data = new ActivityData() { ContactID = ModuleCommands.OnlineMarketingGetCurrentContactID(), SiteID = CMSContext.CurrentSiteID, Type = PredefinedActivityType.EVENT_BOOKING, TitleData = EventNode.DocumentName, ItemID = eai.AttendeeID, URL = URLHelper.CurrentRelativePath, ItemDetailID = EventNode.DocumentID, NodeID = EventNode.NodeID, Culture = EventNode.DocumentCulture, Campaign = CMSContext.Campaign }; ActivityLogProvider.LogActivity(data); } } // Send invitation e-mail TimeZoneInfo tzi = null; CMSContext.GetDateTimeForControl(this, DateTime.Now, out tzi); EventProvider.SendInvitation(currentSiteName, EventNode, eai, tzi); lblRegInfo.Text = GetString("eventmanager.registrationsucceeded"); lblRegInfo.Visible = true; // Hide registration form pnlReg.Visible = false; } } else { // User is already registered lblError.Text = GetString("eventmanager.attendeeregistered"); lblError.Visible = true; } } else { // Event does not exist lblError.Text = GetString("eventmanager.eventnotexist"); lblError.Visible = true; // Hide registration form pnlReg.Visible = false; } } else { // Event registration is not opened lblError.Text = GetString("eventmanager.notopened"); lblError.Visible = true; // Hide registration form pnlReg.Visible = false; } } else { // Display error message lblError.Text = result; lblError.Visible = true; } }
/// <summary> /// OK click handler (Proceed registration). /// </summary> protected void btnOK_Click(object sender, EventArgs e) { System.Globalization.CultureInfo currentUI = System.Globalization.CultureInfo.CurrentUICulture; if ((PageManager.ViewMode == ViewModeEnum.Design) || (HideOnCurrentPage) || (!IsVisible)) { // Do not process } else { String siteName = SiteContext.CurrentSiteName; #region "Banned IPs" // Ban IP addresses which are blocked for registration if (!BannedIPInfoProvider.IsAllowed(siteName, BanControlEnum.Registration)) { lblError.Visible = true; lblError.Text = GetString("banip.ipisbannedregistration"); return; } #endregion #region "Pr�nom" if (string.IsNullOrEmpty(txtFirstName.Text) || (txtFirstName.Text.ToLower() == "firstname") || (txtFirstName.Text.ToLower() == "pr�nom") || (txtFirstName.Text.ToLower() == "prenom")) { lblError.Visible = true; lblError.Text = GetString("errornom"); return; } #endregion #region "Nom" if (string.IsNullOrEmpty(txtLastName.Text) || (txtLastName.Text.ToLower() == "nom") || (txtLastName.Text.ToLower() == "lastname")) { lblError.Visible = true; lblError.Text = GetString("errorprenom"); return; } #endregion #region "T�l�phone" if (string.IsNullOrEmpty(txtTelephone.Text) || (txtTelephone.Text.ToLower() == "telephone")) { lblError.Visible = true; lblError.Text = GetString("errortelephone"); return; } #endregion #region Soci�t� if (rboui.Checked) { if ((txtnomsociete.Text == "") || (txtnomsociete.Text == "Nom soci�t�") || (txtnomsociete.Text == "Company Name")) { lblError.Visible = true; lblError.Text = GetString("errornomsociete "); return; } //if ((txtTva.Text == "") || (txtTva.Text == "TVA") || (txtTva.Text == "VAT")) //{ // lblError.Visible = true; // lblError.Text = GetString("errortva "); // return; //} //if (!EUVatChecker.Check(txtTva.Text)) //{ // lblError.Visible = true; // lblError.Text = GetString("errortva2 "); // return; //} } #endregion #region "Captcha" // Check if captcha is required if (DisplayCaptcha) { // Verifiy captcha text if (!scCaptcha.IsValid()) { // Display error message if catcha text is not valid lblError.Visible = true; lblError.Text = GetString("Webparts_Membership_RegistrationForm.captchaError"); return; } else { // Generate new captcha scCaptcha.GenerateNew(); } } #endregion // Set password //UserInfoProvider.SetPassword(ui, passStrength.Text); // UserInfoProvider.SetPassword(ui, txtPassword.Text.Trim()); if (!CurrentUser.IsAuthenticated()) { // Set password // UserInfoProvider.SetPassword(ui, txtPassword.Text.Trim()); } else { #region "Modif User" //Update User UserInfo updateUser = CurrentUser; updateUser.PreferredCultureCode = ""; updateUser.FirstName = txtFirstName.Text.Trim(); updateUser.FullName = UserInfoProvider.GetFullName(txtFirstName.Text.Trim(), String.Empty, txtLastName.Text.Trim()); updateUser.LastName = txtLastName.Text.Trim(); updateUser.MiddleName = ""; if (payement_option.SelectedValue != "0") { updateUser.SetValue("Civilite", payement_option.SelectedValue); } //updateUser.SetValue("Telephone", txtTelephone.Text); updateUser.SetValue("Telephone", txtTelephone.Text); /*if ((txtPassword.Text != "Mot de passe") && (txtPassword.Text != "Password")) * { * UserInfoProvider.SetPassword(updateUser, txtPassword.Text); * //updateUser.SetValue("UserPassword",txtPassword.Text); * }*/ UserInfoProvider.SetUserInfo(updateUser); //Update Customer CustomerInfo updateCustomer = ECommerceContext.CurrentCustomer; updateCustomer.CustomerUserID = updateUser.UserID; updateCustomer.CustomerLastName = txtLastName.Text.Trim(); updateCustomer.CustomerFirstName = txtFirstName.Text.Trim(); updateCustomer.CustomerEmail = txtEmail.Text.Trim(); //add update phone updateCustomer.CustomerPhone = txtTelephone.Text.Trim(); updateCustomer.CustomerEnabled = true; updateCustomer.CustomerLastModified = DateTime.Now; updateCustomer.CustomerSiteID = CMSContext.CurrentSiteID; updateCustomer.CustomerOrganizationID = ""; if (rboui.Checked) { updateCustomer.CustomerCompany = txtnomsociete.Text.Trim(); updateCustomer.CustomerTaxRegistrationID = txtTva.Text; } else { updateCustomer.CustomerCompany = string.Empty; updateCustomer.CustomerTaxRegistrationID = string.Empty; } if ((rboui.Checked) && (txtTva.Text.Trim() != "TVA") && (txtTva.Text.Trim() != "VAT")) { updateCustomer.CustomerTaxRegistrationID = txtTva.Text; updateCustomer.CustomerCompany = txtnomsociete.Text.ToString(); } else { updateCustomer.CustomerTaxRegistrationID = ""; updateCustomer.CustomerCompany = ""; } CustomerInfoProvider.SetCustomerInfo(updateCustomer); #endregion #region "Insert new adress / Update selected adress" //if (chkNewAddress.Checked) //{ #region "n�" if ((txtnumero.Text == "") || (txtnumero.Text == "Numero") || (txtnumero.Text == "Number")) { lblErrorAdress.Visible = true; lblErrorAdress.Text = GetString("errornumerorue"); return; } #endregion #region "adresse 1" if ((txtadresse1.Text == "") || (txtadresse1.Text == "Adresse 1") || (txtadresse1.Text == "Address 1")) { lblErrorAdress.Visible = true; lblErrorAdress.Text = GetString("erroradresse1"); return; } #endregion #region "adresse 2" if ((txtadresse2.Text == "") || (txtadresse2.Text == "Adresse 2") || (txtadresse2.Text == "Address 2")) { lblErrorAdress.Visible = true; lblErrorAdress.Text = GetString("erroradresse2"); return; } #endregion #region "CP" if ((txtcp.Text == "") || (txtcp.Text == "CP") || (txtcp.Text == "ZIP")) { lblErrorAdress.Visible = true; lblErrorAdress.Text = GetString("errorcp"); return; } #endregion #region "Ville" if ((txtville.Text == "") || (txtville.Text == "Ville") || (txtville.Text == "City")) { lblErrorAdress.Visible = true; lblErrorAdress.Text = GetString("errorville"); return; } #endregion #region "Pays" if ((ddlShippingCountry.Text == "Choose your country") || (ddlShippingCountry.Text == "Choisissez votre pays")) { lblErrorAdress.Visible = true; lblErrorAdress.Text = GetString("errorchoixpays "); return; } #endregion #region "Adresse" if ((chkShippingAddr.Checked == false) && (chkBillingAddr.Checked == false)) { lblErrorAdress.Visible = true; lblErrorAdress.Text = GetString("erroradressechek"); return; } #endregion if (txtIdAdresse.Text == "") { #region "New adress" // Create new address object AddressInfo newAddress = new AddressInfo(); int CountryID = ValidationHelper.GetInteger(ddlShippingCountry.SelectedValue, 0); CustomerInfo uc = ECommerceContext.CurrentCustomer; mCustomerId = uc.CustomerID; string mCustomerName = uc.CustomerFirstName + " " + uc.CustomerLastName; // Set the properties newAddress.AddressName = mCustomerName + " , " + txtnumero.Text + " " + txtadresse1.Text + " - " + txtcp.Text + " " + txtville.Text; newAddress.AddressLine1 = txtadresse1.Text; newAddress.AddressLine2 = txtadresse2.Text; newAddress.AddressCity = txtville.Text; newAddress.AddressZip = txtcp.Text; if (chkBillingAddr.Checked) { newAddress.AddressIsBilling = true; } else { newAddress.AddressIsBilling = false; } if (chkShippingAddr.Checked) { newAddress.AddressIsShipping = true; } else { newAddress.AddressIsShipping = false; } newAddress.AddressEnabled = true; newAddress.AddressPersonalName = mCustomerName; newAddress.AddressCustomerID = mCustomerId; newAddress.AddressCountryID = CountryID; newAddress.SetValue("AddressNumber", txtnumero.Text); // Create the address AddressInfoProvider.SetAddressInfo(newAddress); txtnumero.Text = string.Empty; txtadresse1.Text = string.Empty; txtadresse2.Text = string.Empty; txtcp.Text = string.Empty; txtville.Text = string.Empty; // PnlInsertAdress.Visible = false; if (newAddress != null && newAddress.AddressIsShipping == true) { Session["newAddress"] = newAddress.AddressID; //EventLogProvider eve = new EventLogProvider(); //eve.LogEvent("I", DateTime.Now, "id new address= " + Session["newAddress"], "code"); } #endregion } else { #region "Update selected adress" /* * // Udpate selected adress object * int CountryID = ValidationHelper.GetInteger(ddlShippingCountry.SelectedValue, 0); * int AddressId = Convert.ToInt32(txtIdAdresse.Text); * AddressInfo UpdateAdress = AddressInfoProvider.GetAddressInfo(AddressId); * CustomerInfo uc = ECommerceContext.CurrentCustomer; * mCustomerId = uc.CustomerID; * string mCustomerName = uc.CustomerFirstName + " " + uc.CustomerLastName; * // Set the properties * UpdateAdress.AddressName = mCustomerName + " , " + txtnumero.Text + " " + txtadresse1.Text + " - " + txtcp.Text + " " + txtville.Text; * UpdateAdress.SetValue("AddressNumber", txtnumero.Text); * UpdateAdress.AddressLine1 = txtadresse1.Text; * UpdateAdress.AddressLine2 = txtadresse2.Text; * UpdateAdress.AddressCity = txtville.Text; * UpdateAdress.AddressZip = txtcp.Text; * UpdateAdress.AddressIsBilling = chkBillingAddr.Checked; * UpdateAdress.AddressIsShipping = chkShippingAddr.Checked; * UpdateAdress.AddressEnabled = true; * UpdateAdress.AddressPersonalName = mCustomerName; * UpdateAdress.AddressCustomerID = mCustomerId; * UpdateAdress.AddressCountryID = CountryID; * * // Save addressinfo * AddressInfoProvider.SetAddressInfo(UpdateAdress); * AddressId = UpdateAdress.AddressID; */ #endregion } ReloadDataAdress(); //} #endregion } lblError.Visible = false; // PnlInsertAdress.Visible = false; } }
/// <summary> /// Updates the current Group or creates new if no GroupID is present. /// </summary> public void SaveData() { // Check banned ip if (!BannedIPInfoProvider.IsAllowed(CMSContext.CurrentSiteName, BanControlEnum.AllNonComplete)) { lblError.Visible = true; lblError.Text = GetString("General.BannedIP"); return; } // Validate form entries string errorMessage = ValidateForm(); if (errorMessage == "") { try { codeName = GetSafeCodeName(); codeName = GetUniqueCodeName(codeName); GroupInfo group = new GroupInfo(); group.GroupDisplayName = this.txtDisplayName.Text; group.GroupName = codeName; group.GroupDescription = this.txtDescription.Text; group.GroupAccess = GetGroupAccess(); group.GroupSiteID = this.mSiteId; group.GroupApproveMembers = GetGroupApproveMembers(); // Set columns GroupCreatedByUserID and GroupApprovedByUserID to current user CurrentUserInfo user = CMSContext.CurrentUser; if (user != null) { group.GroupCreatedByUserID = user.UserID; if ((!this.RequireApproval) || (CurrentUserIsAdmin())) { group.GroupApprovedByUserID = user.UserID; group.GroupApproved = true; } } // Save Group in the database GroupInfoProvider.SetGroupInfo(group); // Create group admin role RoleInfo roleInfo = new RoleInfo(); roleInfo.DisplayName = "Group admin"; roleInfo.RoleName = group.GroupName + "_groupadmin"; roleInfo.RoleGroupID = group.GroupID; roleInfo.RoleIsGroupAdministrator = true; roleInfo.SiteID = this.mSiteId; // Save group admin role RoleInfoProvider.SetRoleInfo(roleInfo); if (user != null) { // Set user as member of group GroupMemberInfo gmi = new GroupMemberInfo(); gmi.MemberUserID = user.UserID; gmi.MemberGroupID = group.GroupID; gmi.MemberJoined = DateTime.Now; gmi.MemberStatus = GroupMemberStatus.Approved; gmi.MemberApprovedWhen = DateTime.Now; gmi.MemberApprovedByUserID = user.UserID; // Save user as member of group GroupMemberInfoProvider.SetGroupMemberInfo(gmi); // Set user as member of admin group role UserRoleInfo userRole = new UserRoleInfo(); userRole.UserID = user.UserID; userRole.RoleID = roleInfo.RoleID; // Save user as member of admin group role UserRoleInfoProvider.SetUserRoleInfo(userRole); } // Clear user session a request CMSContext.CurrentUser.Invalidate(); CMSContext.CurrentUser = null; string culture = CultureHelper.EnglishCulture.ToString(); if (CMSContext.CurrentDocument != null) { culture = CMSContext.CurrentDocument.DocumentCulture; } // Copy document errorMessage = GroupInfoProvider.CopyGroupDocument(group, CMSContext.ResolveCurrentPath(GroupTemplateSourceAliasPath), CMSContext.ResolveCurrentPath(GroupTemplateTargetAliasPath), GroupProfileURLPath, culture, this.CombineWithDefaultCulture, CMSContext.CurrentUser, roleInfo); if (errorMessage != "") { // Display error message this.lblError.Text = errorMessage; this.lblError.Visible = true; return; } // Create group forum if (CreateForum) { CreateGroupForum(group); // Create group forum search index if (CreateSearchIndexes) { CreateGroupForumSearchIndex(group); } } // Create group media library if (CreateMediaLibrary) { CreateGroupMediaLibrary(group); } // Create search index for group documents if (CreateSearchIndexes) { CreateGroupContentSearchIndex(group); } // Display information on success this.lblInfo.Text = GetString("group.group.createdinfo"); this.lblInfo.Visible = true; // If URL is set, redirect user to specified page if (!String.IsNullOrEmpty(this.RedirectToURL)) { URLHelper.Redirect(ResolveUrl(CMSContext.GetUrl(this.RedirectToURL))); } // After registration message if ((this.RequireApproval) && (!CurrentUserIsAdmin())) { this.lblInfo.Text = this.SuccessfullRegistrationWaitingForApprovalText; // Send approval email to admin if (!String.IsNullOrEmpty(SendWaitingForApprovalEmailTo)) { // Create the message EmailTemplateInfo eti = EmailTemplateProvider.GetEmailTemplate("Groups.WaitingForApproval", CMSContext.CurrentSiteName); if (eti != null) { EmailMessage message = new EmailMessage(); if (String.IsNullOrEmpty(eti.TemplateFrom)) { message.From = SettingsKeyProvider.GetStringValue(CMSContext.CurrentSiteName + ".CMSSendEmailNotificationsFrom"); } else { message.From = eti.TemplateFrom; } MacroResolver resolver = CMSContext.CurrentResolver; resolver.SourceData = new object[] { group }; resolver.SetNamedSourceData("Group", group); message.Recipients = SendWaitingForApprovalEmailTo; message.Subject = resolver.ResolveMacros(eti.TemplateSubject); message.Body = resolver.ResolveMacros(eti.TemplateText); resolver.EncodeResolvedValues = false; message.PlainTextBody = resolver.ResolveMacros(eti.TemplatePlainText); // Send the message using email engine EmailSender.SendEmail(message); } } } else { string groupPath = SettingsKeyProvider.GetStringValue(CMSContext.CurrentSiteName + ".CMSGroupProfilePath"); string url = String.Empty; if (!String.IsNullOrEmpty(groupPath)) { url = TreePathUtils.GetUrl(groupPath.Replace("{GroupName}", group.GroupName)); } this.lblInfo.Text = String.Format(this.SuccessfullRegistrationText, url); } // Hide form if (this.HideFormAfterRegistration) { this.plcForm.Visible = false; } else { ClearForm(); } } catch (Exception ex) { // Display error message this.lblError.Text = GetString("general.erroroccurred") + ex.Message; this.lblError.Visible = true; } } else { // Display error message this.lblError.Text = errorMessage; this.lblError.Visible = true; } }
/// <summary> /// OK click handler. /// </summary> protected void btnOK_Click(object sender, EventArgs e) { // Check banned IP if (!BannedIPInfoProvider.IsAllowed(CMSContext.CurrentSiteName, BanControlEnum.AllNonComplete)) { lblError.Visible = true; lblError.Text = GetString("General.BannedIP"); return; } // Check input fields string email = txtEmail.Text.Trim(); string result = new Validator().NotEmpty(email, rfvEmailRequired.ErrorMessage) .IsEmail(email, GetString("general.correctemailformat")).Result; // Try to subscribe new subscriber if (result == "") { if (this.DocumentID > 0) { BlogPostSubscriptionInfo bpsi = BlogPostSubscriptionInfoProvider.GetBlogPostSubscriptionInfo(email, this.DocumentID); // Check for duplicit subscriptions if (bpsi == null) { bpsi = new BlogPostSubscriptionInfo(); bpsi.SubscriptionPostDocumentID = this.DocumentID; bpsi.SubscriptionEmail = email; // Update user id for logged users (except the public users) if ((CMSContext.CurrentUser != null) && (!CMSContext.CurrentUser.IsPublic())) { bpsi.SubscriptionUserID = CMSContext.CurrentUser.UserID; } BlogPostSubscriptionInfoProvider.SetBlogPostSubscriptionInfo(bpsi); lblInfo.Visible = true; lblInfo.Text = GetString("blog.subscription.beensubscribed"); // Clear form after successful subscription txtEmail.Text = ""; LogActivity(bpsi, this.NodeID, this.Culture); } else { result = GetString("blog.subscription.emailexists"); } } else { result = GetString("general.invalidid"); } } if (result != String.Empty) { lblError.Visible = true; lblError.Text = result; } }
/// <summary> /// OK click hadler. /// </summary> protected void btnOK_Click(object sender, EventArgs e) { #region "Security" // Check whether forum exists if (ForumContext.CurrentForum == null) { return; } // Check security bool securityCheck = true; switch (ForumContext.CurrentState) { case ForumStateEnum.NewThread: securityCheck = IsAvailable(ForumContext.CurrentForum, ForumActionType.NewThread); break; case ForumStateEnum.ReplyToPost: securityCheck = IsAvailable(ForumContext.CurrentForum, ForumActionType.Reply); break; case ForumStateEnum.EditPost: securityCheck = ForumContext.CurrentPost != null && IsAvailable(ForumContext.CurrentPost, ForumActionType.Edit); break; } if (!securityCheck) { ShowError(GetString("ForumNewPost.PermissionDenied")); return; } #region "Captcha" // Check security code if is required if ((ForumContext.CurrentForum.ForumUseCAPTCHA) && (!SecurityCode1.IsValid()) && (ForumContext.CurrentState != ForumStateEnum.EditPost)) { ShowError(GetString("ForumNewPost.InvalidCaptcha")); return; } #endregion #region "Email field" // Create instance of validator Validator validator = new Validator(); // Check whether email is valid string result = validator.IsEmail(txtEmail.Text, rfvEmail.ErrorMessage).Result; // Check whether email is present with correct format if email is required // or when subscribtion to current post is checked if ((ForumContext.CurrentForum.ForumRequireEmail || chkSubscribe.Checked) && (!String.IsNullOrEmpty(result))) { ShowError(result); return; } // Check if email is added if is in correct format if ((txtEmail.Text.Trim() != "") && (!String.IsNullOrEmpty(result))) { ShowError(rfvEmail.ErrorMessage); return; } #endregion #region "Subject" // Check whether subject is filled if (txtSubject.Text.Trim() == "") { ShowError(rfvSubject.ErrorMessage); return; } #endregion #region "Text" validator = new Validator(); // Check post text in HTML editor or text area if (!ForumContext.CurrentForum.ForumHTMLEditor) { // Check whether post text is added in text area if ((result = validator.NotEmpty(DiscussionMacroHelper.RemoveTags(ucBBEditor.Text), rfvText.ErrorMessage).Result) != "") { ShowError(result); return; } } else { // Check whether post text is added in HTML editor if ((result = validator.NotEmpty(htmlTemplateBody.ResolvedValue, rfvText.ErrorMessage).Result) != "") { ShowError(result); return; } } #endregion #region "User name" // Check whether user name is filled if user name field is visible if (ForumContext.CurrentForum.ForumAllowChangeName || CMSContext.CurrentUser.IsPublic() || ((ForumContext.CurrentForum != null) && (ForumContext.UserIsModerator(ForumContext.CurrentForum.ForumID, ForumContext.CommunityGroupID)))) { validator = new Validator(); if (!String.IsNullOrEmpty(result = validator.NotEmpty(txtUserName.Text, rfvUserName.ErrorMessage).Result)) { ShowError(result); return; } } #endregion #endregion #region "Forum post properties" bool newPost = false; // Current forum info object ForumInfo fi = ForumContext.CurrentForum; // Forum post info object ForumPostInfo fp = null; // Get forum post info with dependence on current state if (ForumContext.CurrentState == ForumStateEnum.EditPost) { // Get existing object fp = ForumContext.CurrentPost; fp.PostLastEdit = DateTime.Now; } else { // Create new forum post info object fp = new ForumPostInfo(); newPost = true; } #region "Ad-hoc forum" if (IsAdHocForum && (ForumContext.CurrentForum.ForumID == 0)) { if (CMSContext.CurrentDocument == null) { ShowError(GetString("forums.documentdoesnotexist")); return; } fi.ForumGroupID = ForumGroupInfoProvider.GetAdHocGroupInfo(SiteID).GroupID; fi.ForumName = "AdHoc-" + Guid.NewGuid(); fi.ForumDisplayName = TextHelper.LimitLength(CMSContext.CurrentDocument.GetDocumentName(), POST_USERNAME_LENGTH, String.Empty); fi.ForumOpen = true; fi.ForumModerated = false; fi.ForumAccess = 040000; fi.ForumThreads = 0; fi.ForumPosts = 0; fi.ForumLogActivity = LogActivity; ForumInfoProvider.SetForumInfo(fi); ForumContext.CurrentForum.ForumID = fi.ForumID; ForumContext.ForumID = fi.ForumID; ForumID = fi.ForumID; } #endregion // Post forum fp.PostForumID = ForumContext.CurrentForum.ForumID; // Get forum post info with dependence on current state if (ForumContext.CurrentState != ForumStateEnum.EditPost) { // Post time fp.PostTime = DateTime.Now; // User IP address fp.PostInfo.IPAddress = HTTPHelper.UserHostAddress; // User agent fp.PostInfo.Agent = Request.UserAgent; // Post user id if (!CMSContext.CurrentUser.IsPublic()) { fp.PostUserID = CMSContext.CurrentUser.UserID; } // Post signature fp.PostUserSignature = txtSignature.Text; } // Post subject fp.PostSubject = txtSubject.Text; // Post user email fp.PostUserMail = txtEmail.Text; // Post type int forumType = ForumContext.CurrentForum.ForumType; if (forumType == 0) { if (ForumContext.CurrentReplyThread == null) { // New thread - use type which user chosen fp.PostType = (radTypeDiscussion.Checked ? 0 : 1); } else { // Reply - use parent type fp.PostType = ForumContext.CurrentReplyThread.PostType; } } else { // Fixed type - use the forum setting fp.PostType = forumType - 1; } bool newThread = (ForumContext.CurrentReplyThread == null); // Set username if change name is allowed if (fi.ForumAllowChangeName || CMSContext.CurrentUser.IsPublic() || ForumContext.UserIsModerator(fp.PostForumID, ForumContext.CommunityGroupID)) { fp.PostUserName = TextHelper.LimitLength(txtUserName.Text, POST_USERNAME_LENGTH, ""); } else { // Get forum post info with dependence on current state if (ForumContext.CurrentState != ForumStateEnum.EditPost) { fp.PostUserName = UserName; } } // Post parent id -> reply to if (ForumContext.CurrentReplyThread != null) { fp.PostParentID = ForumContext.CurrentReplyThread.PostId; // Check max relative level if ((MaxRelativeLevel > -1) && (ForumContext.CurrentReplyThread.PostLevel >= MaxRelativeLevel)) { ShowError(GetString("Forums.MaxRelativeLevelError")); return; } } // Get post text from HTML editor if is enabled fp.PostText = ForumContext.CurrentForum.ForumHTMLEditor ? htmlTemplateBody.ResolvedValue : ucBBEditor.Text; // Approve post if forum is not moderated if (newPost) { if (!ForumContext.CurrentForum.ForumModerated) { fp.PostApproved = true; } else { if (ForumContext.UserIsModerator(fp.PostForumID, CommunityGroupID)) { fp.PostApproved = true; fp.PostApprovedByUserID = CMSContext.CurrentUser.UserID; } } } // If signature is enabled then if (EnableSignature) { fp.PostUserSignature = CMSContext.CurrentUser.UserSignature; } #endregion if (!BadWordInfoProvider.CanUseBadWords(CMSContext.CurrentUser, CMSContext.CurrentSiteName)) { // Prepare columns to check Dictionary <string, int> columns = new Dictionary <string, int>(); columns.Add("PostText", 0); columns.Add("PostSubject", 450); columns.Add("PostUserSignature", 0); columns.Add("PostUserName", 200); // Perform bad words check string badMessage = BadWordsHelper.CheckBadWords(fp, columns, "PostApproved", "PostApprovedByUserID", fp.PostText, CMSContext.CurrentUser.UserID, () => { return(ValidatePost(fp)); }); if (String.IsNullOrEmpty(badMessage)) { if (!ValidatePost(fp)) { badMessage = GetString("ForumNewPost.EmptyBadWord"); } } if (!String.IsNullOrEmpty(badMessage)) { ShowError(badMessage); return; } } // Flood protection if (FloodProtectionHelper.CheckFlooding(CMSContext.CurrentSiteName, CMSContext.CurrentUser)) { ShowError(GetString("General.FloodProtection")); return; } // Check banned ip if (!BannedIPInfoProvider.IsAllowed(CMSContext.CurrentSiteName, BanControlEnum.AllNonComplete)) { ShowError(GetString("General.BannedIP")); return; } string baseUrl = ForumContext.CurrentForum.ForumBaseUrl; if (String.IsNullOrEmpty(baseUrl)) { baseUrl = FriendlyBaseURL; } string unsubscriptionUrl = ForumContext.CurrentForum.ForumUnsubscriptionUrl; if (String.IsNullOrEmpty(unsubscriptionUrl)) { unsubscriptionUrl = UnsubscriptionURL; } // USe parent post id for new post int subscibePostId = newPost ? fp.PostParentID : fp.PostId; // Check subscriptions if ((chkSubscribe.Checked) && (!String.IsNullOrEmpty(txtEmail.Text)) && (ForumSubscriptionInfoProvider.IsSubscribed(txtEmail.Text.Trim(), fp.PostForumID, subscibePostId))) { // Post of the forum is already subscribed to this email -> show an error chkSubscribe.Checked = false; ShowError(GetString("Forums.EmailAlreadySubscribed")); return; } // Save post object ForumPostInfoProvider.SetForumPostInfo(fp, baseUrl, unsubscriptionUrl); LogPostActivity(fp, fi); #region "Subscription" // If subscribe is checked create new subscription to the current post if ((chkSubscribe.Checked) && (!ForumSubscriptionInfoProvider.IsSubscribed(fp.PostUserMail, fp.PostForumID, fp.PostId))) { // Create new subscription info object ForumSubscriptionInfo fsi = new ForumSubscriptionInfo(); // Set info properties fsi.SubscriptionForumID = fp.PostForumID; fsi.SubscriptionEmail = fp.PostUserMail; fsi.SubscriptionPostID = fp.PostId; fsi.SubscriptionUserID = fp.PostUserID; fsi.SubscriptionGUID = Guid.NewGuid(); // Save subscription ForumSubscriptionInfoProvider.Subscribe(fsi, DateTime.Now, true, true); if (fsi.SubscriptionApproved) { LogSubscriptionActivity(fsi, fi); } } #endregion // Generate new captcha code SecurityCode1.GenerateNew(); if ((!fp.PostApproved) && (!ForumContext.UserIsModerator(fp.PostForumID, CommunityGroupID))) { if (OnModerationRequired != null) { OnModerationRequired(this, null); } } // Keep current user info CurrentUserInfo currentUser = CMSContext.CurrentUser; if (currentUser.IsAuthenticated() && chkAttachFile.Checked && (currentUser.IsGlobalAdministrator || ForumContext.CurrentForum.AllowAttachFiles != SecurityAccessEnum.Nobody)) { // Redirect to the post attachments URLHelper.Redirect(GetURL(fp, ForumActionType.Attachment)); } else { if (!StopProcessing) { // Redirect back to the forum or forum thread URLHelper.Redirect(ClearURL()); } } }
/// <summary> /// OK click handler. /// </summary> protected void btnOK_Click(object sender, EventArgs e) { // Check banned IP if (!BannedIPInfoProvider.IsAllowed(SiteContext.CurrentSiteName, BanControlEnum.AllNonComplete)) { lblError.Visible = true; lblError.Text = GetString("General.BannedIP"); return; } // Check input fields string email = txtEmail.Text.Trim(); string result = new Validator() .NotEmpty(email, rfvEmailRequired.ErrorMessage) .MatchesCondition(txtEmail, input => input.IsValid(), GetString("general.correctemailformat")) .Result; // Try to subscribe new subscriber if (result == String.Empty) { if (DocumentID > 0) { BlogPostSubscriptionInfo bpsi = BlogPostSubscriptionInfoProvider.GetBlogPostSubscriptionInfo(email, DocumentID); // Check for duplicity of subscriptions if ((bpsi == null) || !bpsi.SubscriptionApproved) { bpsi = new BlogPostSubscriptionInfo(); bpsi.SubscriptionPostDocumentID = DocumentID; bpsi.SubscriptionEmail = email; // Update user id for logged users (except the public users) if ((MembershipContext.AuthenticatedUser != null) && (!MembershipContext.AuthenticatedUser.IsPublic())) { bpsi.SubscriptionUserID = MembershipContext.AuthenticatedUser.UserID; } BlogPostSubscriptionInfoProvider.Subscribe(bpsi, DateTime.Now, true, true); lblInfo.Visible = true; if (bpsi.SubscriptionApproved) { lblInfo.Text = GetString("blog.subscription.beensubscribed"); Service.Resolve <ICurrentContactMergeService>().UpdateCurrentContactEmail(bpsi.SubscriptionEmail, MembershipContext.AuthenticatedUser); var blogsActivityLogger = Service.Resolve <IBlogsActivityLogger>(); blogsActivityLogger.LogBlogPostSubscriptionActivity(bpsi); } else { lblInfo.Text = GetString("general.subscribed.doubleoptin"); int optInInterval = BlogHelper.GetBlogDoubleOptInInterval(SiteContext.CurrentSiteName); if (optInInterval > 0) { lblInfo.Text += "<br />" + string.Format(GetString("general.subscription_timeintervalwarning"), optInInterval); } } // Clear form after successful subscription txtEmail.Text = ""; } else { result = GetString("blog.subscription.emailexists"); } } else { result = GetString("general.invalidid"); } } if (result == String.Empty) { return; } lblError.Visible = true; lblError.Text = result; }
protected void btnOk_Click(object sender, EventArgs e) { // Let the parent control now new message is being saved if (OnBeforeMessageSaved != null) { OnBeforeMessageSaved(); } // Check banned IP if (!BannedIPInfoProvider.IsAllowed(SiteContext.CurrentSiteName, BanControlEnum.AllNonComplete)) { ShowError(GetString("General.BannedIP")); return; } // Validate form string errorMessage = ValidateForm(); if (errorMessage == "") { // Check flooding when message being inserted through the LiveSite if (CheckFloodProtection && IsLiveSite && FloodProtectionHelper.CheckFlooding(SiteContext.CurrentSiteName, MembershipContext.AuthenticatedUser)) { ShowError(GetString("General.FloodProtection")); return; } CurrentUserInfo currentUser = MembershipContext.AuthenticatedUser; BoardMessageInfo messageInfo = null; if (MessageID > 0) { // Get message info messageInfo = BoardMessageInfoProvider.GetBoardMessageInfo(MessageID); MessageBoardID = messageInfo.MessageBoardID; } else { // Create new info messageInfo = new BoardMessageInfo(); // User IP address messageInfo.MessageUserInfo.IPAddress = RequestContext.UserHostAddress; // User agent messageInfo.MessageUserInfo.Agent = Request.UserAgent; } // Setup message info messageInfo.MessageEmail = txtEmail.Text.Trim(); messageInfo.MessageText = txtMessage.Text.Trim(); // Handle message URL string url = txtURL.Text.Trim(); if ((url != "http://") && (url != "https://") && (url != "")) { if ((!url.ToLowerCSafe().StartsWithCSafe("http://")) && (!url.ToLowerCSafe().StartsWithCSafe("https://"))) { url = "http://" + url; } } else { url = ""; } messageInfo.MessageURL = url; messageInfo.MessageURL = messageInfo.MessageURL.ToLowerCSafe().Replace("javascript", "_javascript"); messageInfo.MessageUserName = txtUserName.Text.Trim(); if ((MessageID <= 0) && (!currentUser.IsPublic())) { messageInfo.MessageUserID = currentUser.UserID; } messageInfo.MessageIsSpam = ValidationHelper.GetBoolean(chkSpam.Checked, false); if (BoardProperties.EnableContentRating && (ratingControl != null) && (ratingControl.GetCurrentRating() > 0)) { messageInfo.MessageRatingValue = ratingControl.CurrentRating; // Remember rating in cookie string docs = CookieHelper.GetValue(CookieName.RatedDocuments) ?? "|"; if (!docs.Contains("|" + DocumentContext.CurrentDocument.DocumentID + "|")) { docs += DocumentContext.CurrentDocument.DocumentID + "|"; // Actualize the cookie CookieHelper.SetValue(CookieName.RatedDocuments, docs, DateTime.Now.AddYears(1)); } } BoardInfo boardInfo = null; // If there is message board if (MessageBoardID > 0) { // Load message board boardInfo = Board; } else { // Create new message board according to webpart properties boardInfo = new BoardInfo(BoardProperties); BoardInfoProvider.SetBoardInfo(boardInfo); // Update information on current message board MessageBoardID = boardInfo.BoardID; // Set board-role relationship BoardRoleInfoProvider.SetBoardRoles(MessageBoardID, BoardProperties.BoardRoles); // Set moderators BoardModeratorInfoProvider.SetBoardModerators(MessageBoardID, BoardProperties.BoardModerators); } if (boardInfo != null) { // If the very new message is inserted if (MessageID == 0) { // If creating message set inserted to now and assign to board messageInfo.MessageInserted = currentUser.DateTimeNow; messageInfo.MessageBoardID = MessageBoardID; // Handle auto approve action bool isAuthorized = BoardInfoProvider.IsUserAuthorizedToManageMessages(boardInfo); if (isAuthorized) { messageInfo.MessageApprovedByUserID = currentUser.UserID; messageInfo.MessageApproved = true; } else { // Is board moderated ? messageInfo.MessageApprovedByUserID = 0; messageInfo.MessageApproved = !boardInfo.BoardModerated; } } else { if (chkApproved.Checked) { // Set current user as approver messageInfo.MessageApproved = true; messageInfo.MessageApprovedByUserID = currentUser.UserID; } else { messageInfo.MessageApproved = false; messageInfo.MessageApprovedByUserID = 0; } } if (!AdvancedMode) { if (!BadWordInfoProvider.CanUseBadWords(MembershipContext.AuthenticatedUser, SiteContext.CurrentSiteName)) { // Columns to check Dictionary <string, int> collumns = new Dictionary <string, int>(); collumns.Add("MessageText", 0); collumns.Add("MessageUserName", 250); // Perform bad words check errorMessage = BadWordsHelper.CheckBadWords(messageInfo, collumns, "MessageApproved", "MessageApprovedByUserID", messageInfo.MessageText, currentUser.UserID, () => { return(ValidateMessage(messageInfo)); }); // Additionally check empty fields if (errorMessage == string.Empty) { if (!ValidateMessage(messageInfo)) { errorMessage = GetString("board.messageedit.emptybadword"); } } } } // Subscribe this user to message board if (chkSubscribe.Checked) { string email = messageInfo.MessageEmail; // Check for duplicate e-mails DataSet ds = BoardSubscriptionInfoProvider.GetSubscriptions("((SubscriptionApproved = 1) OR (SubscriptionApproved IS NULL)) AND SubscriptionBoardID=" + MessageBoardID + " AND SubscriptionEmail='" + SecurityHelper.GetSafeQueryString(email, false) + "'", null); if (DataHelper.DataSourceIsEmpty(ds)) { BoardSubscriptionInfo bsi = new BoardSubscriptionInfo(); bsi.SubscriptionBoardID = MessageBoardID; bsi.SubscriptionEmail = email; if (!currentUser.IsPublic()) { bsi.SubscriptionUserID = currentUser.UserID; } BoardSubscriptionInfoProvider.Subscribe(bsi, DateTime.Now, true, true); ClearForm(); if (bsi.SubscriptionApproved) { LogSubscribingActivity(bsi, boardInfo); } } else { errorMessage = GetString("board.subscription.emailexists"); } } if (errorMessage == "") { try { // Save message info BoardMessageInfoProvider.SetBoardMessageInfo(messageInfo); LogCommentActivity(messageInfo, boardInfo); if (BoardProperties.EnableContentRating && (ratingControl != null) && (ratingControl.GetCurrentRating() > 0)) { LogRatingActivity(ratingControl.CurrentRating); } // If the message is not approved let the user know message is waiting for approval if (messageInfo.MessageApproved == false) { ShowError(GetString("board.messageedit.waitingapproval")); } // Rise after message saved event if (OnAfterMessageSaved != null) { OnAfterMessageSaved(messageInfo); } // Hide message form if user has rated and empty rating is not allowed if (!BoardProperties.AllowEmptyRating && TreeProvider.HasRated(DocumentContext.CurrentDocument)) { pnlMessageEdit.Visible = false; lblAlreadyrated.Visible = true; } else { // Hide rating form if user has rated if (BoardProperties.EnableContentRating && (ratingControl != null) && ratingControl.GetCurrentRating() > 0) { plcRating.Visible = false; } } // Clear form content ClearForm(); } catch (Exception ex) { errorMessage = ex.Message; } } } } if (!String.IsNullOrEmpty(errorMessage)) { ShowError(errorMessage); } }
/// <summary> /// Updates the current Group or creates new if no GroupID is present. /// </summary> public void SaveData() { // Check banned IP if (!BannedIPInfoProvider.IsAllowed(SiteContext.CurrentSiteName, BanControlEnum.AllNonComplete)) { ShowError(GetString("General.BannedIP")); return; } // Validate form entries string errorMessage = ValidateForm(); if (!String.IsNullOrEmpty(errorMessage)) { // Display error message ShowError(errorMessage); return; } try { GroupInfo group = new GroupInfo(); group.GroupDisplayName = txtDisplayName.Text; group.GroupDescription = txtDescription.Text; group.GroupAccess = GetGroupAccess(); group.GroupSiteID = mSiteId; group.GroupApproveMembers = GetGroupApproveMembers(); // Automatic code name can be set after display name + site id is set group.Generalized.EnsureCodeName(); // Set columns GroupCreatedByUserID and GroupApprovedByUserID to current user var user = MembershipContext.AuthenticatedUser; if (user != null) { group.GroupCreatedByUserID = user.UserID; if ((!RequireApproval) || (CurrentUserIsAdmin())) { group.GroupApprovedByUserID = user.UserID; group.GroupApproved = true; } } // Save Group in the database GroupInfoProvider.SetGroupInfo(group); // Create group admin role RoleInfo roleInfo = new RoleInfo(); roleInfo.RoleDisplayName = "Group admin"; roleInfo.RoleName = group.GroupName + "_groupadmin"; roleInfo.RoleGroupID = group.GroupID; roleInfo.RoleIsGroupAdministrator = true; roleInfo.SiteID = mSiteId; // Save group admin role RoleInfoProvider.SetRoleInfo(roleInfo); if (user != null) { // Set user as member of group GroupMemberInfo gmi = new GroupMemberInfo(); gmi.MemberUserID = user.UserID; gmi.MemberGroupID = group.GroupID; gmi.MemberJoined = DateTime.Now; gmi.MemberStatus = GroupMemberStatus.Approved; gmi.MemberApprovedWhen = DateTime.Now; gmi.MemberApprovedByUserID = user.UserID; // Save user as member of group GroupMemberInfoProvider.SetGroupMemberInfo(gmi); // Set user as member of admin group role UserRoleInfo userRole = new UserRoleInfo(); userRole.UserID = user.UserID; userRole.RoleID = roleInfo.RoleID; // Save user as member of admin group role UserRoleInfoProvider.SetUserRoleInfo(userRole); } // Clear user session a request MembershipContext.AuthenticatedUser.Generalized.Invalidate(false); MembershipContext.AuthenticatedUser = null; string culture = CultureHelper.EnglishCulture.ToString(); if (DocumentContext.CurrentDocument != null) { culture = DocumentContext.CurrentDocument.DocumentCulture; } // Copy document errorMessage = GroupInfoProvider.CopyGroupDocument(group, GroupTemplateSourceAliasPath, GroupTemplateTargetAliasPath, GroupProfileURLPath, culture, CombineWithDefaultCulture, MembershipContext.AuthenticatedUser, roleInfo); if (!String.IsNullOrEmpty(errorMessage)) { // Display error message ShowError(errorMessage); return; } // Create group forum if (CreateForum) { CreateGroupForum(group); // Create group forum search index if (CreateSearchIndexes) { CreateGroupForumSearchIndex(group); } } // Create group media library if (CreateMediaLibrary) { CreateGroupMediaLibrary(group); } // Create search index for group documents if (CreateSearchIndexes) { CreateGroupContentSearchIndex(group); } // Display information on success ShowConfirmation(GetString("group.group.createdinfo")); // If URL is set, redirect user to specified page if (!String.IsNullOrEmpty(RedirectToURL)) { URLHelper.Redirect(UrlResolver.ResolveUrl(ResolveUrl(DocumentURLProvider.GetUrl(RedirectToURL)))); } // After registration message if ((RequireApproval) && (!CurrentUserIsAdmin())) { ShowConfirmation(SuccessfullRegistrationWaitingForApprovalText); // Send approval email to admin if (!String.IsNullOrEmpty(SendWaitingForApprovalEmailTo)) { var siteName = SiteContext.CurrentSiteName; // Create the message EmailTemplateInfo eti = EmailTemplateProvider.GetEmailTemplate("Groups.WaitingForApproval", siteName); if (eti != null) { MacroResolver resolver = MacroContext.CurrentResolver; resolver.SetAnonymousSourceData(group); resolver.SetNamedSourceData("Group", group); EmailMessage message = new EmailMessage { From = SettingsKeyInfoProvider.GetValue(siteName + ".CMSSendEmailNotificationsFrom"), Recipients = SendWaitingForApprovalEmailTo }; // Send the message using email engine EmailSender.SendEmailWithTemplateText(siteName, message, eti, resolver, false); } } } else { string groupPath = SettingsKeyInfoProvider.GetValue(SiteContext.CurrentSiteName + ".CMSGroupProfilePath"); string url = String.Empty; if (!String.IsNullOrEmpty(groupPath)) { url = DocumentURLProvider.GetUrl(groupPath.Replace("{GroupName}", group.GroupName)); } ShowConfirmation(String.Format(SuccessfullRegistrationText, url)); } // Hide form if (HideFormAfterRegistration) { plcForm.Visible = false; } else { ClearForm(); } } catch (Exception ex) { // Display error message ShowError(GetString("general.saveerror"), ex.Message); } }
protected void Page_Load(object sender, EventArgs e) { // Controls initialization radBanIP.Text = GetString("banip.radBanIP"); radAllowIP.Text = GetString("banip.radAllowIP"); lblIPAddressBanType.Text = GetString("banip.IPAddressBanType") + ResHelper.Colon; lblIPAddressBanEnabled.Text = GetString("general.enabled") + ResHelper.Colon; lblIPAddress.Text = GetString("banip.IPAddress") + ResHelper.Colon; lblIPAddressBanReason.Text = GetString("banip.IPAddressBanReason") + ResHelper.Colon; rfvIPAddress.ErrorMessage = GetString("banip.IPAddressEmpty"); lblIPAddressAllowOverride.Text = GetString("banip.IPAddressAllowOverride") + ResHelper.Colon; if (!RequestHelper.IsPostBack()) { // Add list items to ban type drop down list ControlsHelper.FillListControlWithEnum <BanControlEnum>(drpIPAddressBanType, "banip.bantype", useStringRepresentation: true); drpIPAddressBanType.SelectedValue = BanControlEnum.AllNonComplete.ToStringRepresentation(); } string currentBannedIP = GetString("banip.NewItemCaption"); // Get bannedIP id from querystring itemid = QueryHelper.GetInteger("itemid", 0); if (itemid > 0) { BannedIPInfo bannedIPObj = BannedIPInfoProvider.GetBannedIPInfo(itemid); EditedObject = bannedIPObj; if (bannedIPObj != null) { //Check whether the item truly belogs to specified site if (((SiteID > 0) && (bannedIPObj.IPAddressSiteID != SiteID)) || ((SelectedSiteID > 0) && (bannedIPObj.IPAddressSiteID != SelectedSiteID))) { RedirectToAccessDenied(GetString("banip.invaliditem")); } currentBannedIP = bannedIPObj.IPAddress; // Add site info to breadcrumbs if (SiteID == 0) { if (bannedIPObj.IPAddressSiteID == 0) { currentBannedIP += " (global)"; radAllowIP.Text = GetString("banip.radAllowIPglobal"); plcIPOveride.Visible = true; } else { SiteInfo si = SiteInfoProvider.GetSiteInfo(bannedIPObj.IPAddressSiteID); if (si != null) { currentBannedIP += " (" + si.DisplayName + ")"; } } } // Fill editing form if (!RequestHelper.IsPostBack()) { LoadData(bannedIPObj); // Show that the bannedIP was created or updated successfully if ((QueryHelper.GetInteger("saved", 0) == 1) && !URLHelper.IsPostback()) { ShowChangesSaved(); } } } } // Initializes page title control SetBreadcrumb(0, GetString("banip.listHeaderCaption"), ResolveUrl("BannedIP_List.aspx?siteId=" + SiteID + "&selectedsiteid=" + SelectedSiteID), null, null); SetBreadcrumb(1, currentBannedIP, null, null, null); // Add info about selected site in Site manager for new item if ((SiteID == 0) && (itemid == 0)) { if (SelectedSiteID > 0) { // Site banned IP SiteInfo si = SiteInfoProvider.GetSiteInfo(SelectedSiteID); if (si != null) { SetBreadcrumb(1, currentBannedIP + " (" + si.DisplayName + ")", null, null, null); } } else { // Global banned IP SetBreadcrumb(1, currentBannedIP + " (global)", null, null, null); radAllowIP.Text = GetString("banip.radAllowIPglobal"); plcIPOveride.Visible = true; } } // Different header and icon if it is new item if (itemid <= 0) { SetTitle(GetString("banip.newHeaderCaption")); } }
/// <summary> /// Performes reporting of abuse. /// </summary> public void PerformAction() { // Check banned ip if (!BannedIPInfoProvider.IsAllowed(CMSContext.CurrentSiteName, BanControlEnum.AllNonComplete)) { lblSaved.CssClass = "ErrorLabel"; lblSaved.Text = GetString("General.BannedIP"); return; } string report = txtText.Text; // Check that text area is not empty or too long report = report.Trim(); report = TextHelper.LimitLength(report, 1000); if (report.Length > 0) { // Create new AbuseReport AbuseReportInfo abuseReport = new AbuseReportInfo(); if (ReportTitle != "") { // Set AbuseReport properties // Decode first, from forums it can be encoded ReportTitle = Server.HtmlDecode(ReportTitle); // Remove BBCode tags ReportTitle = DiscussionMacroHelper.RemoveTags(ReportTitle); abuseReport.ReportTitle = TextHelper.LimitLength(ReportTitle, 100); abuseReport.ReportURL = ReportURL; abuseReport.ReportCulture = CMSContext.PreferredCultureCode; if (ReportObjectID > 0) { abuseReport.ReportObjectID = ReportObjectID; } if (ReportObjectType != "") { abuseReport.ReportObjectType = ReportObjectType; } abuseReport.ReportComment = report; if (CMSContext.CurrentUser.UserID > 0) { abuseReport.ReportUserID = CMSContext.CurrentUser.UserID; } abuseReport.ReportWhen = DateTime.Now; abuseReport.ReportStatus = AbuseReportStatusEnum.New; abuseReport.ReportSiteID = CMSContext.CurrentSite.SiteID; // Save AbuseReport AbuseReportInfoProvider.SetAbuseReportInfo(abuseReport); LogActivity(abuseReport); lblSaved.ResourceString = ConfirmationText; lblSaved.Visible = true; txtText.Visible = false; ReportButton.Visible = false; } else { lblSaved.ResourceString = "abuse.errors.reporttitle"; lblSaved.CssClass = "ErrorLabel"; lblSaved.Visible = true; } } else { lblSaved.ResourceString = "abuse.errors.reportcomment"; lblSaved.CssClass = "ErrorLabel"; lblSaved.Visible = true; } // Additional form modification ReportButton.Visible = false; CancelButton.ResourceString = "general.close"; }
/// <summary> /// OK click handler. /// </summary> protected void btnOK_Click(object sender, EventArgs e) { // Check banned IP if (!BannedIPInfoProvider.IsAllowed(SiteContext.CurrentSiteName, BanControlEnum.AllNonComplete)) { ShowError(GetString("General.BannedIP")); return; } // Check input fields string email = txtEmail.Text.Trim(); string result = new Validator() .NotEmpty(email, rfvEmailRequired.ErrorMessage) .IsEmail(email, GetString("general.correctemailformat"), checkLength: true) .Result; if (!String.IsNullOrEmpty(result)) { ShowError(result); return; } // Try to create a new board BoardInfo boardInfo = null; if (BoardID == 0) { // Create new message board according to webpart properties boardInfo = new BoardInfo(BoardProperties); BoardInfoProvider.SetBoardInfo(boardInfo); // Update information on current message board BoardID = boardInfo.BoardID; // Set board-role relationship BoardRoleInfoProvider.SetBoardRoles(BoardID, BoardProperties.BoardRoles); // Set moderators BoardModeratorInfoProvider.SetBoardModerators(BoardID, BoardProperties.BoardModerators); } if (BoardID > 0) { // Check for duplicit e-mails DataSet ds = BoardSubscriptionInfoProvider.GetSubscriptions("(SubscriptionApproved <> 0) AND (SubscriptionBoardID=" + BoardID + ") AND (SubscriptionEmail='" + SqlHelper.GetSafeQueryString(email, false) + "')", null); if (!DataHelper.DataSourceIsEmpty(ds)) { ShowError(GetString("board.subscription.emailexists")); return; } BoardSubscriptionInfo bsi = new BoardSubscriptionInfo(); bsi.SubscriptionBoardID = BoardID; bsi.SubscriptionEmail = email; if ((MembershipContext.AuthenticatedUser != null) && !MembershipContext.AuthenticatedUser.IsPublic()) { bsi.SubscriptionUserID = MembershipContext.AuthenticatedUser.UserID; } BoardSubscriptionInfoProvider.Subscribe(bsi, DateTime.Now, true, true); // Clear form txtEmail.Text = ""; if (boardInfo == null) { boardInfo = BoardInfoProvider.GetBoardInfo(BoardID); } // If subscribed, log activity if (bsi.SubscriptionApproved) { ShowConfirmation(GetString("board.subscription.beensubscribed")); Service <ICurrentContactMergeService> .Entry().UpdateCurrentContactEmail(bsi.SubscriptionEmail, MembershipContext.AuthenticatedUser); LogActivity(bsi, boardInfo); } else { string confirmation = GetString("general.subscribed.doubleoptin"); int optInInterval = BoardInfoProvider.DoubleOptInInterval(SiteContext.CurrentSiteName); if (optInInterval > 0) { confirmation += "<br />" + string.Format(GetString("general.subscription_timeintervalwarning"), optInInterval); } ShowConfirmation(confirmation); } } }
/// <summary> /// OK click handler. /// </summary> protected void btnOK_Click(object sender, EventArgs e) { // Check banned IP if (!BannedIPInfoProvider.IsAllowed(SiteContext.CurrentSiteName, BanControlEnum.AllNonComplete)) { ShowError(GetString("General.BannedIP")); return; } // Check input fields string result = new Validator().NotEmpty(txtEmail.Text, rfvEmailRequired.ErrorMessage).IsRegularExp(txtEmail.Text, @"^([\w0-9_-]+(\.[\w0-9_-]+)*@[\w0-9_-]+(\.[\w0-9_-]+)+)*$", rfvEmail.ErrorMessage).Result; if (result == "") { // For selected forum and only if subscription is enabled if ((ForumContext.CurrentForum != null) && ((ForumContext.CurrentState == ForumStateEnum.SubscribeToPost) || (ForumContext.CurrentState == ForumStateEnum.NewSubscription))) { // Check permissions if (!IsAvailable(ForumContext.CurrentForum, ForumActionType.SubscribeToForum)) { ShowError(GetString("ForumNewPost.PermissionDenied")); return; } // Create new subscription ForumSubscriptionInfo fsi = new ForumSubscriptionInfo(); fsi.SubscriptionForumID = ForumContext.CurrentForum.ForumID; fsi.SubscriptionEmail = HTMLHelper.HTMLEncode(txtEmail.Text.Trim()); fsi.SubscriptionGUID = Guid.NewGuid(); if (ForumContext.CurrentSubscribeThread != null) { fsi.SubscriptionPostID = ForumContext.CurrentSubscribeThread.PostId; } if (MembershipContext.AuthenticatedUser != null) { fsi.SubscriptionUserID = MembershipContext.AuthenticatedUser.UserID; } // Check whether user is not subscribed if (ForumSubscriptionInfoProvider.IsSubscribed(txtEmail.Text.Trim(), fsi.SubscriptionForumID, fsi.SubscriptionPostID)) { ShowError(GetString("ForumSubscibe.SubscriptionExists")); return; } ForumSubscriptionInfoProvider.Subscribe(fsi, DateTime.Now, true, true); if (fsi.SubscriptionApproved) { ShowConfirmation(GetString("blog.subscription.beensubscribed")); LogSubscriptionActivity(fsi, ForumContext.CurrentForum); } else { string confirmation = GetString("general.subscribed.doubleoptin"); int optInInterval = ForumGroupInfoProvider.DoubleOptInInterval(SiteContext.CurrentSiteName); if (optInInterval > 0) { confirmation += "<br />" + string.Format(GetString("general.subscription_timeintervalwarning"), optInInterval); } ShowConfirmation(confirmation); } } } URLHelper.Redirect(ClearURL()); }
public void PerformAction() { // Check banned ip if (!BannedIPInfoProvider.IsAllowed(SiteContext.CurrentSiteName, BanControlEnum.AllNonComplete)) { lblError.Visible = true; lblError.Text = GetString("General.BannedIP"); return; } if (OnBeforeCommentSaved != null) { OnBeforeCommentSaved(); } // Validate form string errorMessage = ValidateForm(); if (errorMessage == "") { // Check flooding when message being inserted through the LiveSite if (IsLiveSite && FloodProtectionHelper.CheckFlooding(SiteContext.CurrentSiteName, MembershipContext.AuthenticatedUser)) { lblError.Visible = true; lblError.Text = GetString("General.FloodProtection"); return; } var currentUser = MembershipContext.AuthenticatedUser; // Create new comment BlogCommentInfo bci; if (IsInsertMode) { bci = new BlogCommentInfo(); bci.CommentDate = DateTime.Now; bci.CommentPostDocumentID = mPostDocumentId; // User IP address bci.CommentInfo.IPAddress = RequestContext.UserHostAddress; // User agent bci.CommentInfo.Agent = Request.UserAgent; if (!currentUser.IsPublic()) { bci.CommentUserID = currentUser.UserID; } } // Get existing comment else { bci = BlogCommentInfoProvider.GetBlogCommentInfo(mCommentId); } // Update basic comment properties if (bci != null) { // Add http:// if needed string url = txtUrl.Text.Trim(); if (!String.IsNullOrEmpty(url)) { string protocol = URLHelper.GetProtocol(url); if (String.IsNullOrEmpty(protocol)) { url = "http://" + url; } } bci.CommentIsSpam = chkSpam.Checked; bci.CommentApproved = chkApproved.Checked; bci.CommentUserName = txtName.Text.Trim(); bci.CommentUrl = url; bci.CommentText = txtComments.Text.Trim(); bci.CommentUrl = bci.CommentUrl.ToLowerCSafe().Replace("javascript", "_javascript"); bci.CommentEmail = txtEmail.Text.Trim(); } if (IsInsertMode) { // Auto approve owner comments if (bci != null) { TreeNode blogNode = BlogHelper.GetParentBlog(bci.CommentPostDocumentID, false); if ((currentUser != null) && (blogNode != null)) { bool isAuthorized = BlogHelper.IsUserAuthorizedToManageComments(blogNode); if (isAuthorized) { bci.CommentApprovedByUserID = blogNode.NodeOwner; bci.CommentApproved = true; } else { // Is blog moderated ? bool moderated = ValidationHelper.GetBoolean(blogNode.GetValue("BlogModerateComments"), false); bci.CommentApprovedByUserID = 0; bci.CommentApproved = !moderated; } } } } // Perform bad words check if (!BadWordInfoProvider.CanUseBadWords(MembershipContext.AuthenticatedUser, SiteContext.CurrentSiteName)) { if (bci != null) { // Prepare columns to check Dictionary <string, int> columns = new Dictionary <string, int>(); columns.Add("CommentText", 0); columns.Add("CommentUserName", 200); // Perform bad words to check errorMessage = BadWordsHelper.CheckBadWords(bci, columns, "CommentApproved", "CommentApprovedByUserID", bci.CommentText, MembershipContext.AuthenticatedUser.UserID, () => ValidateComment(bci)); } } if (errorMessage == string.Empty) { if (bci != null) { if (!ValidateComment(bci)) { // Show error message lblError.Visible = true; lblError.Text = GetString("Blog.CommentEdit.EmptyBadWord"); } else { // Subscribe new subscriber if (chkSubscribe.Checked) { // Check for duplicate subscriptions BlogPostSubscriptionInfo bpsi = BlogPostSubscriptionInfoProvider.GetBlogPostSubscriptionInfo(txtEmail.Text, mPostDocumentId); if ((bpsi == null) || !bpsi.SubscriptionApproved) { bpsi = new BlogPostSubscriptionInfo(); bpsi.SubscriptionEmail = txtEmail.Text; bpsi.SubscriptionPostDocumentID = mPostDocumentId; bpsi.SubscriptionUserID = bci.CommentUserID; BlogPostSubscriptionInfoProvider.Subscribe(bpsi, DateTime.Now, true, true); if (bpsi.SubscriptionApproved) { LogRegistrationActivity(bpsi); } } else { errorMessage = GetString("blog.subscription.emailexists"); } } if (errorMessage == "") { // Save changes to database BlogCommentInfoProvider.SetBlogCommentInfo(bci); if (!bci.CommentApproved) { CommentSavedText = GetString("blog.comments.requiresmoderationafteraction"); } // Inform user lblInfo.Visible = true; lblInfo.Text = CommentSavedText; // Clear form when required if (mClearFormAfterSave) { txtComments.Text = ""; txtUrl.Text = ""; ctrlCaptcha.Value = ""; } LogCommentActivity(bci, PostNodeId, PostCulture); if (OnAfterCommentSaved != null) { OnAfterCommentSaved(bci); } } } } } } if (errorMessage != "") { // Show error message lblError.Visible = true; lblError.Text = errorMessage; } }
/// <summary> /// OK click handler. /// </summary> protected void btnOK_Click(object sender, EventArgs e) { // Check banned ip if (!BannedIPInfoProvider.IsAllowed(CMSContext.CurrentSiteName, BanControlEnum.AllNonComplete)) { lblError.Visible = true; lblError.Text = GetString("General.BannedIP"); return; } // Check input fields string email = txtEmail.Text.Trim(); string result = new Validator().NotEmpty(email, rfvEmailRequired.ErrorMessage) .IsEmail(email, GetString("general.correctemailformat")).Result; // Try to subscribe new subscriber if (result == "") { // Try to create a new board BoardInfo boardInfo = null; if (this.BoardID == 0) { // Create new message board according to webpart properties boardInfo = new BoardInfo(this.BoardProperties); BoardInfoProvider.SetBoardInfo(boardInfo); // Update information on current message board this.BoardID = boardInfo.BoardID; // Set board-role relationship BoardRoleInfoProvider.SetBoardRoles(this.BoardID, this.BoardProperties.BoardRoles); // Set moderators BoardModeratorInfoProvider.SetBoardModerators(this.BoardID, this.BoardProperties.BoardModerators); } if (this.BoardID > 0) { // Check for duplicit e-mails DataSet ds = BoardSubscriptionInfoProvider.GetSubscriptions("SubscriptionBoardID=" + this.BoardID + " AND SubscriptionEmail='" + SqlHelperClass.GetSafeQueryString(email, false) + "'", null); if (DataHelper.DataSourceIsEmpty(ds)) { BoardSubscriptionInfo bsi = new BoardSubscriptionInfo(); bsi.SubscriptionBoardID = this.BoardID; bsi.SubscriptionEmail = email; if ((CMSContext.CurrentUser != null) && !CMSContext.CurrentUser.IsPublic()) { bsi.SubscriptionUserID = CMSContext.CurrentUser.UserID; } BoardSubscriptionInfoProvider.SetBoardSubscriptionInfo(bsi); lblInfo.Visible = true; lblInfo.Text = GetString("board.subscription.beensubscribed"); // Clear form txtEmail.Text = ""; if (boardInfo == null) { boardInfo = BoardInfoProvider.GetBoardInfo(this.BoardID); } LogActivity(bsi, boardInfo); } else { result = GetString("board.subscription.emailexists"); } } } if (result != String.Empty) { lblError.Visible = true; lblError.Text = result; } }
/// <summary> /// Performs reporting of abuse. /// </summary> public void PerformAction() { // Check banned ip if (!BannedIPInfoProvider.IsAllowed(SiteContext.CurrentSiteName, BanControlEnum.AllNonComplete)) { ShowError(GetString("General.BannedIP")); return; } string report = txtText.Text; // Check that text area is not empty or too long report = report.Trim(); report = TextHelper.LimitLength(report, 1000); if (report.Length > 0) { // Create new AbuseReport AbuseReportInfo abuseReport = new AbuseReportInfo(); if (ReportTitle != "") { // Set AbuseReport properties // Decode first, from forums it can be encoded ReportTitle = Server.HtmlDecode(ReportTitle); // Remove BBCode tags ReportTitle = DiscussionMacroResolver.RemoveTags(ReportTitle); abuseReport.ReportTitle = TextHelper.LimitLength(ReportTitle, 100); abuseReport.ReportURL = URLHelper.GetAbsoluteUrl(ReportURL); abuseReport.ReportCulture = LocalizationContext.PreferredCultureCode; if (ReportObjectID > 0) { abuseReport.ReportObjectID = ReportObjectID; } if (ReportObjectType != "") { abuseReport.ReportObjectType = ReportObjectType; } abuseReport.ReportComment = report; if (MembershipContext.AuthenticatedUser.UserID > 0) { abuseReport.ReportUserID = MembershipContext.AuthenticatedUser.UserID; } abuseReport.ReportWhen = DateTime.Now; abuseReport.ReportStatus = AbuseReportStatusEnum.New; abuseReport.ReportSiteID = SiteContext.CurrentSite.SiteID; // Save AbuseReport AbuseReportInfoProvider.SetAbuseReportInfo(abuseReport); LogActivity(abuseReport); ShowConfirmation(GetString(ConfirmationText), true); txtText.Visible = false; ReportButton.Visible = false; } else { ShowError(GetString("abuse.errors.reporttitle")); } } else { ShowError(GetString("abuse.errors.reportcomment")); } // Additional form modification ReportButton.Visible = false; }
/// <summary> /// OK click handler (Proceed registration). /// </summary> void btnRegister_Click(object sender, EventArgs e) { if ((this.PageManager.ViewMode == ViewModeEnum.Design) || (this.HideOnCurrentPage) || (!this.IsVisible)) { // Do not process } else { // Ban IP addresses which are blocked for registration if (!BannedIPInfoProvider.IsAllowed(CMSContext.CurrentSiteName, BanControlEnum.Registration)) { lblError.Visible = true; lblError.Text = GetString("banip.ipisbannedregistration"); return; } // Check if captcha is required if (this.DisplayCaptcha) { // Verify captcha text if (!captchaElem.IsValid()) { // Display error message if catcha text is not valid lblError.Visible = true; lblError.Text = GetString("Webparts_Membership_RegistrationForm.captchaError"); return; } else { // Generate new code and clear captcha textbox if cpatcha code is valid captchaElem.GenerateNew(); } } string userName = String.Empty; string nickName = String.Empty; string firstName = String.Empty; string lastName = String.Empty; string emailValue = String.Empty; // Check duplicit user // 1. Find appropriate control and get its value (i.e. user name) // 2. Try to find user info EditingFormControl txtUserName = formUser.BasicForm.FieldEditingControls["UserName"] as EditingFormControl; if (txtUserName != null) { userName = ValidationHelper.GetString(txtUserName.Value, String.Empty); } EditingFormControl txtNickName = formUser.BasicForm.FieldEditingControls["UserNickName"] as EditingFormControl; if (txtNickName != null) { nickName = ValidationHelper.GetString(txtNickName.Value, String.Empty); } EditingFormControl txtEmail = formUser.BasicForm.FieldEditingControls["Email"] as EditingFormControl; if (txtEmail != null) { emailValue = ValidationHelper.GetString(txtEmail.Value, String.Empty); } EditingFormControl txtFirstName = formUser.BasicForm.FieldEditingControls["FirstName"] as EditingFormControl; if (txtFirstName != null) { firstName = ValidationHelper.GetString(txtFirstName.Value, String.Empty); } EditingFormControl txtLastName = formUser.BasicForm.FieldEditingControls["LastName"] as EditingFormControl; if (txtLastName != null) { lastName = ValidationHelper.GetString(txtLastName.Value, String.Empty); } // Test if "global" or "site" user exists. SiteInfo si = CMSContext.CurrentSite; UserInfo siteui = UserInfoProvider.GetUserInfo(UserInfoProvider.EnsureSitePrefixUserName(userName, si)); if ((UserInfoProvider.GetUserInfo(userName) != null) || (siteui != null)) { lblError.Visible = true; lblError.Text = GetString("Webparts_Membership_RegistrationForm.UserAlreadyExists").Replace("%%name%%", HTMLHelper.HTMLEncode(Functions.GetFormattedUserName(userName, true))); return; } // Check for reserved user names like administrator, sysadmin, ... if (UserInfoProvider.NameIsReserved(CMSContext.CurrentSiteName, userName)) { lblError.Visible = true; lblError.Text = GetString("Webparts_Membership_RegistrationForm.UserNameReserved").Replace("%%name%%", HTMLHelper.HTMLEncode(Functions.GetFormattedUserName(userName, true))); return; } if (UserInfoProvider.NameIsReserved(CMSContext.CurrentSiteName, nickName)) { lblError.Visible = true; lblError.Text = GetString("Webparts_Membership_RegistrationForm.UserNameReserved").Replace("%%name%%", HTMLHelper.HTMLEncode(nickName)); return; } // Check limitations for site members if (!UserInfoProvider.LicenseVersionCheck(URLHelper.GetCurrentDomain(), FeatureEnum.SiteMembers, VersionActionEnum.Insert, false)) { lblError.Visible = true; lblError.Text = GetString("License.MaxItemsReachedSiteMember"); return; } // Check whether email is unique if it is required string checkSites = (String.IsNullOrEmpty(this.AssignToSites)) ? CMSContext.CurrentSiteName : this.AssignToSites; if (!UserInfoProvider.IsEmailUnique(emailValue, checkSites, 0)) { lblError.Visible = true; lblError.Text = GetString("UserInfo.EmailAlreadyExist"); return; } // Validate and save form with new user data if (!formUser.Save()) { // Return if saving failed return; } // Get user info from form UserInfo ui = (UserInfo)formUser.Info; // Add user prefix if settings is on // Ensure site prefixes if (UserInfoProvider.UserNameSitePrefixEnabled(CMSContext.CurrentSiteName)) { ui.UserName = UserInfoProvider.EnsureSitePrefixUserName(userName, si); } ui.PreferredCultureCode = ""; ui.Enabled = this.EnableUserAfterRegistration; ui.IsEditor = false; ui.IsGlobalAdministrator = false; ui.UserURLReferrer = CMSContext.CurrentUser.URLReferrer; ui.UserCampaign = CMSContext.Campaign; // Fill optionally full user name if (String.IsNullOrEmpty(ui.FullName)) { string fullName = ""; if (ui.FirstName.Trim() != "") { fullName += ui.FirstName; } if (ui.MiddleName.Trim() != "") { fullName += " " + ui.MiddleName; } if (ui.LastName.Trim() != "") { fullName += " " + ui.LastName; } ui.FullName = fullName; } // Ensure nick name if (ui.UserNickName.Trim() == "") { ui.UserNickName = Functions.GetFormattedUserName(ui.UserName, true); } ui.UserSettings.UserRegistrationInfo.IPAddress = HTTPHelper.UserHostAddress; ui.UserSettings.UserRegistrationInfo.Agent = HttpContext.Current.Request.UserAgent; ui.UserSettings.UserLogActivities = true; ui.UserSettings.UserShowSplashScreen = true; // Check whether confirmation is required bool requiresConfirmation = SettingsKeyProvider.GetBoolValue(CMSContext.CurrentSiteName + ".CMSRegistrationEmailConfirmation"); bool requiresAdminApprove = SettingsKeyProvider.GetBoolValue(CMSContext.CurrentSiteName + ".CMSRegistrationAdministratorApproval"); if (!requiresConfirmation) { // If confirmation is not required check whether administration approval is reqiures if (requiresAdminApprove) { ui.Enabled = false; ui.UserSettings.UserWaitingForApproval = true; } } else { // EnableUserAfterRegistration is overrided by requiresConfirmation - user needs to be confirmed before enable ui.Enabled = false; } // Set user's starting alias path if (!String.IsNullOrEmpty(this.StartingAliasPath)) { ui.UserStartingAliasPath = CMSContext.ResolveCurrentPath(this.StartingAliasPath); } // Get user password and save it in apropriate format after form save string password = ValidationHelper.GetString(ui.GetValue("UserPassword"), String.Empty); UserInfoProvider.SetPassword(ui, password); #region "Welcome Emails (confirmation, waiting for approval)" bool error = false; EventLogProvider ev = new EventLogProvider(); EmailTemplateInfo template = null; // Prepare macro replacements string[,] replacements = new string[6, 2]; replacements[0, 0] = "confirmaddress"; replacements[0, 1] = (this.ApprovalPage != String.Empty) ? URLHelper.GetAbsoluteUrl(this.ApprovalPage) + "?userguid=" + ui.UserGUID : URLHelper.GetAbsoluteUrl("~/CMSPages/Dialogs/UserRegistration.aspx") + "?userguid=" + ui.UserGUID; replacements[1, 0] = "username"; replacements[1, 1] = userName; replacements[2, 0] = "password"; replacements[2, 1] = password; replacements[3, 0] = "Email"; replacements[3, 1] = emailValue; replacements[4, 0] = "FirstName"; replacements[4, 1] = firstName; replacements[5, 0] = "LastName"; replacements[5, 1] = lastName; // Set resolver ContextResolver resolver = CMSContext.CurrentResolver; resolver.SourceParameters = replacements; // Email message EmailMessage emailMessage = new EmailMessage(); emailMessage.EmailFormat = EmailFormatEnum.Default; emailMessage.Recipients = ui.Email; // Send welcome message with username and password, with confirmation link, user must confirm registration if (requiresConfirmation) { template = EmailTemplateProvider.GetEmailTemplate("RegistrationConfirmation", CMSContext.CurrentSiteName); emailMessage.Subject = GetString("RegistrationForm.RegistrationConfirmationEmailSubject"); } // Send welcome message with username and password, with information that user must be approved by administrator else if (this.SendWelcomeEmail) { if (requiresAdminApprove) { template = EmailTemplateProvider.GetEmailTemplate("Membership.RegistrationWaitingForApproval", CMSContext.CurrentSiteName); emailMessage.Subject = GetString("RegistrationForm.RegistrationWaitingForApprovalSubject"); } // Send welcome message with username and password, user can logon directly else { template = EmailTemplateProvider.GetEmailTemplate("Membership.Registration", CMSContext.CurrentSiteName); emailMessage.Subject = GetString("RegistrationForm.RegistrationSubject"); } } if (template != null) { emailMessage.From = EmailHelper.GetSender(template, SettingsKeyProvider.GetStringValue(CMSContext.CurrentSiteName + ".CMSNoreplyEmailAddress")); // Enable macro encoding for body resolver.EncodeResolvedValues = true; emailMessage.Body = resolver.ResolveMacros(template.TemplateText); // Disable macro encoding for plaintext body and subject resolver.EncodeResolvedValues = false; emailMessage.PlainTextBody = resolver.ResolveMacros(template.TemplatePlainText); emailMessage.Subject = resolver.ResolveMacros(EmailHelper.GetSubject(template, emailMessage.Subject)); emailMessage.CcRecipients = template.TemplateCc; emailMessage.BccRecipients = template.TemplateBcc; try { MetaFileInfoProvider.ResolveMetaFileImages(emailMessage, template.TemplateID, EmailObjectType.EMAILTEMPLATE, MetaFileInfoProvider.OBJECT_CATEGORY_TEMPLATE); // Send the e-mail immediately EmailSender.SendEmail(CMSContext.CurrentSiteName, emailMessage, true); } catch (Exception ex) { ev.LogEvent("E", "RegistrationForm - SendEmail", ex); error = true; } } // If there was some error, user must be deleted if (error) { lblError.Visible = true; lblError.Text = GetString("RegistrationForm.UserWasNotCreated"); // Email was not send, user can't be approved - delete it UserInfoProvider.DeleteUser(ui); return; } #endregion #region "Administrator notification email" // Notify administrator if enabled and email confirmation is not required if (!requiresConfirmation && this.NotifyAdministrator && (this.FromAddress != String.Empty) && (this.ToAddress != String.Empty)) { EmailTemplateInfo mEmailTemplate = null; if (requiresAdminApprove) { mEmailTemplate = EmailTemplateProvider.GetEmailTemplate("Registration.Approve", CMSContext.CurrentSiteName); } else { mEmailTemplate = EmailTemplateProvider.GetEmailTemplate("Registration.New", CMSContext.CurrentSiteName); } if (mEmailTemplate == null) { ev.LogEvent("E", DateTime.Now, "RegistrationForm", "GetEmailTemplate", HTTPHelper.GetAbsoluteUri()); } //email template ok else { replacements = new string[4, 2]; replacements[0, 0] = "firstname"; replacements[0, 1] = ui.FirstName; replacements[1, 0] = "lastname"; replacements[1, 1] = ui.LastName; replacements[2, 0] = "email"; replacements[2, 1] = ui.Email; replacements[3, 0] = "username"; replacements[3, 1] = userName; // Set resolver resolver = CMSContext.CurrentResolver; resolver.SourceParameters = replacements; // Enable macro encoding for body resolver.EncodeResolvedValues = true; EmailMessage message = new EmailMessage(); message.EmailFormat = EmailFormatEnum.Default; message.From = EmailHelper.GetSender(mEmailTemplate, this.FromAddress); message.Recipients = this.ToAddress; message.Body = resolver.ResolveMacros(mEmailTemplate.TemplateText); // Disable macro encoding for plaintext body and subject resolver.EncodeResolvedValues = false; message.Subject = resolver.ResolveMacros(EmailHelper.GetSubject(mEmailTemplate, GetString("RegistrationForm.EmailSubject"))); message.PlainTextBody = resolver.ResolveMacros(mEmailTemplate.TemplatePlainText); message.CcRecipients = mEmailTemplate.TemplateCc; message.BccRecipients = mEmailTemplate.TemplateBcc; try { // Attach template meta-files to e-mail MetaFileInfoProvider.ResolveMetaFileImages(message, mEmailTemplate.TemplateID, EmailObjectType.EMAILTEMPLATE, MetaFileInfoProvider.OBJECT_CATEGORY_TEMPLATE); EmailSender.SendEmail(CMSContext.CurrentSiteName, message); } catch { ev.LogEvent("E", DateTime.Now, "Membership", "RegistrationEmail", CMSContext.CurrentSite.SiteID); } } } #endregion #region "Web analytics" // Track successful registration conversion if (this.TrackConversionName != String.Empty) { string siteName = CMSContext.CurrentSiteName; if (AnalyticsHelper.AnalyticsEnabled(siteName) && AnalyticsHelper.TrackConversionsEnabled(siteName) && !AnalyticsHelper.IsIPExcluded(siteName, HTTPHelper.UserHostAddress)) { HitLogProvider.LogConversions(siteName, CMSContext.PreferredCultureCode, this.TrackConversionName, 0, ConversionValue); } } // Log registered user if confirmation is not required if (!requiresConfirmation) { AnalyticsHelper.LogRegisteredUser(CMSContext.CurrentSiteName, ui); } #endregion #region "On-line marketing - activity" // Log registered user if confirmation is not required if (!requiresConfirmation) { string siteName = CMSContext.CurrentSiteName; if (ActivitySettingsHelper.ActivitiesEnabledAndModuleLoaded(siteName)) { int contactId = 0; // Log registration activity if (ActivitySettingsHelper.UserRegistrationEnabled(siteName)) { if (ActivitySettingsHelper.ActivitiesEnabledForThisUser(ui)) { contactId = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui); ActivityLogProvider.LogRegistrationActivity(contactId, ui, URLHelper.CurrentRelativePath, CMSContext.CurrentDocument.DocumentID, siteName, CMSContext.Campaign, CMSContext.CurrentDocument.DocumentCulture); } } // Log login activity if (ui.Enabled && ActivitySettingsHelper.UserLoginEnabled(siteName)) { if (contactId <= 0) { contactId = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui); } ActivityLogHelper.UpdateContactLastLogon(contactId); // Update last logon time if (ActivitySettingsHelper.ActivitiesEnabledForThisUser(ui)) { ActivityLogProvider.LogLoginActivity(contactId, ui, URLHelper.CurrentRelativePath, CMSContext.CurrentDocument.DocumentID, siteName, CMSContext.Campaign, CMSContext.CurrentDocument.DocumentCulture); } } } } #endregion #region "Site and roles addition and authentication" string[] roleList = this.AssignRoles.Split(';'); string[] siteList; // If AssignToSites field set if (!String.IsNullOrEmpty(this.AssignToSites)) { siteList = this.AssignToSites.Split(';'); } else // If not set user current site { siteList = new string[] { CMSContext.CurrentSiteName }; } foreach (string siteName in siteList) { // Add new user to the current site UserInfoProvider.AddUserToSite(ui.UserName, siteName); foreach (string roleName in roleList) { if (!String.IsNullOrEmpty(roleName)) { String sn = roleName.StartsWith(".") ? "" : siteName; // Add user to desired roles if (RoleInfoProvider.RoleExists(roleName, sn)) { UserInfoProvider.AddUserToRole(ui.UserName, roleName, sn); } } } } if (this.DisplayMessage.Trim() != String.Empty) { pnlRegForm.Visible = false; lblInfo.Visible = true; lblInfo.Text = this.DisplayMessage; } else { if (ui.Enabled) { CMSContext.AuthenticateUser(ui.UserName, true); } string returnUrl = QueryHelper.GetString("ReturnURL", ""); if (!String.IsNullOrEmpty(returnUrl) && (returnUrl.StartsWith("~") || returnUrl.StartsWith("/") || QueryHelper.ValidateHash("hash"))) { URLHelper.Redirect(HttpUtility.UrlDecode(returnUrl)); } else if (this.RedirectToURL != String.Empty) { URLHelper.Redirect(this.RedirectToURL); } } #endregion lblError.Visible = false; } }