public void SendFormEmail(BizFormItem item, int attachmentsCount) { if (item.BizFormInfo != null) { MacroResolver resolver = MacroContext.CurrentResolver.CreateChild(); resolver.SetAnonymousSourceData(item); resolver.Settings.EncodeResolvedValues = true; resolver.Culture = CultureHelper.GetPreferredCulture(); string body = DataHelper.GetNotEmpty(item.BizFormInfo.FormEmailTemplate, string.Empty); body = resolver.ResolveMacros(body); EmailMessage message = new EmailMessage(); message.From = item.BizFormInfo.FormSendFromEmail; message.Recipients = resolver.ResolveMacros(item.BizFormInfo.FormSendToEmail); message.Subject = resolver.ResolveMacros(item.BizFormInfo.FormEmailSubject); message.Body = URLHelper.MakeLinksAbsolute(body); message.EmailFormat = EmailFormatEnum.Html; for (int i = 1; i <= attachmentsCount; i++) { Attachment attachment = GetAttachment(item.GetStringValue("File" + i, string.Empty)); if (attachment != null) { message.Attachments.Add(attachment); } } EmailSender.SendEmail(message); } }
private void SendFormEmail(BizFormItem item) { if (item.BizFormInfo != null) { MacroResolver resolver = MacroContext.CurrentResolver.CreateChild(); resolver.SetAnonymousSourceData(item); resolver.Settings.EncodeResolvedValues = true; resolver.Culture = CultureHelper.GetPreferredCulture(); string body = DataHelper.GetNotEmpty(item.BizFormInfo.FormEmailTemplate, string.Empty); body = resolver.ResolveMacros(body); EmailMessage message = new EmailMessage(); message.From = item.BizFormInfo.FormSendFromEmail; message.Recipients = resolver.ResolveMacros(item.BizFormInfo.FormSendToEmail); message.Subject = resolver.ResolveMacros(item.BizFormInfo.FormEmailSubject); message.Body = URLHelper.MakeLinksAbsolute(body); message.EmailFormat = EmailFormatEnum.Html; EmailSender.SendEmail(message); } }
/// <summary> /// Fills dropdown with data. /// </summary> /// <param name="parentID">Identifier of node which children you want to add</param> /// <param name="level">Level of indentation</param> private void FillDropDown(int parentID, int level) { if (GroupedCategories != null) { List <DataRowView> gCategory = GroupedCategories.GetGroup(parentID); if (gCategory != null) { var categoryTypeInfo = CategoryInfo.TypeInfo; foreach (DataRowView drCategory in gCategory) { if (!ExcludedItems.Contains(ValidationHelper.GetInteger(drCategory[categoryTypeInfo.IDColumn], 0))) { string name = ResHelper.LocalizeString(drCategory[CategoryInfo.Generalized.DisplayNameColumn].ToString()); int categoryId = ValidationHelper.GetInteger(drCategory[categoryTypeInfo.IDColumn], 0); List <DataRowView> objectGroup = ((!ShowEmptyCategories || ShowObjects) && GroupedObjects != null) ? GroupedObjects.GetGroup(drCategory[categoryTypeInfo.IDColumn]) : null; List <DataRowView> childCategoryGroup = !ShowEmptyCategories?GroupedCategories.GetGroup(categoryId) : null; // Check for empty categories except the root if ((level == 0) || ShowEmptyCategories || ((objectGroup != null) && (objectGroup.Count > 0)) || ((childCategoryGroup != null) && (childCategoryGroup.Count > 0))) { bool enabled = true; // Resolve Enabled condition if (!String.IsNullOrEmpty(EnabledCondition)) { MacroResolver.SetAnonymousSourceData(drCategory); enabled = ValidationHelper.GetBoolean(MacroResolver.ResolveMacros(EnabledCondition), true); } string indentation = String.Empty; if ((level > 0) || ShowRoot) { // Create indentation for specified level indentation = String.Concat(Enumerable.Repeat(SubItemPrefix, ShowRoot ? level : level - 1)); string value = ((level == 0) && (RootValue > 0) ? RootValue : categoryId).ToString(); // Prevent category list item to be selected by ID when selecting object if (ShowObjects) { value = "cat_" + value; } // Insert category ListItem listItem = new ListItem(indentation + ResHelper.LocalizeString(name), value); if (ShowObjects || DisabledItems.Contains(categoryId) || !enabled) { listItem.Attributes.Add("style", DisabledItemStyle); listItem.Attributes.Add("disabled", "disabled"); } else { if (!firstItem && String.IsNullOrEmpty(mSelectedValue)) { SetItem(parentID, value); } } drpCategory.Items.Add(listItem); } // Go deeper FillDropDown(categoryId, level + 1); // Insert all child objects if needed if (ShowObjects && !DataHelper.DataSourceIsEmpty(objectGroup)) { if (objectGroup != null) { indentation += SubItemPrefix; foreach (DataRowView childObject in objectGroup) { string text = indentation + ResHelper.LocalizeString(childObject[ObjectInfo.Generalized.DisplayNameColumn].ToString()); string objValue = childObject[ObjectInfo.TypeInfo.IDColumn].ToString(); drpCategory.Items.Add(new ListItem(text, objValue)); if (!firstItem && String.IsNullOrEmpty(mSelectedValue)) { SetItem(parentID, objValue); } } } } } } } } } }
/// <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 (errorMessage == string.Empty) { try { codeName = GetSafeCodeName(); codeName = GetUniqueCodeName(codeName); GroupInfo group = new GroupInfo(); group.GroupDisplayName = txtDisplayName.Text; group.GroupName = codeName; group.GroupDescription = txtDescription.Text; group.GroupAccess = GetGroupAccess(); group.GroupSiteID = mSiteId; group.GroupApproveMembers = GetGroupApproveMembers(); // 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.DisplayName = "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(ResolveUrl(DocumentURLProvider.GetUrl(RedirectToURL))); } // After registration message if ((RequireApproval) && (!CurrentUserIsAdmin())) { ShowConfirmation(SuccessfullRegistrationWaitingForApprovalText); // Send approval email to admin if (!String.IsNullOrEmpty(SendWaitingForApprovalEmailTo)) { // Create the message EmailTemplateInfo eti = EmailTemplateProvider.GetEmailTemplate("Groups.WaitingForApproval", SiteContext.CurrentSiteName); if (eti != null) { EmailMessage message = new EmailMessage(); if (String.IsNullOrEmpty(eti.TemplateFrom)) { message.From = SettingsKeyInfoProvider.GetStringValue(SiteContext.CurrentSiteName + ".CMSSendEmailNotificationsFrom"); } else { message.From = eti.TemplateFrom; } MacroResolver resolver = MacroContext.CurrentResolver; resolver.SetAnonymousSourceData(group); resolver.SetNamedSourceData("Group", group); message.Recipients = SendWaitingForApprovalEmailTo; message.Subject = resolver.ResolveMacros(eti.TemplateSubject); message.Body = resolver.ResolveMacros(eti.TemplateText); resolver.Settings.EncodeResolvedValues = false; message.PlainTextBody = resolver.ResolveMacros(eti.TemplatePlainText); // Send the message using email engine EmailSender.SendEmail(message); } } } else { string groupPath = SettingsKeyInfoProvider.GetStringValue(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, null); } } else { // Display error message ShowError(errorMessage); } }
/// <summary> /// Saves the data. /// </summary> /// <param name="newsletterName">Newsletter name</param> /// <param name="sb">Subscriber</param> private bool Save(string newsletterName, SubscriberInfo sb) { bool toReturn = false; int siteId = SiteContext.CurrentSiteID; // Check if sunscriber info object exists if ((sb == null) || string.IsNullOrEmpty(newsletterName)) { return(false); } // Get nesletter info NewsletterInfo news = NewsletterInfoProvider.GetNewsletterInfo(newsletterName, siteId); if (news != null) { // Init webpart resolver object[] data = new object[3]; data[0] = news; data[1] = sb; MacroResolver resolver = ContextResolver; resolver.SetNamedSourceData("Newsletter", news); resolver.SetNamedSourceData("Subscriber", sb); if (AllowUserSubscribers && isAuthenticated) { data[2] = CurrentUser; resolver.SetNamedSourceData("User", CurrentUser); } resolver.SetAnonymousSourceData(data); try { // Check if subscriber is not allready subscribed if (!SubscriberInfoProvider.IsSubscribed(sb.SubscriberGUID, news.NewsletterGUID, siteId)) { toReturn = true; // Subscribe to the site SubscriberInfoProvider.Subscribe(sb.SubscriberID, news.NewsletterID, DateTime.Now, SendConfirmationEmail); if (!chooseMode) { // Display message about successful subscription lblInfo.Visible = true; lblInfo.Text = SubscriptionConfirmationMessage; } // Track successful subscription conversion if (!string.IsNullOrEmpty(TrackConversionName)) { string siteName = SiteContext.CurrentSiteName; if (AnalyticsHelper.AnalyticsEnabled(siteName) && AnalyticsHelper.TrackConversionsEnabled(siteName) && !AnalyticsHelper.IsIPExcluded(siteName, RequestContext.UserHostAddress)) { // Log conversion HitLogProvider.LogConversions(siteName, LocalizationContext.PreferredCultureCode, TrackConversionName, 0, ConversionValue); } } // Log newsletter subscription activity if double opt-in is not required if (!news.NewsletterEnableOptIn) { Activity activity = new ActivityNewsletterSubscribing(sb, news, AnalyticsContext.ActivityEnvironmentVariables); activity.Log(); } } else { lblInfo.Visible = true; string message = null; if (string.IsNullOrEmpty(MessageForAlreadySubscribed)) { if (!chooseMode) { message = GetString("NewsletterSubscription.SubscriberIsAlreadySubscribed"); } else { message = string.Format("{0} {1}.<br />", GetString("NewsletterSubscription.SubscriberIsAlreadySubscribedXY"), HTMLHelper.HTMLEncode(ResHelper.LocalizeString(news.NewsletterDisplayName))); } } else { message = MessageForAlreadySubscribed; } // Info message - subscriber is allready in site if (!chooseMode) { lblInfo.Text = message; } else { lblInfo.Text += message; } } } catch (Exception ex) { lblError.Visible = true; lblError.Text = ex.Message; } } else { lblError.Visible = true; lblError.Text = GetString("NewsletterSubscription.NewsletterDoesNotExist"); } return(toReturn); }
/// <summary> /// Loads fields to drop down control. /// </summary> private void SetupFieldSelector(string selectedValue, bool forceReload) { if (forceReload || (fieldSelector.Items.Count == 0)) { // Clear dropdown list fieldSelector.Items.Clear(); // Get data class info string className = ValidationHelper.GetString(classSelector.Value, null); if (!String.IsNullOrEmpty(className) && (className != SpecialFieldValue.NONE.ToString())) { // Get fields of type file var dci = DataClassInfoProvider.GetDataClassInfo(className); var fi = FormHelper.GetFormInfo(dci.ClassName, false); var ffi = fi.GetFields(true, true); // Filter fields if (!String.IsNullOrEmpty(FieldCondition)) { MacroResolver resolver = MacroResolver.GetInstance(); var visibleFields = new List <FormFieldInfo>(); foreach (FormFieldInfo field in ffi) { resolver.SetAnonymousSourceData(field); bool result = ValidationHelper.GetBoolean(resolver.ResolveMacros(FieldCondition), true); if (result) { visibleFields.Add(field); } } ffi = visibleFields; } if (ffi.Count > 0) { // Fill dropdown list with fields var list = ffi.Select(t => new Tuple <string, string>(!String.IsNullOrEmpty(t.GetPropertyValue(FormFieldPropertyEnum.FieldCaption, ContextResolver)) ? t.GetPropertyValue(FormFieldPropertyEnum.FieldCaption, ContextResolver) : t.Name, t.Guid.ToString())).OrderBy(t => t.Item1); foreach (var item in list) { fieldSelector.Items.Add(new ListItem(item.Item1, item.Item2)); } if (!String.IsNullOrEmpty(selectedValue) && (fieldSelector.Items.FindByValue(selectedValue) != null) && !forceReload) { // Selected value from database fieldSelector.SelectedValue = selectedValue; } else { // Select first item if nothing selected or class name was changed fieldSelector.SelectedIndex = 0; } fieldSelector.Enabled = true; } else { fieldSelector.Enabled = false; } pnlFields.Visible = true; } else { // Hide field selector for (none) option pnlFields.Visible = false; } } }
/// <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; string pwd = string.Empty; string confPassword = string.Empty; string educationLevel = String.Empty; string interestArea = String.Empty; string industry = String.Empty; string referralSource = 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); userName = emailValue; } // If user name and e-mail aren't filled stop processing and display error. if (string.IsNullOrEmpty(userName) && String.IsNullOrEmpty(emailValue)) { formUser.StopProcessing = true; lblError.Visible = true; lblError.Text = GetString("customregistrationform.usernameandemail"); return; } else { formUser.Data.SetValue("UserName", userName); } //check if email is valid if (!ValidationHelper.IsEmail(txtEmail.Text.ToLowerCSafe())) { lblError.Visible = true; lblError.Text = GetString("Webparts_Membership_RegistrationForm.EmailIsNotValid"); return; } 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); } FormEngineUserControl txtPwd = formUser.FieldControls["UserPassword"]; if (txtPwd != null) { pwd = ValidationHelper.GetString(txtPwd.Value, String.Empty); } FormEngineUserControl txtConfPassword = formUser.FieldControls["ReenterPassword"]; if (txtConfPassword != null) { confPassword = ValidationHelper.GetString(txtConfPassword.Value, String.Empty); } if (string.IsNullOrEmpty(pwd) || string.IsNullOrEmpty(confPassword)) { lblError.Visible = true; lblError.Text = "please enter password with confirmation"; return; } if (pwd != confPassword) { lblError.Visible = true; lblError.Text = "Password doesn't match"; return; } if (validateFields(formUser.FieldControls["UserPassword"].Value.ToString())) { // 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); var customerToken = PersonifyRegistered(emailValue, password, firstName, lastName); if (string.IsNullOrEmpty(customerToken)) { UserInfoProvider.DeleteUser(ui); return; } else { var roles = GetImsroles(customerToken); string groupslist = ""; if (roles.Length > 0) { foreach (string s in roles) { if (s.Length > 0) { groupslist += s + ","; } } } //we need this mispelling. groupslist += "peronifyUser" + ","; new LoginUsertokentico().AddUserToRole(ui, groupslist, true, false); } // 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 (ui.Enabled) { if (this.AutoLoginAfterRegistration) { Session["UserName"] = userName; Session["Password"] = password; Session["RememberMe"] = true; Session["RetryCount"] = null; if (this.Request.QueryString["ReturnURL"] != null) { var returnURL = this.Request.QueryString["ReturnURL"]; Session["ReturnURL"] = returnURL; } else if (!String.IsNullOrEmpty(this.RedirectToURL)) { var returnURL = this.Request.QueryString["ReturnURL"]; Session["ReturnURL"] = returnURL; } Response.Redirect("~/sso/ssohandler.aspx", true); } else if (!String.IsNullOrEmpty(this.LoginURL)) { Response.Redirect(string.Format(this.LoginURL, userName), true); } else if (!String.IsNullOrEmpty(this.RedirectToURL)) { Response.Redirect(this.RedirectToURL, true); } } #endregion lblError.Visible = false; } } }
/// <summary> /// Sends e-mail to all attendees. /// </summary> protected void Send() { // Check 'Modify' permission if (!CheckPermissions("cms.eventmanager", "Modify")) { return; } txtSenderName.Text = txtSenderName.Text.Trim(); txtSenderEmail.Text = txtSenderEmail.Text.Trim(); txtSubject.Text = txtSubject.Text.Trim(); // Validate the fields string errorMessage = new Validator() .NotEmpty(txtSenderName.Text, GetString("Events_SendEmail.EmptySenderName")) .NotEmpty(txtSenderEmail.Text, GetString("Events_SendEmail.EmptySenderEmail")) .MatchesCondition(txtSenderEmail, input => input.IsValid(), GetString("Events_SendEmail.InvalidEmailFormat")) .NotEmpty(txtSubject.Text, GetString("Events_SendEmail.EmptyEmailSubject")) .Result; if (!String.IsNullOrEmpty(errorMessage)) { ShowError(errorMessage); return; } string subject = txtSubject.Text; string emailBody = htmlEmail.ResolvedValue; // Get event node data TreeProvider mTree = new TreeProvider(); DocTreeNode node = mTree.SelectSingleNode(EventID); if (node != null && CMSString.Equals(node.NodeClassName, "cms.bookingevent", true)) { // Initialize macro resolver MacroResolver resolver = MacroResolver.GetInstance(); resolver.Settings.KeepUnresolvedMacros = true; resolver.SetAnonymousSourceData(node); // Add named source data resolver.SetNamedSourceData("Event", node); // Event date string macro DateTime eventDate = ValidationHelper.GetDateTime(node.GetValue("EventDate"), DateTimeHelper.ZERO_TIME); DateTime eventEndDate = ValidationHelper.GetDateTime(node.GetValue("EventEndDate"), DateTimeHelper.ZERO_TIME); bool isAllDay = ValidationHelper.GetBoolean(node.GetValue("EventAllDay"), false); resolver.SetNamedSourceData("eventdatestring", EventProvider.GetEventDateString(eventDate, eventEndDate, isAllDay, TimeZoneHelper.GetTimeZoneInfo(SiteContext.CurrentSite), SiteContext.CurrentSiteName), false); // Resolve e-mail body and subject macros and make links absolute emailBody = resolver.ResolveMacros(emailBody); emailBody = URLHelper.MakeLinksAbsolute(emailBody); subject = TextHelper.LimitLength(resolver.ResolveMacros(subject), 450); // EventSendEmail manages sending e-mails to all attendees EventSendEmail ese = new EventSendEmail(EventID, SiteContext.CurrentSiteName, subject, emailBody, txtSenderName.Text.Trim(), txtSenderEmail.Text.Trim()); ShowConfirmation(GetString("Events_SendEmail.EmailSent")); } }
/// <summary> /// Saves the data. /// </summary> private bool Save(string newsletterName, ContactInfo contact) { bool toReturn = false; if ((contact == null) || string.IsNullOrEmpty(newsletterName)) { return(false); } // Get newsletter info var newsletter = NewsletterInfoProvider.GetNewsletterInfo(newsletterName, SiteContext.CurrentSiteID); if (newsletter != null) { try { // Check if subscriber is not marketable if (!mSubscriptionService.IsMarketable(contact, newsletter)) { toReturn = true; if (!AllowUserSubscribersIsAuthenticated || String.IsNullOrEmpty(CurrentUser.Email)) { if (!SaveDataForm()) { return(false); } } mSubscriptionService.Subscribe(contact, newsletter, new SubscribeSettings() { SendConfirmationEmail = SendConfirmationEmail, AllowOptIn = true, RemoveUnsubscriptionFromNewsletter = true, RemoveAlsoUnsubscriptionFromAllNewsletters = true, SourceSubscriber = subscriber }); if (!mChooseMode) { // Display message about successful subscription lblInfo.Visible = true; lblInfo.Text = SubscriptionConfirmationMessage; } // Track successful subscription conversion if (!string.IsNullOrEmpty(TrackConversionName)) { string siteName = SiteContext.CurrentSiteName; if (AnalyticsHelper.AnalyticsEnabled(siteName) && Service.Resolve <IAnalyticsConsentProvider>().HasConsentForLogging() && !AnalyticsHelper.IsIPExcluded(siteName, RequestContext.UserHostAddress)) { // Log conversion HitLogProvider.LogConversions(siteName, LocalizationContext.PreferredCultureCode, TrackConversionName, 0, ConversionValue); } } } else { // Init web part resolver object[] data = new object[3]; data[0] = newsletter; data[1] = subscriber; MacroResolver resolver = ContextResolver; resolver.SetNamedSourceData("Newsletter", newsletter); resolver.SetNamedSourceData("Subscriber", subscriber); if (AllowUserSubscribersIsAuthenticated) { data[2] = CurrentUser; resolver.SetNamedSourceData("User", CurrentUser); } resolver.SetAnonymousSourceData(data); lblInfo.Visible = true; string message = null; if (string.IsNullOrEmpty(MessageForAlreadySubscribed)) { if (!mChooseMode) { message = GetString("NewsletterSubscription.SubscriberIsAlreadySubscribed"); } else { message = string.Format("{0} {1}.<br />", GetString("NewsletterSubscription.SubscriberIsAlreadySubscribedXY"), HTMLHelper.HTMLEncode(newsletter.NewsletterDisplayName)); } } else { message = MessageForAlreadySubscribed; } // Info message - subscriber is already in site if (!mChooseMode) { lblInfo.Text = message; } else { lblInfo.Text += message; } } } catch (Exception ex) { lblError.Visible = true; lblError.Text = ex.Message; } } else { lblError.Visible = true; lblError.Text = GetString("NewsletterSubscription.NewsletterDoesNotExist"); } return(toReturn); }
/// <summary> /// Send notifications. /// </summary> private void SentNotification() { if (SendNotificationMessage || SendNotificationEmail) { // Get e-mail template EmailTemplateInfo template = null; // Get message subject string messageSubject = null; switch (action) { case FriendsActionEnum.Approve: template = EmailTemplateProvider.GetEmailTemplate("Friends.Approve", SiteContext.CurrentSiteName); messageSubject = ApprovedCaption; break; case FriendsActionEnum.Reject: template = EmailTemplateProvider.GetEmailTemplate("Friends.Reject", SiteContext.CurrentSiteName); messageSubject = RejectedCaption; break; } if (template == null) { return; } // Get user infos UserInfo recipient = UserInfoProvider.GetFullUserInfo(friendship.FriendUserID); UserInfo sender = UserInfoProvider.GetFullUserInfo(friendship.FriendRequestedUserID); MacroResolver resolver = MacroContext.CurrentResolver; resolver.SetAnonymousSourceData(sender, recipient, friendship); resolver.SetNamedSourceData("Sender", sender); resolver.SetNamedSourceData("Recipient", recipient); resolver.SetNamedSourceData("Friendship", friendship); resolver.SetNamedSourceData("FORMATTEDSENDERNAME", Functions.GetFormattedUserName(sender.UserName), false); if (SendNotificationMessage) { // Set message info object MessageInfo mi = new MessageInfo(); mi.MessageLastModified = DateTime.Now; mi.MessageSent = DateTime.Now; mi.MessageRecipientUserID = recipient.UserID; mi.MessageRecipientNickName = TextHelper.LimitLength(Functions.GetFormattedUserName(recipient.UserName, recipient.FullName, recipient.UserNickName, true), 200); mi.MessageSenderUserID = friendship.FriendRequestedUserID; mi.MessageSenderNickName = TextHelper.LimitLength(Functions.GetFormattedUserName(sender.UserName, sender.FullName, sender.UserNickName, true), 200); mi.MessageSenderDeleted = true; mi.MessageSubject = TextHelper.LimitLength(resolver.ResolveMacros(template.TemplateSubject), 200); mi.MessageBody = resolver.ResolveMacros(template.TemplatePlainText); MessageInfoProvider.SetMessageInfo(mi); } if (SendNotificationEmail && !String.IsNullOrEmpty(recipient.Email) && !String.IsNullOrEmpty(sender.Email)) { // Send e-mail EmailMessage message = new EmailMessage(); message.EmailFormat = EmailFormatEnum.Default; message.Recipients = Functions.GetFormattedUserName(recipient.UserName, true) + " <" + recipient.Email + ">"; message.From = Functions.GetFormattedUserName(sender.UserName, true) + " <" + sender.Email + ">"; message.Subject = messageSubject; EmailSender.SendEmailWithTemplateText(SiteContext.CurrentSiteName, message, template, resolver, false); } } }
/// <summary> /// Initializes the control properties. /// </summary> protected void SetupControl() { if (StopProcessing) { // Do nothing } else { if (!RequestHelper.IsPostBack()) { // If user is public if (MembershipContext.AuthenticatedUser.IsPublic()) { // Get logon URL string logonUrl = AuthenticationHelper.GetSecuredAreasLogonPage(SiteContext.CurrentSiteName); logonUrl = DataHelper.GetNotEmpty(LoginURL, logonUrl); // Create redirect URL logonUrl = UrlResolver.ResolveUrl(logonUrl) + "?ReturnURL=" + HttpUtility.UrlEncode(RequestContext.CurrentURL); URLHelper.Redirect(logonUrl); } else { // Get invitation by GUID Guid invitationGuid = QueryHelper.GetGuid("invitationguid", Guid.Empty); if (invitationGuid != Guid.Empty) { InvitationInfo invitation = InvitationInfoProvider.GetInvitationInfo(invitationGuid); if (invitation != null) { // Check if invitation is valid if ((invitation.InvitationValidTo == DateTimeHelper.ZERO_TIME) || (invitation.InvitationValidTo >= DateTime.Now)) { GroupInfo group = GroupInfoProvider.GetGroupInfo(invitation.InvitationGroupID); if (group != null) { // Check whether current user is the user who should be invited if ((invitation.InvitedUserID > 0) && (invitation.InvitedUserID != MembershipContext.AuthenticatedUser.UserID)) { lblInfo.CssClass = "InvitationErrorLabel"; lblInfo.Text = InvitationIsNotValid; lblInfo.Visible = true; return; } // If user was invited by e-mail if (invitation.InvitedUserID == 0) { invitation.InvitedUserID = MembershipContext.AuthenticatedUser.UserID; } if (!GroupMemberInfoProvider.IsMemberOfGroup(invitation.InvitedUserID, invitation.InvitationGroupID)) { // Create group member info object GroupMemberInfo groupMember = new GroupMemberInfo(); groupMember.MemberInvitedByUserID = invitation.InvitedByUserID; groupMember.MemberUserID = MembershipContext.AuthenticatedUser.UserID; groupMember.MemberGroupID = invitation.InvitationGroupID; groupMember.MemberJoined = DateTime.Now; // Set proper status depending on grouo settings switch (group.GroupApproveMembers) { // Only approved members can join case GroupApproveMembersEnum.ApprovedCanJoin: groupMember.MemberStatus = GroupMemberStatus.WaitingForApproval; lblInfo.Text = MemberWaiting.Replace("##GROUPNAME##", HTMLHelper.HTMLEncode(group.GroupDisplayName)); break; // Only invited members case GroupApproveMembersEnum.InvitedWithoutApproval: // Any site members can join case GroupApproveMembersEnum.AnyoneCanJoin: groupMember.MemberApprovedWhen = DateTime.Now; groupMember.MemberStatus = GroupMemberStatus.Approved; lblInfo.Text = MemberJoined.Replace("##GROUPNAME##", HTMLHelper.HTMLEncode(group.GroupDisplayName)); break; } // Store info object to database GroupMemberInfoProvider.SetGroupMemberInfo(groupMember); // Handle sending e-mails if (SendEmailToInviter || SendDefaultGroupEmails) { UserInfo sender = UserInfoProvider.GetFullUserInfo(groupMember.MemberUserID); UserInfo recipient = UserInfoProvider.GetFullUserInfo(groupMember.MemberInvitedByUserID); if (SendEmailToInviter) { EmailTemplateInfo template = EmailTemplateProvider.GetEmailTemplate("Groups.MemberAcceptedInvitation", SiteContext.CurrentSiteName); // Resolve macros MacroResolver resolver = MacroContext.CurrentResolver; resolver.SetAnonymousSourceData(sender, recipient, group, groupMember); resolver.SetNamedSourceData("Sender", sender); resolver.SetNamedSourceData("Recipient", recipient); resolver.SetNamedSourceData("Group", group); resolver.SetNamedSourceData("GroupMember", groupMember); if (!String.IsNullOrEmpty(recipient.Email) && !String.IsNullOrEmpty(sender.Email)) { // Send e-mail EmailMessage message = new EmailMessage(); message.EmailFormat = EmailFormatEnum.Default; message.Recipients = recipient.Email; message.From = SettingsKeyInfoProvider.GetValue(SiteContext.CurrentSiteName + ".CMSNoreplyEmailAddress"); EmailSender.SendEmailWithTemplateText(SiteContext.CurrentSiteName, message, template, resolver, false); } } if (SendDefaultGroupEmails) { // Send join or leave notification if (group.GroupSendJoinLeaveNotification && (groupMember.MemberStatus == GroupMemberStatus.Approved)) { GroupMemberInfoProvider.SendNotificationMail("Groups.MemberJoin", SiteContext.CurrentSiteName, groupMember, true); GroupMemberInfoProvider.SendNotificationMail("Groups.MemberJoinedConfirmation", SiteContext.CurrentSiteName, groupMember, false); } // Send 'waiting for approval' notification if (group.GroupSendWaitingForApprovalNotification && (groupMember.MemberStatus == GroupMemberStatus.WaitingForApproval)) { GroupMemberInfoProvider.SendNotificationMail("Groups.MemberWaitingForApproval", SiteContext.CurrentSiteName, groupMember, true); GroupMemberInfoProvider.SendNotificationMail("Groups.MemberJoinedWaitingForApproval", SiteContext.CurrentSiteName, groupMember, false); } } } // Delete all invitations to specified group for specified user (based on e-mail or userId) string whereCondition = "InvitationGroupID = " + invitation.InvitationGroupID + " AND (InvitedUserID=" + MembershipContext.AuthenticatedUser.UserID + " OR InvitationUserEmail = N'" + SqlHelper.GetSafeQueryString(MembershipContext.AuthenticatedUser.Email, false) + "')"; InvitationInfoProvider.DeleteInvitations(whereCondition); } else { lblInfo.Text = UserIsAlreadyMember.Replace("##GROUPNAME##", HTMLHelper.HTMLEncode(group.GroupDisplayName)); lblInfo.CssClass = "InvitationErrorLabel"; // Delete this invitation InvitationInfoProvider.DeleteInvitationInfo(invitation); } } else { lblInfo.Text = GroupNoLongerExists; lblInfo.CssClass = "InvitationErrorLabel"; // Delete this invitation InvitationInfoProvider.DeleteInvitationInfo(invitation); } } else { lblInfo.Text = InvitationIsNotValid; lblInfo.CssClass = "InvitationErrorLabel"; // Delete this invitation InvitationInfoProvider.DeleteInvitationInfo(invitation); } } else { lblInfo.Text = InvitationNoLongerExists; lblInfo.CssClass = "InvitationErrorLabel"; } lblInfo.Visible = true; } else { // Hide control if invitation GUID isn't set Visible = false; } } } } }
/// <summary> /// Send e-mail to administrator about new registration. /// </summary> /// <param name="administrationApproval">Indicates if administration approval is required</param> private void SendEmailToAdministrator(bool administrationApproval) { EmailTemplateInfo template = null; if (administrationApproval) { template = EmailTemplateProvider.GetEmailTemplate("Registration.Approve", SiteContext.CurrentSiteName); } else { template = EmailTemplateProvider.GetEmailTemplate("Registration.New", SiteContext.CurrentSiteName); } if (template == null) { EventLogProvider.LogEvent(EventType.ERROR, "RegistrationForm", "GetEmailTemplate", eventUrl: RequestContext.RawURL); } else { // E-mail template ok string from = EmailHelper.GetSender(template, (!String.IsNullOrEmpty(FromAddress)) ? FromAddress : SettingsKeyInfoProvider.GetStringValue(SiteContext.CurrentSiteName + ".CMSNoreplyEmailAddress")); if (!String.IsNullOrEmpty(from)) { // Prepare macro replacements string[,] replacements = new string[4, 2]; replacements[0, 0] = "firstname"; replacements[0, 1] = RegisteredUser.FirstName; replacements[1, 0] = "lastname"; replacements[1, 1] = RegisteredUser.LastName; replacements[2, 0] = "email"; replacements[2, 1] = RegisteredUser.Email; replacements[3, 0] = "username"; replacements[3, 1] = RegisteredUser.UserName; // Set resolver MacroResolver resolver = MacroContext.CurrentResolver; resolver.SetNamedSourceData(replacements); resolver.Settings.EncodeResolvedValues = true; // Add user info data resolver.SetAnonymousSourceData(new object[1] { RegisteredUser }); // Email message EmailMessage email = new EmailMessage(); email.EmailFormat = EmailFormatEnum.Default; email.Recipients = AdministratorEmail; // Get e-mail sender and subject from template, if used email.From = from; email.Body = resolver.ResolveMacros(template.TemplateText); resolver.Settings.EncodeResolvedValues = false; email.PlainTextBody = resolver.ResolveMacros(template.TemplatePlainText); string emailSubject = EmailHelper.GetSubject(template, GetString("RegistrationForm.EmailSubject")); 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(SiteContext.CurrentSiteName, email, true); } catch { EventLogProvider.LogEvent(EventType.ERROR, "Membership", "RegistrationApprovalEmail"); } } else { EventLogProvider.LogEvent(EventType.ERROR, "RegistrationApproval", "EmailSenderNotSpecified"); } } }
/// <summary> /// Send notifications. /// </summary> private void SentNotification() { if (SendNotificationMessage || SendNotificationEmail) { // Get e-mail template EmailTemplateInfo template = null; // Get message subject string messageSubject = null; switch (action) { case FriendsActionEnum.Approve: template = EmailTemplateProvider.GetEmailTemplate("Friends.Approve", SiteContext.CurrentSiteName); messageSubject = ApprovedCaption; break; case FriendsActionEnum.Reject: template = EmailTemplateProvider.GetEmailTemplate("Friends.Reject", SiteContext.CurrentSiteName); messageSubject = RejectedCaption; break; } if (template == null) { return; } // Get user infos UserInfo recipient = UserInfoProvider.GetFullUserInfo(friendship.FriendUserID); UserInfo sender = UserInfoProvider.GetFullUserInfo(friendship.FriendRequestedUserID); MacroResolver resolver = MacroContext.CurrentResolver; resolver.SetAnonymousSourceData(sender, recipient, friendship); resolver.SetNamedSourceData("Sender", sender); resolver.SetNamedSourceData("Recipient", recipient); resolver.SetNamedSourceData("Friendship", friendship); string[,] replacements = new string[1, 2]; replacements[0, 0] = "FORMATTEDSENDERNAME"; replacements[0, 1] = Functions.GetFormattedUserName(sender.UserName); resolver.SetNamedSourceData(replacements); if (SendNotificationMessage) { // Set message info object MessageInfo mi = new MessageInfo(); mi.MessageLastModified = DateTime.Now; mi.MessageSent = DateTime.Now; mi.MessageRecipientUserID = recipient.UserID; mi.MessageRecipientNickName = TextHelper.LimitLength(Functions.GetFormattedUserName(recipient.UserName, recipient.FullName, recipient.UserNickName, true), 200); mi.MessageSenderUserID = friendship.FriendRequestedUserID; mi.MessageSenderNickName = TextHelper.LimitLength(Functions.GetFormattedUserName(sender.UserName, sender.FullName, sender.UserNickName, true), 200); mi.MessageSenderDeleted = true; mi.MessageSubject = TextHelper.LimitLength(resolver.ResolveMacros(template.TemplateSubject), 200); mi.MessageBody = resolver.ResolveMacros(template.TemplatePlainText); MessageInfoProvider.SetMessageInfo(mi); } if (SendNotificationEmail && !String.IsNullOrEmpty(recipient.Email) && !String.IsNullOrEmpty(sender.Email)) { // Send e-mail EmailMessage message = new EmailMessage(); message.Recipients = Functions.GetFormattedUserName(recipient.UserName, true) + " <" + recipient.Email + ">"; message.From = EmailHelper.GetSender(template, Functions.GetFormattedUserName(sender.UserName, true) + " <" + sender.Email + ">"); message.Subject = EmailHelper.GetSubject(template, messageSubject); message.CcRecipients = template.TemplateCc; message.BccRecipients = template.TemplateBcc; message.EmailFormat = EmailFormatEnum.Default; // Replace replacements, resolve macros resolver.Settings.EncodeResolvedValues = true; message.Body = resolver.ResolveMacros(template.TemplateText); // Do not encode plain text body and subject resolver.Settings.EncodeResolvedValues = false; message.Subject = resolver.ResolveMacros(message.Subject); message.PlainTextBody = resolver.ResolveMacros(template.TemplatePlainText); EmailHelper.ResolveMetaFileImages(message, template.TemplateID, EmailTemplateInfo.OBJECT_TYPE, ObjectAttachmentsCategories.TEMPLATE); EmailSender.SendEmail(SiteContext.CurrentSiteName, message); } } }
/// <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 = AnalyticsHelper.Campaign; 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); // 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); resolver.Settings.EncodeResolvedValues = true; #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) { // Retrieve 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] = AuthenticationHelper.GetRegistrationApprovalUrl(ApprovalPage, ui.UserGUID, siteName, NotifyAdministrator, contactId); 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 resolver.SetNamedSourceData(replacements); // Email message EmailMessage email = new EmailMessage(); email.EmailFormat = EmailFormatEnum.Default; email.Recipients = ui.Email; email.From = EmailHelper.GetSender(template, SettingsKeyInfoProvider.GetStringValue(siteName + ".CMSNoreplyEmailAddress")); email.Body = resolver.ResolveMacros(template.TemplateText); resolver.Settings.EncodeResolvedValues = false; 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; if (requiresAdminApprove) { 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 { 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; // Set resolver resolver.SetNamedSourceData(replacements); EmailMessage message = new EmailMessage(); message.EmailFormat = EmailFormatEnum.Default; message.From = EmailHelper.GetSender(mEmailTemplate, FromAddress); message.Recipients = ToAddress; message.Body = resolver.ResolveMacros(mEmailTemplate.TemplateText); 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.TrackConversionsEnabled(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")) { 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; } }