Ejemplo n.º 1
0
 /// <summary>
 /// Creates customer - current contact binding if does not exist and logs customer registration activity.
 /// </summary>
 /// <param name="customer">Customer to assign to the current contact.</param>
 private void AssignCustomerToContact(CustomerInfo customer)
 {
     if (ContactID > 0)
     {
         ModuleCommands.OnlineMarketingCreateRelation(customer.CustomerID, MembershipType.ECOMMERCE_CUSTOMER, ContactID);
     }
 }
    /// <summary>
    /// Merge contact with customer and creates relation between these two.
    /// </summary>
    /// <param name="customerInfo">Registered customer to merge with proper contact</param>
    private void CreateContactRelation(CustomerInfo customerInfo)
    {
        int contactId = ModuleCommands.OnlineMarketingGetCurrentContactID();

        ModuleCommands.OnlineMarketingCreateRelation(customerInfo.CustomerID, MembershipType.ECOMMERCE_CUSTOMER, contactId);
        ModuleCommands.OnlineMarketingUpdateContactFromExternalData(
            customerInfo,
            DataClassInfoProvider.GetDataClassInfo(CustomerInfo.TYPEINFO.ObjectClassName).ClassContactOverwriteEnabled,
            contactId);
    }
Ejemplo n.º 3
0
    /// <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))
            {
                ShowError(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 another user with this user name (which is effectively 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))
            {
                ShowError(GetString("Webparts_Membership_RegistrationForm.UserAlreadyExists").Replace("%%name%%", HTMLHelper.HTMLEncode(txtEmail.Text)));
                return;
            }

            // Check whether password is same
            if (passStrength.Text != txtConfirmPassword.Text)
            {
                ShowError(GetString("Webparts_Membership_RegistrationForm.PassworDoNotMatch"));
                return;
            }

            if ((PasswordMinLength > 0) && (passStrength.Text.Length < PasswordMinLength))
            {
                ShowError(String.Format(GetString("Webparts_Membership_RegistrationForm.PasswordMinLength"), PasswordMinLength));
                return;
            }

            if (!passStrength.IsValid())
            {
                ShowError(AuthenticationHelper.GetPolicyViolationMessage(SiteContext.CurrentSiteName));
                return;
            }

            if ((!txtEmail.IsValid()) || (txtEmail.Text.Length > EMAIL_MAX_LENGTH))
            {
                ShowError(String.Format(GetString("Webparts_Membership_RegistrationForm.EmailIsNotValid"), EMAIL_MAX_LENGTH));
                return;
            }

            #endregion


            #region "Captcha"

            // Check if captcha is required and verify captcha text
            if (DisplayCaptcha && !scCaptcha.IsValid())
            {
                // Display error message if catcha text is not valid
                ShowError(GetString("Webparts_Membership_RegistrationForm.captchaError"));
                return;
            }

            #endregion


            #region "User properties"

            var userEmail = txtEmail.Text.Trim();

            ui = new UserInfo();
            ui.PreferredCultureCode = "";
            ui.Email          = userEmail;
            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)
            var plainUserName = userEmail;
            ui.UserName = plainUserName;

            // Check if the given email can be used as user name
            if (!ValidationHelper.IsUserName(plainUserName))
            {
                ShowError(String.Format(GetString("Webparts_Membership_RegistrationForm.UserNameNotValid"), HTMLHelper.HTMLEncode(plainUserName)));
                return;
            }

            // Ensure site prefixes
            if (UserInfoProvider.UserNameSitePrefixEnabled(siteName))
            {
                ui.UserName = UserInfoProvider.EnsureSitePrefixUserName(plainUserName, si);
            }

            ui.Enabled         = EnableUserAfterRegistration;
            ui.UserURLReferrer = CookieHelper.GetValue(CookieName.UrlReferrer);
            ui.UserCampaign    = Service <ICampaignService> .Entry().CampaignCode;

            ui.SiteIndependentPrivilegeLevel = 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 required
                requiresAdminApprove = SettingsKeyInfoProvider.GetBoolValue(siteName + ".CMSRegistrationAdministratorApproval");
                if (requiresAdminApprove)
                {
                    ui.Enabled = false;
                    ui.UserSettings.UserWaitingForApproval = true;
                }
            }
            else
            {
                // EnableUserAfterRegistration is overridden 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))
            {
                ShowError(GetString("Webparts_Membership_RegistrationForm.UserNameReserved").Replace("%%name%%", HTMLHelper.HTMLEncode(Functions.GetFormattedUserName(ui.UserName, true))));
                return;
            }

            if (UserInfoProvider.NameIsReserved(siteName, ui.UserNickName))
            {
                ShowError(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))
            {
                ShowError(errorMessage);
                return;
            }

            #endregion


            // Check whether email is unique if it is required
            if (!UserInfoProvider.IsEmailUnique(userEmail, siteList, 0))
            {
                ShowError(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, MembershipType.CMS_USER, contactId);
                }

                // Email message
                EmailMessage email = new EmailMessage();
                email.EmailFormat = EmailFormatEnum.Default;
                email.Recipients  = ui.Email;
                email.From        = SettingsKeyInfoProvider.GetValue(siteName + ".CMSNoreplyEmailAddress");
                email.Subject     = emailSubject;

                try
                {
                    var resolver = MembershipResolvers.GetMembershipRegistrationResolver(ui, AuthenticationHelper.GetRegistrationApprovalUrl(ApprovalPage, ui.UserGUID, siteName, NotifyAdministrator));
                    EmailSender.SendEmailWithTemplateText(siteName, email, template, resolver, true);
                }
                catch (Exception ex)
                {
                    EventLogProvider.LogException("E", "RegistrationForm - SendEmail", ex);
                    error = true;
                }
            }

            // If there was some error, user must be deleted
            if (error)
            {
                ShowError(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;
                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;
                    message.Subject     = GetString("RegistrationForm.EmailSubject");

                    try
                    {
                        MacroResolver resolver = MembershipResolvers.GetRegistrationResolver(ui);
                        EmailSender.SendEmailWithTemplateText(siteName, message, mEmailTemplate, resolver, false);
                    }
                    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)
            {
                MembershipActivityLogger.LogRegistration(ui.UserName, DocumentContext.CurrentDocument);
                // Log login activity
                if (ui.Enabled)
                {
                    MembershipActivityLogger.LogLogin(ui.UserName, DocumentContext.CurrentDocument);
                }
            }

            #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.StartsWith(".", StringComparison.Ordinal) ? "" : 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(UrlResolver.ResolveUrl(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("~", StringComparison.Ordinal) || url.StartsWith("/", StringComparison.Ordinal) || QueryHelper.ValidateHash("hash", "aliaspath"))
                    {
                        URLHelper.Redirect(UrlResolver.ResolveUrl(url));
                    }
                    // Absolute path with wrong hash
                    else
                    {
                        URLHelper.Redirect(AdministrationUrlHelper.GetErrorPageUrl("dialogs.badhashtitle", "dialogs.badhashtext"));
                    }
                }
            }

            #endregion

            lblError.Visible = false;
        }
    }
Ejemplo n.º 4
0
    /// <summary>
    /// Save subscriber.
    /// </summary>
    /// <returns>Subscriver info object</returns>
    private SubscriberInfo SaveSubscriber()
    {
        // Check if a subscriber exists first
        SubscriberInfo sb = null;

        if (AllowUserSubscribers && (MembershipContext.AuthenticatedUser != null) && AuthenticationHelper.IsAuthenticated())
        {
            sb = SubscriberInfoProvider.GetSubscriberInfo(UserInfo.OBJECT_TYPE, MembershipContext.AuthenticatedUser.UserID, SiteContext.CurrentSiteID);
        }
        else
        {
            sb = SubscriberInfoProvider.GetSubscriberInfo(txtEmail.Text, SiteContext.CurrentSiteID);
        }

        if ((sb == null) || ((chooseMode) && (sb != null)))
        {
            // Create subscriber
            if (sb == null)
            {
                sb = new SubscriberInfo();
            }

            // Handle authenticated user
            if (AllowUserSubscribers && (MembershipContext.AuthenticatedUser != null) && AuthenticationHelper.IsAuthenticated())
            {
                // Get user info and copy first name, last name or full name to new subscriber
                UserInfo ui = UserInfoProvider.GetUserInfo(MembershipContext.AuthenticatedUser.UserID);
                if (ui != null)
                {
                    if (!DataHelper.IsEmpty(ui.FirstName) && !DataHelper.IsEmpty(ui.LastName))
                    {
                        sb.SubscriberFirstName = ui.FirstName;
                        sb.SubscriberLastName  = ui.LastName;
                    }
                    else
                    {
                        sb.SubscriberFirstName = ui.FullName;
                    }
                    // Full name consists of "user " and user full name
                    sb.SubscriberFullName = new SubscriberFullNameFormater().GetUserSubscriberName(ui.FullName);
                }
                else
                {
                    return(null);
                }

                sb.SubscriberType      = UserInfo.OBJECT_TYPE;
                sb.SubscriberRelatedID = MembershipContext.AuthenticatedUser.UserID;
            }
            // Work with non-authenticated user
            else
            {
                sb.SubscriberEmail = txtEmail.Text.Trim();

                // First name
                if (DisplayFirstName)
                {
                    sb.SubscriberFirstName = txtFirstName.Text;
                }
                else
                {
                    sb.SubscriberFirstName = string.Empty;
                }

                // Last name
                if (DisplayLastName)
                {
                    sb.SubscriberLastName = txtLastName.Text;
                }
                else
                {
                    sb.SubscriberLastName = string.Empty;
                }

                // Full name
                sb.SubscriberFullName = (sb.SubscriberFirstName + " " + sb.SubscriberLastName).Trim();
            }

            // Set site ID
            sb.SubscriberSiteID = SiteContext.CurrentSiteID;

            // Check subscriber limits
            if (!SubscriberInfoProvider.LicenseVersionCheck(RequestContext.CurrentDomain, FeatureEnum.Subscribers, ObjectActionEnum.Insert))
            {
                lblError.Visible = true;
                lblError.Text    = GetString("LicenseVersionCheck.Subscribers");
                return(null);
            }

            // Save subscriber info
            SubscriberInfoProvider.SetSubscriberInfo(sb);
        }

        if (sb != null)
        {
            // Create membership between current contact and subscriber
            ModuleCommands.OnlineMarketingCreateRelation(sb.SubscriberID, MembershipType.NEWSLETTER_SUBSCRIBER, ModuleCommands.OnlineMarketingGetCurrentContactID());
        }

        // Hide all
        visibleLastName  = false;
        visibleFirstName = false;
        visibleEmail     = false;

        pnlButtonSubmit.Visible = false;
        pnlImageSubmit.Visible  = false;

        plcNwsList.Visible = false;

        // Clear the form
        txtEmail.Text     = string.Empty;
        txtFirstName.Text = string.Empty;
        txtLastName.Text  = string.Empty;

        // Return subscriber info object
        return(sb);
    }
Ejemplo n.º 5
0
    /// <summary>
    /// Sends confirmation or welcome email.
    /// </summary>
    private void SendRegistrationEmail(UserInfo ui, string password)
    {
        bool error = false;
        EmailTemplateInfo template = null;

        // 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 (ConfirmationRequired)
        {
            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 (AdminApprovalRequired)
            {
                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)
        {
            // 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, MembershipType.CMS_USER, contactId);
            }

            // Prepare resolver for notification and welcome emails
            MacroResolver resolver = MembershipResolvers.GetMembershipRegistrationResolver(ui, password, AuthenticationHelper.GetRegistrationApprovalUrl(ApprovalPage, ui.UserGUID, CurrentSiteName, NotifyAdministrator));

            emailMessage.From = EmailHelper.GetSender(template, SettingsKeyInfoProvider.GetValue(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)
        {
            ShowError(GetString("RegistrationForm.UserWasNotCreated"));

            // Email was not send, user can't be approved - delete it
            UserInfoProvider.DeleteUser(ui);
        }
    }
Ejemplo n.º 6
0
    /// <summary>
    /// Sends confirmation or welcome email.
    /// </summary>
    private void SendRegistrationEmail(UserInfo ui)
    {
        bool error = false;
        EmailTemplateInfo template = null;

        // Email message
        EmailMessage emailMessage = new EmailMessage();

        emailMessage.EmailFormat = EmailFormatEnum.Default;
        emailMessage.Recipients  = ui.Email;
        emailMessage.From        = SettingsKeyInfoProvider.GetValue(CurrentSiteName + ".CMSNoreplyEmailAddress");

        // Send welcome message with username and password, with confirmation link, user must confirm registration
        if (ConfirmationRequired)
        {
            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 (AdminApprovalRequired)
            {
                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)
        {
            // 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, MembershipType.CMS_USER, contactId);
            }

            try
            {
                // Prepare resolver for notification and welcome emails
                MacroResolver resolver = MembershipResolvers.GetMembershipRegistrationResolver(ui, AuthenticationHelper.GetRegistrationApprovalUrl(ApprovalPage, ui.UserGUID, CurrentSiteName, NotifyAdministrator));
                EmailSender.SendEmailWithTemplateText(CurrentSiteName, emailMessage, template, resolver, true);
            }
            catch (Exception ex)
            {
                EventLogProvider.LogException("E", "RegistrationForm - SendEmail", ex);
                error = true;
            }
        }

        // If there was some error, user must be deleted
        if (error)
        {
            ShowError(GetString("RegistrationForm.UserWasNotCreated"));

            // Email was not send, user can't be approved - delete it
            UserInfoProvider.DeleteUser(ui);
        }
    }
    /// <summary>
    /// Sets data to database.
    /// </summary>
    protected void btnOK_Click(object sender, EventArgs e)
    {
        string errorMessage = "";
        string siteName     = SiteContext.CurrentSiteName;

        if ((txtCustomerCompany.Text.Trim() == "" || !IsBusiness) &&
            ((txtCustomerFirstName.Text.Trim() == "") || (txtCustomerLastName.Text.Trim() == "")))
        {
            errorMessage = GetString("Customers_Edit.errorInsert");
        }

        // At least company name has to be filled when company account is selected
        if (errorMessage == "" && IsBusiness)
        {
            errorMessage = new Validator().NotEmpty(txtCustomerCompany.Text, GetString("customers_edit.errorCompany")).Result;
        }

        // Check the following items if complete company info is required for company account
        if (errorMessage == "" && ECommerceSettings.RequireCompanyInfo(siteName) && IsBusiness)
        {
            errorMessage = new Validator().NotEmpty(txtOraganizationID.Text, GetString("customers_edit.errorOrganizationID"))
                           .NotEmpty(txtTaxRegistrationID.Text, GetString("customers_edit.errorTaxRegID")).Result;
        }

        if (errorMessage == "")
        {
            errorMessage = new Validator().IsEmail(txtCustomerEmail.Text.Trim(), GetString("customers_edit.erroremailformat"), true)
                           .MatchesCondition(txtCustomerPhone.Text.Trim(), k => k.Length < 50, GetString("customers_edit.errorphoneformat")).Result;
        }

        plcCompanyInfo.Visible = IsBusiness;

        if (errorMessage == "")
        {
            // If customer doesn't already exist, create new one
            if (mCustomer == null)
            {
                mCustomer = new CustomerInfo();
                mCustomer.CustomerUserID = MembershipContext.AuthenticatedUser.UserID;
            }

            mCustomer.CustomerEmail     = txtCustomerEmail.Text.Trim();
            mCustomer.CustomerLastName  = txtCustomerLastName.Text.Trim();
            mCustomer.CustomerPhone     = txtCustomerPhone.Text.Trim();
            mCustomer.CustomerFirstName = txtCustomerFirstName.Text.Trim();
            mCustomer.CustomerCreated   = DateTime.Now;

            if (IsBusiness)
            {
                mCustomer.CustomerCompany           = txtCustomerCompany.Text.Trim();
                mCustomer.CustomerOrganizationID    = txtOraganizationID.Text.Trim();
                mCustomer.CustomerTaxRegistrationID = txtTaxRegistrationID.Text.Trim();
            }
            else
            {
                mCustomer.CustomerCompany           = "";
                mCustomer.CustomerOrganizationID    = "";
                mCustomer.CustomerTaxRegistrationID = "";
            }

            // Update customer data
            CustomerInfoProvider.SetCustomerInfo(mCustomer);

            // Update corresponding contact data
            int currentContactId = ModuleCommands.OnlineMarketingGetCurrentContactID();
            ModuleCommands.OnlineMarketingCreateRelation(mCustomer.CustomerID, MembershipType.ECOMMERCE_CUSTOMER, currentContactId);
            ContactInfoProvider.UpdateContactFromExternalData(
                mCustomer,
                DataClassInfoProvider.GetDataClassInfo(CustomerInfo.TYPEINFO.ObjectClassName).ClassContactOverwriteEnabled,
                currentContactId);

            // Let others now that customer was created
            if (OnCustomerCrated != null)
            {
                OnCustomerCrated();

                ShowChangesSaved();
            }
            else
            {
                URLHelper.Redirect(URLHelper.AddParameterToUrl(RequestContext.CurrentURL, "saved", "1"));
            }
        }
        else
        {
            //Show error
            ShowError(errorMessage);
        }
    }
    private void usNewsletters_OnSelectionChanged(object sender, EventArgs e)
    {
        if (RaiseOnCheckPermissions("ManageSubscribers", this))
        {
            if (StopProcessing)
            {
                return;
            }
        }

        // Get specified user if used instead of current user
        UserInfo ui = null;

        if (UserID > 0)
        {
            ui = UserInfoProvider.GetUserInfo(UserID);
        }
        else
        {
            ui = CMSContext.CurrentUser;
        }

        // Get specified site ID instead of current site ID
        int siteId = 0;

        if (SiteID > 0)
        {
            siteId = SiteID;
        }
        else
        {
            siteId = CMSContext.CurrentSiteID;
        }

        if ((sb == null) && (ui != null))
        {
            // Create new subsciber (bind to existing user account)
            if ((!ui.IsPublic()) && (ValidationHelper.IsEmail(ui.Email) || ValidationHelper.IsEmail(ui.UserName)))
            {
                sb = new SubscriberInfo();
                if (ui != null)
                {
                    if (!string.IsNullOrEmpty(ui.FirstName) && !string.IsNullOrEmpty(ui.LastName))
                    {
                        sb.SubscriberFirstName = ui.FirstName;
                        sb.SubscriberLastName  = ui.LastName;
                    }
                    else
                    {
                        sb.SubscriberFirstName = ui.FullName;
                    }
                    // Full name consists of "user " and user full name
                    sb.SubscriberFullName = "User '" + ui.FullName + "'";
                }

                sb.SubscriberSiteID    = siteId;
                sb.SubscriberType      = SiteObjectType.USER;
                sb.SubscriberRelatedID = ui.UserID;
                // Save subscriber to DB
                SubscriberInfoProvider.SetSubscriberInfo(sb);
            }
        }

        if (sb == null)
        {
            return;
        }

        // Create membership between current contact and subscriber
        ModuleCommands.OnlineMarketingCreateRelation(sb.SubscriberID, MembershipType.NEWSLETTER_SUBSCRIBER, ModuleCommands.OnlineMarketingGetCurrentContactID());

        // Remove old items
        int    newsletterId = 0;
        string newValues    = ValidationHelper.GetString(usNewsletters.Value, null);
        string items        = DataHelper.GetNewItemsInList(newValues, currentValues);

        if (!String.IsNullOrEmpty(items))
        {
            string[] newItems = items.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
            if (newItems != null)
            {
                foreach (string item in newItems)
                {
                    newsletterId = ValidationHelper.GetInteger(item, 0);

                    // If subscriber is subscribed, unsubscribe him
                    if (SubscriberInfoProvider.IsSubscribed(sb.SubscriberID, newsletterId))
                    {
                        SubscriberInfoProvider.Unsubscribe(sb.SubscriberID, newsletterId, SendConfirmationEmail);
                        // Log activity
                        LogActivity(ui, newsletterId, false);
                    }
                }
            }
        }

        // Add new items
        items = DataHelper.GetNewItemsInList(currentValues, newValues);
        if (!String.IsNullOrEmpty(items))
        {
            string[] newItems = items.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
            if (newItems != null)
            {
                foreach (string item in newItems)
                {
                    newsletterId = ValidationHelper.GetInteger(item, 0);

                    // If subscriber is not subscribed, subscribe him
                    if (!SubscriberInfoProvider.IsSubscribed(sb.SubscriberID, newsletterId))
                    {
                        try
                        {
                            SubscriberInfoProvider.Subscribe(sb.SubscriberID, newsletterId, DateTime.Now, SendConfirmationEmail);
                            // Log activity
                            LogActivity(ui, newsletterId, true);
                        }
                        catch
                        {
                        }
                    }
                }
            }
        }

        // Display information about successful (un)subscription
        ShowChangesSaved();
    }
Ejemplo n.º 9
0
    /// <summary>
    /// Save subscriber.
    /// </summary>
    /// <returns>Subscriber info object</returns>
    private SubscriberInfo SaveSubscriber()
    {
        string emailValue    = null;
        int    currentSiteId = SiteContext.CurrentSiteID;

        // Check if a subscriber exists first
        SubscriberInfo sb = null;

        if (AllowUserSubscribers && isAuthenticated)
        {
            // Try to get user subscriber
            sb = SubscriberInfoProvider.GetSubscriberInfo(UserInfo.OBJECT_TYPE, CurrentUser.UserID, currentSiteId);
        }
        else
        {
            EditingFormControl txtEmail = formElem.FieldEditingControls["SubscriberEmail"] as EditingFormControl;
            if (txtEmail != null)
            {
                emailValue = ValidationHelper.GetString(txtEmail.Value, String.Empty);
            }

            if (!string.IsNullOrEmpty(emailValue))
            {
                // Try to get subscriber by email address
                sb = SubscriberInfoProvider.GetSubscriberInfo(emailValue, currentSiteId);
            }
        }

        if ((sb == null) || (chooseMode))
        {
            // Create subscriber
            if (sb == null)
            {
                if (formElem.Visible)
                {
                    int formSiteId = formElem.Data.GetValue("SubscriberSiteID").ToInteger(0);
                    if (formSiteId == 0)
                    {
                        // Specify SiteID for the new subscriber
                        formElem.Data.SetValue("SubscriberSiteID", currentSiteId);
                    }

                    // Save form with new subscriber data
                    if (!formElem.Save())
                    {
                        return(null);
                    }

                    // Get subscriber info from form
                    sb = (SubscriberInfo)formElem.Info;
                }
                else
                {
                    sb = new SubscriberInfo();
                }
            }

            // Handle authenticated user
            if (AllowUserSubscribers && isAuthenticated)
            {
                // Get user info and copy first name, last name or full name to new subscriber
                // if these properties were not set
                UserInfo ui = UserInfoProvider.GetUserInfo(CurrentUser.UserID);
                if (ui != null)
                {
                    if (!DataHelper.IsEmpty(ui.FirstName) && !DataHelper.IsEmpty(ui.LastName))
                    {
                        if (string.IsNullOrEmpty(sb.SubscriberFirstName))
                        {
                            sb.SubscriberFirstName = ui.FirstName;
                        }
                        if (string.IsNullOrEmpty(sb.SubscriberLastName))
                        {
                            sb.SubscriberLastName = ui.LastName;
                        }
                    }
                    else
                    {
                        if (string.IsNullOrEmpty(sb.SubscriberFirstName))
                        {
                            sb.SubscriberFirstName = ui.FullName;
                        }
                    }

                    // Full name consists of "user " and user full name
                    sb.SubscriberFullName = new SubscriberFullNameFormater().GetUserSubscriberName(ui.FullName);

                    if (!string.IsNullOrEmpty(sb.SubscriberEmail) && string.IsNullOrEmpty(ui.Email))
                    {
                        // Update user email if it was not set
                        ui.Email = sb.SubscriberEmail;
                        UserInfoProvider.SetUserInfo(ui);

                        // Reset email for user subscriber
                        sb.SubscriberEmail = null;
                    }
                }
                else
                {
                    return(null);
                }

                sb.SubscriberType      = UserInfo.OBJECT_TYPE;
                sb.SubscriberRelatedID = ui.UserID;
            }
            // Work with non-authenticated user
            else
            {
                if (string.IsNullOrEmpty(sb.SubscriberFullName))
                {
                    // Fill full name if it was not set via the form
                    sb.SubscriberFullName = (sb.SubscriberFirstName + " " + sb.SubscriberLastName).Trim();
                }
            }

            // Set site ID
            sb.SubscriberSiteID = SiteContext.CurrentSiteID;

            // Insert or update subscriber info
            SubscriberInfoProvider.SetSubscriberInfo(sb);

            // Check subscriber limits
            if (!SubscriberInfoProvider.LicenseVersionCheck(RequestContext.CurrentDomain, FeatureEnum.Subscribers, ObjectActionEnum.Insert))
            {
                // Remove created subscriber and display error message
                SubscriberInfoProvider.DeleteSubscriberInfo(sb);

                lblError.Visible = true;
                lblError.Text    = GetString("LicenseVersionCheck.Subscribers");
                return(null);
            }
        }

        if (sb != null)
        {
            // Create membership between current contact and subscriber
            ModuleCommands.OnlineMarketingCreateRelation(sb.SubscriberID, MembershipType.NEWSLETTER_SUBSCRIBER, ModuleCommands.OnlineMarketingGetCurrentContactID());
        }

        // Return subscriber info object
        return(sb);
    }
Ejemplo n.º 10
0
    private void usNewsletters_OnSelectionChanged(object sender, EventArgs e)
    {
        if (RaiseOnCheckPermissions("ManageSubscribers", this))
        {
            if (StopProcessing)
            {
                return;
            }
        }

        // Get specified site ID instead of current site ID
        int siteId = 0;

        if (SiteID > 0)
        {
            siteId = SiteID;
        }
        else
        {
            siteId = SiteContext.CurrentSiteID;
        }

        if ((subscriber == null) && (userInfo != null))
        {
            // Create new subsciber (bind to existing user account)
            if ((!userInfo.IsPublic()) && (ValidationHelper.IsEmail(userInfo.Email) || ValidationHelper.IsEmail(userInfo.UserName)))
            {
                subscriber = new SubscriberInfo();
                if (userInfo != null)
                {
                    if (!string.IsNullOrEmpty(userInfo.FirstName) && !string.IsNullOrEmpty(userInfo.LastName))
                    {
                        subscriber.SubscriberFirstName = userInfo.FirstName;
                        subscriber.SubscriberLastName  = userInfo.LastName;
                    }
                    else
                    {
                        subscriber.SubscriberFirstName = userInfo.FullName;
                    }
                    // Full name consists of "user " and user full name
                    subscriber.SubscriberFullName = new SubscriberFullNameFormater().GetUserSubscriberName(userInfo.FullName);
                }

                subscriber.SubscriberSiteID    = siteId;
                subscriber.SubscriberType      = UserInfo.OBJECT_TYPE;
                subscriber.SubscriberRelatedID = userInfo.UserID;
                // Save subscriber to DB
                SubscriberInfoProvider.SetSubscriberInfo(subscriber);
            }
        }

        if (subscriber == null)
        {
            return;
        }

        // Create membership between current contact and subscriber
        ModuleCommands.OnlineMarketingCreateRelation(subscriber.SubscriberID, MembershipType.NEWSLETTER_SUBSCRIBER, ModuleCommands.OnlineMarketingGetCurrentContactID());

        // Remove old items
        int    newsletterId = 0;
        string newValues    = ValidationHelper.GetString(usNewsletters.Value, null);
        string items        = DataHelper.GetNewItemsInList(newValues, currentValues);

        if (!String.IsNullOrEmpty(items))
        {
            string[] newItems = items.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);

            var ids           = newItems.Select(item => ValidationHelper.GetInteger(item, 0)).ToArray();
            var subscriptions = SubscriberNewsletterInfoProvider
                                .GetSubscriberNewsletters()
                                .WhereEquals("SubscriberID", subscriber.SubscriberID)
                                .WhereIn("NewsletterID", ids);

            foreach (var subscription in subscriptions)
            {
                subscription.Delete();
                LogActivity(userInfo, newsletterId, false);
            }
        }

        // Add new items
        items = DataHelper.GetNewItemsInList(currentValues, newValues);
        if (!String.IsNullOrEmpty(items))
        {
            string[] newItems = items.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
            if (newItems != null)
            {
                foreach (string item in newItems)
                {
                    newsletterId = ValidationHelper.GetInteger(item, 0);

                    try
                    {
                        // If subscriber is not subscribed, subscribe him
                        if (!mSubscriptionService.IsSubscribed(subscriber.SubscriberID, newsletterId))
                        {
                            mSubscriptionService.Subscribe(subscriber.SubscriberID, newsletterId, new SubscribeSettings()
                            {
                                SendConfirmationEmail = SendConfirmationEmail,
                                RequireOptIn          = true,
                                RemoveAlsoUnsubscriptionFromAllNewsletters = true,
                            });
                            // Log activity
                            LogActivity(userInfo, newsletterId, true);
                        }
                    }
                    catch
                    {
                        // Can occur e.g. when newsletter is deleted while the user is selecting it for subscription.
                        // This is rare scenario, the main purpose of this catch is to avoid YSOD on the live site.
                    }
                }
            }
        }

        // Display information about successful (un)subscription
        ShowChangesSaved();
    }
Ejemplo n.º 11
0
    protected void Page_Load(object sender, EventArgs e)
    {
        // If StopProcessing flag is set, do nothing
        if (StopProcessing)
        {
            Visible = false;
            return;
        }

        string subscriptionHash = QueryHelper.GetString("subscriptionhash", string.Empty);
        string requestTime      = QueryHelper.GetString("datetime", string.Empty);

        DateTime datetime = DateTimeHelper.ZERO_TIME;

        // Get date and time
        if (!string.IsNullOrEmpty(requestTime))
        {
            try
            {
                datetime = DateTime.ParseExact(requestTime, SecurityHelper.EMAIL_CONFIRMATION_DATETIME_FORMAT, null);
            }
            catch
            {
                lblInfo.Text = ResHelper.GetString("newsletter.approval_failed");
                return;
            }
        }

        if (string.IsNullOrEmpty(subscriptionHash))
        {
            this.Visible = false;
            return;
        }

        // Try to approve subscription
        SubscriberProvider.ApprovalResult result = SubscriberProvider.ApproveSubscription(subscriptionHash, false, CMSContext.CurrentSiteName, datetime);

        switch (result)
        {
        // Approving subscription was successful
        case SubscriberProvider.ApprovalResult.Success:
            if (!String.IsNullOrEmpty(this.SuccessfulApprovalText))
            {
                lblInfo.Text = this.SuccessfulApprovalText;
            }
            else
            {
                lblInfo.Text = ResHelper.GetString("newsletter.successful_approval");
            }

            // Log newsletter subscription activity
            if ((CMSContext.ViewMode == ViewModeEnum.LiveSite))
            {
                SubscriberNewsletterInfo sni = SubscriberNewsletterInfoProvider.GetSubscriberNewsletterInfo(subscriptionHash);
                if (sni != null)
                {
                    // Load subscriber info and make sure activity modul is enabled
                    Subscriber sb = SubscriberProvider.GetSubscriber(sni.SubscriberID);
                    if ((sb != null) && ActivitySettingsHelper.ActivitiesEnabledAndModuleLoaded(sb.SubscriberSiteID))
                    {
                        int        siteId = sb.SubscriberSiteID;
                        Newsletter news   = NewsletterProvider.GetNewsletter(sni.NewsletterID);
                        if (news.NewsletterLogActivity && ActivitySettingsHelper.NewsletterSubscribeEnabled(siteId))
                        {
                            // Under what contacs this subscriber belogs to?
                            int contactId = ActivityTrackingHelper.GetContactID(sb);

                            if (contactId > 0)
                            {
                                ModuleCommands.OnlineMarketingUpdateContactFromExternalData(sb, contactId);
                                ModuleCommands.OnlineMarketingCreateRelation(sb.SubscriberID, MembershipType.NEWSLETTER_SUBSCRIBER, contactId);
                                var data = new ActivityData()
                                {
                                    ContactID = contactId,
                                    SiteID    = sb.SubscriberSiteID,
                                    Type      = PredefinedActivityType.NEWSLETTER_SUBSCRIBING,
                                    TitleData = news.NewsletterName,
                                    ItemID    = news.NewsletterID,
                                    URL       = URLHelper.CurrentRelativePath,
                                    Campaign  = CMSContext.Campaign
                                };
                                ActivityLogProvider.LogActivity(data);
                            }
                        }
                    }
                }
            }
            break;

        // Subscription was already approved
        case SubscriberProvider.ApprovalResult.Failed:
            if (!String.IsNullOrEmpty(this.UnsuccessfulApprovalText))
            {
                lblInfo.Text = this.UnsuccessfulApprovalText;
            }
            else
            {
                lblInfo.Text = ResHelper.GetString("newsletter.approval_failed");
            }
            break;

        case SubscriberProvider.ApprovalResult.TimeExceeded:
            if (!String.IsNullOrEmpty(this.UnsuccessfulApprovalText))
            {
                lblInfo.Text = this.UnsuccessfulApprovalText;
            }
            else
            {
                lblInfo.Text = ResHelper.GetString("newsletter.approval_timeexceeded");
            }
            break;


        // Subscription not found
        default:
        case SubscriberProvider.ApprovalResult.NotFound:
            if (!String.IsNullOrEmpty(this.UnsuccessfulApprovalText))
            {
                lblInfo.Text = this.UnsuccessfulApprovalText;
            }
            else
            {
                lblInfo.Text = ResHelper.GetString("newsletter.approval_invalid");
            }
            break;
        }
    }
    /// <summary>
    /// Saves the data.
    /// </summary>
    private bool Save(string newsletterName, Subscriber sb)
    {
        bool toReturn = false;
        int  siteId   = CMSContext.CurrentSiteID;

        // Check if sunscriber info object exists
        if ((sb == null) || string.IsNullOrEmpty(newsletterName))
        {
            return(false);
        }

        // Get nesletter info
        Newsletter news = NewsletterProvider.GetNewsletter(newsletterName, siteId);

        if (news != null)
        {
            try
            {
                // Check if subscriber is not allready subscribed
                if (!SubscriberProvider.IsSubscribed(sb.SubscriberGUID, news.NewsletterGUID, siteId))
                {
                    toReturn = true;

                    // Subscribe to the site
                    SubscriberProvider.Subscribe(sb.SubscriberID, news.NewsletterID, DateTime.Now, this.SendConfirmationEmail);

                    // Info message
                    if (!chooseMode)
                    {
                        lblInfo.Visible = true;
                        lblInfo.Text    = GetString("NewsletterSubscription.Subscribed");
                    }

                    // Track successful subscription conversion
                    if (this.TrackConversionName != string.Empty)
                    {
                        string siteName = CMSContext.CurrentSiteName;

                        if (AnalyticsHelper.AnalyticsEnabled(siteName) && AnalyticsHelper.TrackConversionsEnabled(siteName) && !AnalyticsHelper.IsIPExcluded(siteName, HTTPHelper.UserHostAddress))
                        {
                            // Log conversion
                            HitLogProvider.LogConversions(siteName, CMSContext.PreferredCultureCode, TrackConversionName, 0, ConversionValue);
                        }
                    }

                    // Log newsletter subscription activity if double opt-in is not required
                    if (!news.NewsletterEnableOptIn)
                    {
                        if ((CMSContext.ViewMode == ViewModeEnum.LiveSite) && news.NewsletterLogActivity && ActivitySettingsHelper.ActivitiesEnabledAndModuleLoaded(siteId) &&
                            ActivitySettingsHelper.ActivitiesEnabledForThisUser(CMSContext.CurrentUser) &&
                            ActivitySettingsHelper.NewsletterSubscribeEnabled(siteId))
                        {
                            int contactId = ModuleCommands.OnlineMarketingGetCurrentContactID();
                            ModuleCommands.OnlineMarketingUpdateContactFromExternalData(sb, contactId);
                            ModuleCommands.OnlineMarketingCreateRelation(sb.SubscriberID, MembershipType.NEWSLETTER_SUBSCRIBER, contactId);

                            if (ActivitySettingsHelper.ActivitiesEnabledForThisUser(CMSContext.CurrentUser))
                            {
                                var data = new ActivityData()
                                {
                                    ContactID = contactId,
                                    SiteID    = sb.SubscriberSiteID,
                                    Type      = PredefinedActivityType.NEWSLETTER_SUBSCRIBING,
                                    TitleData = news.NewsletterName,
                                    ItemID    = news.NewsletterID,
                                    URL       = URLHelper.CurrentRelativePath,
                                    Campaign  = CMSContext.Campaign
                                };
                                ActivityLogProvider.LogActivity(data);
                            }
                        }
                    }
                }
                else
                {
                    // Info message - subscriber is allready in site
                    if (!chooseMode)
                    {
                        lblInfo.Visible = true;
                        lblInfo.Text    = GetString("NewsletterSubscription.SubscriberIsAlreadySubscribed");
                    }
                    else
                    {
                        lblInfo.Visible = true;
                        lblInfo.Text   += GetString("NewsletterSubscription.SubscriberIsAlreadySubscribedXY") + " " + HTMLHelper.HTMLEncode(news.NewsletterDisplayName) + ".<br />";
                    }
                }
            }
            catch (Exception ex)
            {
                lblError.Visible = true;
                lblError.Text    = ex.Message;
            }
        }
        else
        {
            lblError.Visible = true;
            lblError.Text    = GetString("NewsletterSubscription.NewsletterDoesNotExist");
        }

        return(toReturn);
    }