Beispiel #1
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)
            {
                var checker = new UserContactDataPropagationChecker();
                Service.Resolve <IContactRelationAssigner>().Assign(ui.UserID, MembershipType.CMS_USER, contactId, checker);
            }

            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>
    /// Sends e-mail with password in case the user has specified his email address.
    /// Otherwise, displays the newly generated password to the current user.
    /// </summary>
    /// <param name="pswd">Password to send</param>
    private void SendEmail(string pswd)
    {
        if (UserInfo == null)
        {
            return;
        }

        // Check whether the 'From' element was specified
        string siteName  = SiteContext.CurrentSiteName;
        string emailFrom = SettingsKeyInfoProvider.GetValue("CMSSendPasswordEmailsFrom", siteName);

        if (string.IsNullOrEmpty(emailFrom))
        {
            ShowError(String.Format("{0} {1}", GetString("Administration-User_Edit_Password.PassChangedNotSent"), GetString("Administration-User_Edit_Password.FromMissing")));

            return;
        }

        string emailTo = UserInfo.Email;

        if (!String.IsNullOrEmpty(emailTo))
        {
            EmailMessage em = new EmailMessage
            {
                From        = emailFrom,
                Recipients  = emailTo,
                Subject     = GetString("Administration-User_Edit_Password.NewGen"),
                EmailFormat = EmailFormatEnum.Default
            };

            // Get e-mail template - try to get site specific template if edited user is assigned to current site
            EmailTemplateInfo template = EmailTemplateProvider.GetEmailTemplate("Membership.ChangedPassword", UserInfo.IsInSite(siteName) ? siteName : null);
            if (template != null)
            {
                em.Body = template.TemplateText;

                // Because the password was generated by the system, it's included in the e-mail
                MacroResolver resolver = MembershipResolvers.GetPasswordResolver(UserInfo, pswd);

                try
                {
                    EmailHelper.ResolveMetaFileImages(em, template.TemplateID, EmailTemplateInfo.OBJECT_TYPE, ObjectAttachmentsCategories.TEMPLATE);

                    // Send message immediately (+ resolve macros)
                    EmailSender.SendEmailWithTemplateText(siteName, em, template, resolver, true);

                    // Inform on success
                    ShowConfirmation(GetString("Administration-User_Edit_Password.PasswordsSent") + " " + HTMLHelper.HTMLEncode(emailTo));

                    return;
                }
                catch (Exception ex)
                {
                    EventLogProvider.LogException("PasswordRetrieval", "USERPASSWORD", ex);
                    ShowError("Failed to send the password: "******"Administration-User_Edit_Password.PassChangedNotSent"));
            }
        }
        else
        {
            ShowConfirmation(String.Format(GetString("Administration-User_Edit_Password.passshow"), pswd), true);
        }
    }
Beispiel #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))
            {
                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"

            // Encode brackets and set to textbox to ensure max length after encoding
            txtFirstName.Text = HTMLHelper.EncodeAngleBrackets(txtFirstName.Text.Trim());
            txtLastName.Text  = HTMLHelper.EncodeAngleBrackets(txtLastName.Text.Trim());

            ui = new UserInfo();
            ui.PreferredCultureCode = "";
            ui.Email          = txtEmail.Text.Trim();
            ui.FirstName      = txtFirstName.Text;
            ui.LastName       = txtLastName.Text;
            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;
        }
    }
Beispiel #4
0
    /// <summary>
    /// Sends e-mail with password if required.
    /// </summary>
    /// <param name="pswd">Password to send</param>
    /// <param name="toEmail">E-mail address of the mail recipient</param>
    /// <param name="subject">Subject of the e-mail sent</param>
    /// <param name="emailType">Type of the e-mail specificating the template used (NEW, CHANGED, RESEND)</param>
    /// <param name="showPassword">Indicates whether password is shown in message.</param>
    private void SendEmail(string subject, string pswd, int userId, string emailType, bool showPassword)
    {
        // Check whether the 'From' element was specified
        string emailFrom   = SettingsKeyProvider.GetStringValue(CMSContext.CurrentSiteName + ".CMSSendPasswordEmailsFrom");
        bool   fromMissing = string.IsNullOrEmpty(emailFrom);

        if ((!string.IsNullOrEmpty(emailType)) && (ui != null) && (!fromMissing))
        {
            if (!string.IsNullOrEmpty(ui.Email))
            {
                EmailMessage em = new EmailMessage();

                em.From        = emailFrom;
                em.Recipients  = ui.Email;
                em.Subject     = subject;
                em.EmailFormat = EmailFormatEnum.Default;

                string templateName = null;

                // Get e-mail template name
                switch (emailType.ToLowerCSafe())
                {
                case "new":
                    templateName = "Membership.NewPassword";
                    break;

                case "changed":
                    templateName = "Membership.ChangedPassword";
                    break;

                case "resend":
                    templateName = "Membership.ResendPassword";
                    break;

                default:
                    break;
                }

                // Get template info object
                if (templateName != null)
                {
                    try
                    {
                        // Get e-mail template
                        EmailTemplateInfo template = EmailTemplateProvider.GetEmailTemplate(templateName, null);
                        if (template != null)
                        {
                            em.Body = template.TemplateText;

                            // Macros
                            string[,] macros = new string[2, 2];
                            macros[0, 0]     = "UserName";
                            macros[0, 1]     = ui.UserName;
                            macros[1, 0]     = "Password";
                            macros[1, 1]     = pswd;
                            // Create macro resolver
                            ContextResolver resolver = CMSContext.CurrentResolver;
                            resolver.SourceParameters = macros;

                            // Add template attachments
                            MetaFileInfoProvider.ResolveMetaFileImages(em, template.TemplateID, EmailObjectType.EMAILTEMPLATE, MetaFileInfoProvider.OBJECT_CATEGORY_TEMPLATE);
                            // Send message immediately (+ resolve macros)
                            EmailSender.SendEmailWithTemplateText(CMSContext.CurrentSiteName, em, template, resolver, true);

                            // Inform on success
                            ShowConfirmation(GetString("Administration-User_Edit_Password.PasswordsSent") + " " + HTMLHelper.HTMLEncode(ui.Email));

                            return;
                        }
                    }
                    catch (Exception ex)
                    {
                        // Log the error to the event log
                        EventLogProvider eventLog = new EventLogProvider();
                        eventLog.LogEvent("Password retrieval", "USERPASSWORD", ex);
                        ShowError("Failed to send the password: "******"Administration-User_Edit_Password.passshow"), pswd), true);
                }
                else
                {
                    ShowConfirmation(GetString("Administration-User_Edit_Password.PassChangedNotSent"));
                }

                return;
            }
        }

        // Inform on error
        string errorMessage = GetString("Administration-User_Edit_Password.PasswordsNotSent");

        if (fromMissing)
        {
            ShowError(errorMessage + " " + GetString("Administration-User_Edit_Password.FromMissing"));
        }
        else
        {
            ShowError(errorMessage);
        }
    }
    /// <summary>
    /// Page Load.
    /// </summary>
    protected void Page_Load(object sender, EventArgs e)
    {
        // If StopProcessing flag is set, do nothing
        if (StopProcessing)
        {
            Visible = false;
            return;
        }

        Guid userGuid = QueryHelper.GetGuid("userguid", Guid.Empty);

        if (userGuid != Guid.Empty)
        {
            #region "Request validity"

            UserInfo ui = UserInfoProvider.GetUserInfoByGUID(userGuid);

            // ui was not found, probably late activation try
            if (ui == null)
            {
                lblInfo.Text = UserDeletedText;
                return;
            }

            // ui has been already activated
            if ((ui.UserSettings.UserActivationDate > DateTimeHelper.ZERO_TIME) || ui.UserSettings.UserWaitingForApproval || ui.UserEnabled)
            {
                lblInfo.Text = UnsuccessfulApprovalText;
                return;
            }

            #endregion

            string siteName = null;
            bool   administrationApproval = SettingsKeyProvider.GetBoolValue(CMSContext.CurrentSiteName + ".CMSRegistrationAdministratorApproval");
            lblInfo.Text = SuccessfulApprovalText;

            // Admin approve is not required, enable ui
            if (!administrationApproval)
            {
                lblInfo.Text = (!String.IsNullOrEmpty(SuccessfulApprovalText)) ? SuccessfulApprovalText : GetString("mem.reg.SuccessfulApprovalText");

                // Enable ui
                ui.UserSettings.UserActivationDate = DateTime.Now;
                ui.Enabled = true;

                // ui is confirmed and enabled, could be logged into statistics
                siteName = CMSContext.CurrentSiteName;
                AnalyticsHelper.LogRegisteredUser(siteName, ui);
            }
            // ui must wait for admin approval
            else
            {
                lblInfo.Text = (!String.IsNullOrEmpty(WaitingForApprovalText)) ? WaitingForApprovalText : ResHelper.GetString("mem.reg.SuccessfulApprovalWaitingForAdministratorApproval");

                // Mark for admin approval
                ui.UserSettings.UserWaitingForApproval = true;
            }

            // Save changes
            UserInfoProvider.SetUserInfo(ui);

            #region "Log activity"

            // Log registration activity
            siteName = CMSContext.CurrentSiteName;
            if (ActivitySettingsHelper.ActivitiesEnabledAndModuleLoaded(siteName))
            {
                if (ActivitySettingsHelper.UserRegistrationEnabled(siteName))
                {
                    if (ActivitySettingsHelper.ActivitiesEnabledForThisUser(ui))
                    {
                        // Try to get contact ID from confirmation link (if any)
                        int contactId = QueryHelper.GetInteger("contactid", 0);
                        if (contactId <= 0)
                        {
                            // Contact ID not found => get new ID according to user info
                            contactId = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui);
                        }
                        TreeNode currDoc = CMSContext.CurrentDocument;
                        ActivityLogProvider.LogRegistrationActivity(contactId,
                                                                    ui, URLHelper.CurrentRelativePath, (currDoc != null) ? currDoc.DocumentID : 0, siteName, CMSContext.Campaign, (currDoc != null) ? currDoc.DocumentCulture : null);
                    }
                }
            }

            #endregion


            #region "Administrator notification email"

            // Notify administrator if enabled and email confirmation is not required
            if ((!String.IsNullOrEmpty(AdministratorEmail)) && (administrationApproval || NotifyAdministrator))
            {
                EmailTemplateInfo template = null;

                if (administrationApproval)
                {
                    template = EmailTemplateProvider.GetEmailTemplate("Registration.Approve", CMSContext.CurrentSiteName);
                }
                else
                {
                    template = EmailTemplateProvider.GetEmailTemplate("Registration.New", CMSContext.CurrentSiteName);
                }

                EventLogProvider ev = new EventLogProvider();

                if (template == null)
                {
                    ev.LogEvent("E", DateTime.Now, "RegistrationForm", "GetEmailTemplate", HTTPHelper.GetAbsoluteUri());
                }
                //email template ok
                else
                {
                    // Prepare macro replacements
                    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]     = ui.UserName;

                    // Set resolver
                    ContextResolver resolver = CMSContext.CurrentResolver;
                    resolver.SourceParameters     = replacements;
                    resolver.EncodeResolvedValues = true;

                    // 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 = EmailHelper.GetSender(template, (!String.IsNullOrEmpty(FromAddress)) ? FromAddress : SettingsKeyProvider.GetStringValue(CMSContext.CurrentSiteName + ".CMSNoreplyEmailAddress"));

                    email.Body = resolver.ResolveMacros(template.TemplateText);

                    resolver.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
                    {
                        MetaFileInfoProvider.ResolveMetaFileImages(email, template.TemplateID, EmailObjectType.EMAILTEMPLATE, MetaFileInfoProvider.OBJECT_CATEGORY_TEMPLATE);
                        // Send the e-mail immediately
                        EmailSender.SendEmail(CMSContext.CurrentSiteName, email, true);
                    }
                    catch
                    {
                        ev.LogEvent("E", DateTime.Now, "Membership", "RegistrationApprovalEmail", CMSContext.CurrentSite.SiteID);
                    }
                }
            }

            #endregion
        }
        else
        {
            Visible = false;
        }
    }
Beispiel #6
0
    public void Save(bool closeOnSave)
    {
        // Check modify permission
        RaiseOnCheckPermissions(PERMISSION_MODIFY, this);

        txtDisplayName.Text = txtDisplayName.Text.Trim();
        txtCodeName.Text    = txtCodeName.Text.Trim();
        txtSubject.Text     = txtSubject.Text.Trim();

        // Find whether required fields are not empty
        string result = new Validator().NotEmpty(txtDisplayName.Text, GetString("EmailTemplate_Edit.FillDisplayNameField"))
                        .NotEmpty(txtCodeName.Text, GetString("EmailTemplate_Edit.FillCodeNameField"))
                        .IsCodeName(txtCodeName.Text, GetString("general.invalidcodename"))
                        .Result;

        // Check validity of entered e-mails
        if (!String.IsNullOrEmpty(txtFrom.Text) && !ValidationHelper.AreEmails(txtFrom.Text))
        {
            result = GetString("EmailTemplate_Edit.InvalidFrom");
        }
        else if (!String.IsNullOrEmpty(txtBcc.Text) && !ValidationHelper.AreEmails(txtBcc.Text))
        {
            result = GetString("EmailTemplate_Edit.InvalidBcc");
        }
        else if (!String.IsNullOrEmpty(txtCc.Text) && !ValidationHelper.AreEmails(txtCc.Text))
        {
            result = GetString("EmailTemplate_Edit.InvalidCc");
        }

        if (String.IsNullOrEmpty(result))
        {
            string siteName = null;
            if (SiteID != 0)
            {
                // Get site name for non-global templates
                SiteInfo site = SiteInfoProvider.GetSiteInfo(SiteID);
                if (site != null)
                {
                    siteName = site.SiteName;
                }
            }
            // Try to get template by template name and site name
            EmailTemplateInfo templateInfo = EmailTemplateProvider.GetEmailTemplate(txtCodeName.Text, siteName);

            // Find if codename of the email template is unique for the site
            if ((templateInfo == null) || (templateInfo.TemplateID == EmailTemplateID) || ((templateInfo.TemplateSiteID == 0) && (SiteID > 0)))
            {
                bool isInsert = false;

                // Get object
                if (templateInfo == null)
                {
                    templateInfo = EmailTemplateProvider.GetEmailTemplate(EmailTemplateID);
                    if (templateInfo == null)
                    {
                        templateInfo = new EmailTemplateInfo();
                        isInsert     = true;
                    }
                }

                templateInfo.TemplateID          = EmailTemplateID;
                templateInfo.TemplateDisplayName = txtDisplayName.Text;
                templateInfo.TemplateName        = txtCodeName.Text;
                templateInfo.TemplateSubject     = txtSubject.Text;
                templateInfo.TemplateFrom        = txtFrom.Text;
                templateInfo.TemplateBcc         = txtBcc.Text;
                templateInfo.TemplateCc          = txtCc.Text;
                templateInfo.TemplateText        = txtText.Text;
                templateInfo.TemplatePlainText   = txtPlainText.Text;
                templateInfo.TemplateSiteID      = SiteID;
                templateInfo.TemplateType        = ValidationHelper.GetString(drpEmailType.Value, null);

                // Save (insert/update) EmailTemplateInfo object
                EmailTemplateProvider.SetEmailTemplate(templateInfo);

                CMSContext.EditedObject = templateInfo;

                if (isInsert)
                {
                    pnlObjectLocking.ObjectManager.ObjectType = null;
                    CMSObjectManager.CheckOutNewObject(this.Page);
                }

                // Handle redirection
                RedirectOnSave(templateInfo, closeOnSave);
            }
            else
            {
                ShowError(GetString("EmailTemplate_Edit.UniqueCodeName"));
            }
        }
        else
        {
            ShowError(result);
        }
    }
Beispiel #7
0
    protected void Page_Load(object sender, EventArgs e)
    {
        // Initialize HTML editor
        txtText.Editor.EnableViewState = false;
        txtText.Editor.EditorMode      = EditorModeEnum.Advanced;
        txtText.Editor.Language        = LanguageEnum.HTMLMixed;
        txtText.Editor.Height          = new Unit("400px");
        txtText.Editor.Width           = new Unit("100%");

        // Initialize Plain Text editor
        txtPlainText.Editor.EnableViewState = false;
        txtPlainText.Editor.EditorMode      = EditorModeEnum.Advanced;
        txtPlainText.Editor.Language        = LanguageEnum.Text;
        txtPlainText.Editor.Height          = new Unit("400px");
        txtPlainText.Editor.Width           = new Unit("100%");

        txtPlainText.Editor.FullScreenParentElementID = txtText.Editor.FullScreenParentElementID = "divContent";

        if (TemplateType == null)
        {
            drpEmailType.DropDown.AutoPostBack = true;
        }
        else
        {
            drpEmailType.DropDown.Enabled = false;
            drpEmailType.Value            = EmailTemplateMacros.GetEmailTypeString(TemplateType.Value);
        }

        // Initialize required field validators
        RequiredFieldValidatorDisplayName.ErrorMessage = GetString("EmailTemplate_Edit.FillDisplayNameField");
        RequiredFieldValidatorCodeName.ErrorMessage    = GetString("EmailTemplate_Edit.FillCodeNameField");

        // Register save button handler
        pnlObjectLocking.ObjectManager.OnSaveData    += new EventHandler <SimpleObjectManagerEventArgs>(ObjectManager_OnSaveData);
        pnlObjectLocking.ObjectManager.OnAfterAction += new EventHandler <SimpleObjectManagerEventArgs>(ObjectManager_OnAfterAction);

        if (EmailTemplateID > 0)
        {
            // Get email template info of specified 'templateid'
            templateInfo = EmailTemplateProvider.GetEmailTemplate(EmailTemplateID);
            EditedObject = templateInfo;

            // Get SiteID of the template
            SiteID = templateInfo.TemplateSiteID;

            // Check if user is assigned to web site
            if (!CMSContext.CurrentUser.IsGlobalAdministrator)
            {
                if (!CMSContext.CurrentUser.IsInSite(SiteInfoProvider.GetSiteName(SiteID)))
                {
                    // Disable object for user
                    EditedObject = null;
                }
            }

            // Fill the form
            if (!RequestHelper.IsPostBack())
            {
                // Load data to the form
                LoadData(templateInfo);

                // Show message that the email template was created or updated successfully.
                if (QueryHelper.GetBoolean("saved", false))
                {
                    ShowChangesSaved();

                    // Reload header if changes were saved
                    if ((Page is CMSPage) && ((CMSPage)Page).TabMode)
                    {
                        ScriptHelper.RefreshTabHeader(Page, null);
                    }
                }
            }

            // Register paste attachment script
            RegisterPasteScript();
        }
        else
        {
            pnlObjectLocking.ObjectManager.ObjectType = PredefinedObjectType.EMAILTEMPLATE;
        }

        // Get correct MacroResolver
        ContextResolver resolver = EmailTemplateMacros.GetEmailTemplateResolver(EmailTemplateMacros.GetEmailTypeEnum(ValidationHelper.GetString(drpEmailType.Value, "")));

        txtText.Resolver      = resolver;
        txtPlainText.Resolver = resolver;

        // Disable display name and code name editation when editing item from selector
        txtDisplayName.Enabled = txtCodeName.Enabled = !EditMode || !DialogMode;

        macroSelectorElm.Resolver             = resolver;
        macroSelectorElm.ShowMacroTreeAbove   = true;
        macroSelectorElm.ExtendedTextAreaElem = txtText.Editor.EditorID;
        macroSelectorElm.TextAreaID           = txtText.Editor.ClientID;

        macroSelectorPlain.Resolver             = resolver;
        macroSelectorPlain.ShowMacroTreeAbove   = true;
        macroSelectorPlain.ExtendedTextAreaElem = txtPlainText.Editor.EditorID;
        macroSelectorPlain.TextAreaID           = txtPlainText.Editor.ClientID;

        InitHeaderActions(EmailTemplateID, SiteID);
    }
    /// <summary>
    /// Sets new UserInfo for approved user.
    /// </summary>
    /// <param name="userID">User to be approved</param>
    protected void SetUserInfo(int userID)
    {
        UserInfo user = UserInfoProvider.GetFullUserInfo(userID);

        // Cancel waiting for approval attribute
        user.UserSettings.UserWaitingForApproval = false;
        // Set activation time to now
        user.UserSettings.UserActivationDate = DateTime.Now;
        // Set user who activated this account
        user.UserSettings.UserActivatedByUserID = MembershipContext.AuthenticatedUser.UserID;
        // Enable user
        user.UserEnabled = true;

        UserInfoProvider.SetUserInfo(user);

        // Send e-mail to user
        if (!String.IsNullOrEmpty(user.Email))
        {
            EmailTemplateInfo template = EmailTemplateProvider.GetEmailTemplate("RegistrationUserApproved", SiteContext.CurrentSiteName);
            if (template != null)
            {
                string from = EmailHelper.GetSender(template, SettingsKeyInfoProvider.GetValue(SiteContext.CurrentSiteName + ".CMSNoreplyEmailAddress"));
                if (!String.IsNullOrEmpty(from))
                {
                    EmailMessage email = new EmailMessage();
                    email.EmailFormat = EmailFormatEnum.Default;
                    // Get e-mail sender and subject from template, if used
                    email.From       = from;
                    email.Recipients = user.Email;

                    MacroResolver resolver = MembershipResolvers.GetRegistrationApprovalResolver(user, URLHelper.GetAbsoluteUrl("~/"));

                    // Enable encoding of macro results for HTML mail body
                    resolver.Settings.EncodeResolvedValues = true;
                    email.Body = resolver.ResolveMacros(template.TemplateText);

                    // Disable encoding of macro results for plaintext body and subject
                    resolver.Settings.EncodeResolvedValues = false;
                    string emailSubject = EmailHelper.GetSubject(template, GetString("registrationform.registrationapprovalemailsubject"));
                    email.Subject = resolver.ResolveMacros(emailSubject);

                    email.PlainTextBody = resolver.ResolveMacros(template.TemplatePlainText);

                    email.CcRecipients  = template.TemplateCc;
                    email.BccRecipients = template.TemplateBcc;

                    try
                    {
                        // Add attachments
                        EmailHelper.ResolveMetaFileImages(email, template.TemplateID, EmailTemplateInfo.OBJECT_TYPE, ObjectAttachmentsCategories.TEMPLATE);
                        EmailSender.SendEmail(SiteContext.CurrentSiteName, email);
                    }
                    catch
                    {
                        EventLogProvider.LogEvent(EventType.ERROR, "Membership", "WaitingForApprovalEmail");
                    }
                }
                else
                {
                    EventLogProvider.LogEvent(EventType.ERROR, "WaitingForApproval", "EmailSenderNotSpecified");
                }
            }
            else
            {
                // Log missing e-mail template
                try
                {
                    EventLogProvider.LogEvent(EventType.ERROR, "RegistrationUserApproved", "GetEmailTemplate", eventUrl: RequestContext.RawURL);
                }
                catch
                {
                }
            }
        }

        // User is approved and enabled, could be logged into statistics
        AnalyticsHelper.LogRegisteredUser(SiteContext.CurrentSiteName, user);
    }
    /// <summary>
    /// Initializes the control properties.
    /// </summary>
    protected void SetupControl()
    {
        if (StopProcessing)
        {
            // Do nothing
        }
        else
        {
            if (!RequestHelper.IsPostBack())
            {
                // If user is public
                if (CMSContext.CurrentUser.IsPublic())
                {
                    // Get logon URL
                    string logonUrl = SettingsKeyProvider.GetStringValue(CMSContext.CurrentSiteName + ".CMSSecuredAreasLogonPage");
                    logonUrl = DataHelper.GetNotEmpty(LoginURL, logonUrl);

                    // Create redirect URL
                    logonUrl = URLHelper.ResolveUrl(logonUrl) + "?ReturnURL=" + HttpUtility.UrlEncode(URLHelper.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 != CMSContext.CurrentUser.UserID))
                                    {
                                        lblInfo.CssClass = "InvitationErrorLabel";
                                        lblInfo.Text     = InvitationIsNotValid;
                                        lblInfo.Visible  = true;
                                        return;
                                    }

                                    // If user was invited by e-mail
                                    if (invitation.InvitedUserID == 0)
                                    {
                                        invitation.InvitedUserID = CMSContext.CurrentUser.UserID;
                                    }

                                    if (!GroupMemberInfoProvider.IsMemberOfGroup(invitation.InvitedUserID, invitation.InvitationGroupID))
                                    {
                                        // Create group member info object
                                        GroupMemberInfo groupMember = new GroupMemberInfo();
                                        groupMember.MemberInvitedByUserID = invitation.InvitedByUserID;
                                        groupMember.MemberUserID          = CMSContext.CurrentUser.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", CMSContext.CurrentSiteName);

                                                // Resolve macros
                                                MacroResolver resolver = CMSContext.CurrentResolver;
                                                resolver.SourceData = new object[] { 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.Recipients    = recipient.Email;
                                                    message.From          = EmailHelper.GetSender(template, SettingsKeyProvider.GetStringValue(CMSContext.CurrentSiteName + ".CMSNoreplyEmailAddress"));
                                                    message.Subject       = resolver.ResolveMacros(template.TemplateSubject);
                                                    message.PlainTextBody = resolver.ResolveMacros(template.TemplatePlainText);

                                                    // Enable macro encoding for body
                                                    resolver.EncodeResolvedValues = true;
                                                    message.Body          = resolver.ResolveMacros(template.TemplateText);
                                                    message.CcRecipients  = template.TemplateCc;
                                                    message.BccRecipients = template.TemplateBcc;
                                                    message.EmailFormat   = EmailFormatEnum.Default;

                                                    MetaFileInfoProvider.ResolveMetaFileImages(message, template.TemplateID, EmailObjectType.EMAILTEMPLATE, MetaFileInfoProvider.OBJECT_CATEGORY_TEMPLATE);
                                                    EmailSender.SendEmail(CMSContext.CurrentSiteName, message);
                                                }
                                            }

                                            if (SendDefaultGroupEmails)
                                            {
                                                // Send join or leave notification
                                                if (group.GroupSendJoinLeaveNotification &&
                                                    (groupMember.MemberStatus == GroupMemberStatus.Approved))
                                                {
                                                    GroupMemberInfoProvider.SendNotificationMail("Groups.MemberJoin", CMSContext.CurrentSiteName, groupMember, true);
                                                    GroupMemberInfoProvider.SendNotificationMail("Groups.MemberJoinedConfirmation", CMSContext.CurrentSiteName, groupMember, false);
                                                }

                                                // Send 'waiting for approval' notification
                                                if (group.GroupSendWaitingForApprovalNotification && (groupMember.MemberStatus == GroupMemberStatus.WaitingForApproval))
                                                {
                                                    GroupMemberInfoProvider.SendNotificationMail("Groups.MemberWaitingForApproval", CMSContext.CurrentSiteName, groupMember, true);
                                                    GroupMemberInfoProvider.SendNotificationMail("Groups.MemberJoinedWaitingForApproval", CMSContext.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=" + CMSContext.CurrentUser.UserID + " OR InvitationUserEmail = N'" + SqlHelperClass.GetSafeQueryString(CMSContext.CurrentUser.Email, false) + "')";
                                        InvitationInfoProvider.DeleteInvitations(whereCondition);

                                        // Log activity
                                        LogJoinActivity(groupMember, group);
                                    }
                                    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;
                    }
                }
            }
        }
    }
Beispiel #10
0
    /// <summary>
    /// OK click handler (Proceed registration).
    /// </summary>
    void btnRegister_Click(object sender, EventArgs e)
    {
        if ((this.PageManager.ViewMode == ViewModeEnum.Design) || (this.HideOnCurrentPage) || (!this.IsVisible))
        {
            // Do not process
        }
        else
        {
            // Ban IP addresses which are blocked for registration
            if (!BannedIPInfoProvider.IsAllowed(CMSContext.CurrentSiteName, BanControlEnum.Registration))
            {
                lblError.Visible = true;
                lblError.Text    = GetString("banip.ipisbannedregistration");
                return;
            }

            // Check if captcha is required
            if (this.DisplayCaptcha)
            {
                // Verify captcha text
                if (!captchaElem.IsValid())
                {
                    // Display error message if catcha text is not valid
                    lblError.Visible = true;
                    lblError.Text    = GetString("Webparts_Membership_RegistrationForm.captchaError");
                    return;
                }
                else
                {
                    // Generate new code and clear captcha textbox if cpatcha code is valid
                    captchaElem.GenerateNew();
                }
            }

            string userName   = String.Empty;
            string nickName   = String.Empty;
            string firstName  = String.Empty;
            string lastName   = String.Empty;
            string emailValue = String.Empty;

            // Check duplicit user
            // 1. Find appropriate control and get its value (i.e. user name)
            // 2. Try to find user info
            EditingFormControl txtUserName = formUser.BasicForm.FieldEditingControls["UserName"] as EditingFormControl;
            if (txtUserName != null)
            {
                userName = ValidationHelper.GetString(txtUserName.Value, String.Empty);
            }

            EditingFormControl txtNickName = formUser.BasicForm.FieldEditingControls["UserNickName"] as EditingFormControl;
            if (txtNickName != null)
            {
                nickName = ValidationHelper.GetString(txtNickName.Value, String.Empty);
            }

            EditingFormControl txtEmail = formUser.BasicForm.FieldEditingControls["Email"] as EditingFormControl;
            if (txtEmail != null)
            {
                emailValue = ValidationHelper.GetString(txtEmail.Value, String.Empty);
            }

            EditingFormControl txtFirstName = formUser.BasicForm.FieldEditingControls["FirstName"] as EditingFormControl;
            if (txtFirstName != null)
            {
                firstName = ValidationHelper.GetString(txtFirstName.Value, String.Empty);
            }

            EditingFormControl txtLastName = formUser.BasicForm.FieldEditingControls["LastName"] as EditingFormControl;
            if (txtLastName != null)
            {
                lastName = ValidationHelper.GetString(txtLastName.Value, String.Empty);
            }

            // Test if "global" or "site" user exists.
            SiteInfo si     = CMSContext.CurrentSite;
            UserInfo siteui = UserInfoProvider.GetUserInfo(UserInfoProvider.EnsureSitePrefixUserName(userName, si));
            if ((UserInfoProvider.GetUserInfo(userName) != null) || (siteui != null))
            {
                lblError.Visible = true;
                lblError.Text    = GetString("Webparts_Membership_RegistrationForm.UserAlreadyExists").Replace("%%name%%", HTMLHelper.HTMLEncode(Functions.GetFormattedUserName(userName, true)));
                return;
            }

            // Check for reserved user names like administrator, sysadmin, ...
            if (UserInfoProvider.NameIsReserved(CMSContext.CurrentSiteName, userName))
            {
                lblError.Visible = true;
                lblError.Text    = GetString("Webparts_Membership_RegistrationForm.UserNameReserved").Replace("%%name%%", HTMLHelper.HTMLEncode(Functions.GetFormattedUserName(userName, true)));
                return;
            }

            if (UserInfoProvider.NameIsReserved(CMSContext.CurrentSiteName, nickName))
            {
                lblError.Visible = true;
                lblError.Text    = GetString("Webparts_Membership_RegistrationForm.UserNameReserved").Replace("%%name%%", HTMLHelper.HTMLEncode(nickName));
                return;
            }

            // Check limitations for site members
            if (!UserInfoProvider.LicenseVersionCheck(URLHelper.GetCurrentDomain(), FeatureEnum.SiteMembers, VersionActionEnum.Insert, false))
            {
                lblError.Visible = true;
                lblError.Text    = GetString("License.MaxItemsReachedSiteMember");
                return;
            }

            // Check whether email is unique if it is required
            string checkSites = (String.IsNullOrEmpty(this.AssignToSites)) ? CMSContext.CurrentSiteName : this.AssignToSites;
            if (!UserInfoProvider.IsEmailUnique(emailValue, checkSites, 0))
            {
                lblError.Visible = true;
                lblError.Text    = GetString("UserInfo.EmailAlreadyExist");
                return;
            }

            // Validate and save form with new user data
            if (!formUser.Save())
            {
                // Return if saving failed
                return;
            }

            // Get user info from form
            UserInfo ui = (UserInfo)formUser.Info;

            // Add user prefix if settings is on
            // Ensure site prefixes
            if (UserInfoProvider.UserNameSitePrefixEnabled(CMSContext.CurrentSiteName))
            {
                ui.UserName = UserInfoProvider.EnsureSitePrefixUserName(userName, si);
            }

            ui.PreferredCultureCode = "";
            ui.Enabled  = this.EnableUserAfterRegistration;
            ui.IsEditor = false;
            ui.IsGlobalAdministrator = false;
            ui.UserURLReferrer       = CMSContext.CurrentUser.URLReferrer;
            ui.UserCampaign          = CMSContext.Campaign;

            // Fill optionally full user name
            if (String.IsNullOrEmpty(ui.FullName))
            {
                string fullName = "";
                if (ui.FirstName.Trim() != "")
                {
                    fullName += ui.FirstName;
                }

                if (ui.MiddleName.Trim() != "")
                {
                    fullName += " " + ui.MiddleName;
                }

                if (ui.LastName.Trim() != "")
                {
                    fullName += " " + ui.LastName;
                }
                ui.FullName = fullName;
            }

            // Ensure nick name
            if (ui.UserNickName.Trim() == "")
            {
                ui.UserNickName = Functions.GetFormattedUserName(ui.UserName, true);
            }

            ui.UserSettings.UserRegistrationInfo.IPAddress = HTTPHelper.UserHostAddress;
            ui.UserSettings.UserRegistrationInfo.Agent     = HttpContext.Current.Request.UserAgent;
            ui.UserSettings.UserLogActivities    = true;
            ui.UserSettings.UserShowSplashScreen = true;

            // Check whether confirmation is required
            bool requiresConfirmation = SettingsKeyProvider.GetBoolValue(CMSContext.CurrentSiteName + ".CMSRegistrationEmailConfirmation");
            bool requiresAdminApprove = SettingsKeyProvider.GetBoolValue(CMSContext.CurrentSiteName + ".CMSRegistrationAdministratorApproval");
            if (!requiresConfirmation)
            {
                // If confirmation is not required check whether administration approval is reqiures
                if (requiresAdminApprove)
                {
                    ui.Enabled = false;
                    ui.UserSettings.UserWaitingForApproval = true;
                }
            }
            else
            {
                // EnableUserAfterRegistration is overrided by requiresConfirmation - user needs to be confirmed before enable
                ui.Enabled = false;
            }

            // Set user's starting alias path
            if (!String.IsNullOrEmpty(this.StartingAliasPath))
            {
                ui.UserStartingAliasPath = CMSContext.ResolveCurrentPath(this.StartingAliasPath);
            }

            // Get user password and save it in apropriate format after form save
            string password = ValidationHelper.GetString(ui.GetValue("UserPassword"), String.Empty);
            UserInfoProvider.SetPassword(ui, password);

            #region "Welcome Emails (confirmation, waiting for approval)"

            bool              error    = false;
            EventLogProvider  ev       = new EventLogProvider();
            EmailTemplateInfo template = null;

            // Prepare macro replacements
            string[,] replacements = new string[6, 2];
            replacements[0, 0]     = "confirmaddress";
            replacements[0, 1]     = (this.ApprovalPage != String.Empty) ? URLHelper.GetAbsoluteUrl(this.ApprovalPage) + "?userguid=" + ui.UserGUID : URLHelper.GetAbsoluteUrl("~/CMSPages/Dialogs/UserRegistration.aspx") + "?userguid=" + ui.UserGUID;
            replacements[1, 0]     = "username";
            replacements[1, 1]     = userName;
            replacements[2, 0]     = "password";
            replacements[2, 1]     = password;
            replacements[3, 0]     = "Email";
            replacements[3, 1]     = emailValue;
            replacements[4, 0]     = "FirstName";
            replacements[4, 1]     = firstName;
            replacements[5, 0]     = "LastName";
            replacements[5, 1]     = lastName;

            // Set resolver
            ContextResolver resolver = CMSContext.CurrentResolver;
            resolver.SourceParameters = replacements;

            // Email message
            EmailMessage emailMessage = new EmailMessage();
            emailMessage.EmailFormat = EmailFormatEnum.Default;
            emailMessage.Recipients  = ui.Email;

            // Send welcome message with username and password, with confirmation link, user must confirm registration
            if (requiresConfirmation)
            {
                template             = EmailTemplateProvider.GetEmailTemplate("RegistrationConfirmation", CMSContext.CurrentSiteName);
                emailMessage.Subject = GetString("RegistrationForm.RegistrationConfirmationEmailSubject");
            }
            // Send welcome message with username and password, with information that user must be approved by administrator
            else if (this.SendWelcomeEmail)
            {
                if (requiresAdminApprove)
                {
                    template             = EmailTemplateProvider.GetEmailTemplate("Membership.RegistrationWaitingForApproval", CMSContext.CurrentSiteName);
                    emailMessage.Subject = GetString("RegistrationForm.RegistrationWaitingForApprovalSubject");
                }
                // Send welcome message with username and password, user can logon directly
                else
                {
                    template             = EmailTemplateProvider.GetEmailTemplate("Membership.Registration", CMSContext.CurrentSiteName);
                    emailMessage.Subject = GetString("RegistrationForm.RegistrationSubject");
                }
            }

            if (template != null)
            {
                emailMessage.From = EmailHelper.GetSender(template, SettingsKeyProvider.GetStringValue(CMSContext.CurrentSiteName + ".CMSNoreplyEmailAddress"));
                // Enable macro encoding for body
                resolver.EncodeResolvedValues = true;
                emailMessage.Body             = resolver.ResolveMacros(template.TemplateText);
                // Disable macro encoding for plaintext body and subject
                resolver.EncodeResolvedValues = false;
                emailMessage.PlainTextBody    = resolver.ResolveMacros(template.TemplatePlainText);
                emailMessage.Subject          = resolver.ResolveMacros(EmailHelper.GetSubject(template, emailMessage.Subject));

                emailMessage.CcRecipients  = template.TemplateCc;
                emailMessage.BccRecipients = template.TemplateBcc;

                try
                {
                    MetaFileInfoProvider.ResolveMetaFileImages(emailMessage, template.TemplateID, EmailObjectType.EMAILTEMPLATE, MetaFileInfoProvider.OBJECT_CATEGORY_TEMPLATE);
                    // Send the e-mail immediately
                    EmailSender.SendEmail(CMSContext.CurrentSiteName, emailMessage, true);
                }
                catch (Exception ex)
                {
                    ev.LogEvent("E", "RegistrationForm - SendEmail", ex);
                    error = true;
                }
            }

            // If there was some error, user must be deleted
            if (error)
            {
                lblError.Visible = true;
                lblError.Text    = GetString("RegistrationForm.UserWasNotCreated");

                // Email was not send, user can't be approved - delete it
                UserInfoProvider.DeleteUser(ui);
                return;
            }

            #endregion

            #region "Administrator notification email"

            // Notify administrator if enabled and email confirmation is not required
            if (!requiresConfirmation && this.NotifyAdministrator && (this.FromAddress != String.Empty) && (this.ToAddress != String.Empty))
            {
                EmailTemplateInfo mEmailTemplate = null;

                if (requiresAdminApprove)
                {
                    mEmailTemplate = EmailTemplateProvider.GetEmailTemplate("Registration.Approve", CMSContext.CurrentSiteName);
                }
                else
                {
                    mEmailTemplate = EmailTemplateProvider.GetEmailTemplate("Registration.New", CMSContext.CurrentSiteName);
                }

                if (mEmailTemplate == null)
                {
                    ev.LogEvent("E", DateTime.Now, "RegistrationForm", "GetEmailTemplate", HTTPHelper.GetAbsoluteUri());
                }
                //email template ok
                else
                {
                    replacements       = new string[4, 2];
                    replacements[0, 0] = "firstname";
                    replacements[0, 1] = ui.FirstName;
                    replacements[1, 0] = "lastname";
                    replacements[1, 1] = ui.LastName;
                    replacements[2, 0] = "email";
                    replacements[2, 1] = ui.Email;
                    replacements[3, 0] = "username";
                    replacements[3, 1] = userName;

                    // Set resolver
                    resolver = CMSContext.CurrentResolver;
                    resolver.SourceParameters = replacements;
                    // Enable macro encoding for body
                    resolver.EncodeResolvedValues = true;

                    EmailMessage message = new EmailMessage();
                    message.EmailFormat = EmailFormatEnum.Default;
                    message.From        = EmailHelper.GetSender(mEmailTemplate, this.FromAddress);
                    message.Recipients  = this.ToAddress;
                    message.Body        = resolver.ResolveMacros(mEmailTemplate.TemplateText);
                    // Disable macro encoding for plaintext body and subject
                    resolver.EncodeResolvedValues = false;
                    message.Subject       = resolver.ResolveMacros(EmailHelper.GetSubject(mEmailTemplate, GetString("RegistrationForm.EmailSubject")));
                    message.PlainTextBody = resolver.ResolveMacros(mEmailTemplate.TemplatePlainText);

                    message.CcRecipients  = mEmailTemplate.TemplateCc;
                    message.BccRecipients = mEmailTemplate.TemplateBcc;

                    try
                    {
                        // Attach template meta-files to e-mail
                        MetaFileInfoProvider.ResolveMetaFileImages(message, mEmailTemplate.TemplateID, EmailObjectType.EMAILTEMPLATE, MetaFileInfoProvider.OBJECT_CATEGORY_TEMPLATE);
                        EmailSender.SendEmail(CMSContext.CurrentSiteName, message);
                    }
                    catch
                    {
                        ev.LogEvent("E", DateTime.Now, "Membership", "RegistrationEmail", CMSContext.CurrentSite.SiteID);
                    }
                }
            }

            #endregion

            #region "Web analytics"

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

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

            // Log registered user if confirmation is not required
            if (!requiresConfirmation)
            {
                AnalyticsHelper.LogRegisteredUser(CMSContext.CurrentSiteName, ui);
            }

            #endregion

            #region "On-line marketing - activity"

            // Log registered user if confirmation is not required
            if (!requiresConfirmation)
            {
                string siteName = CMSContext.CurrentSiteName;
                if (ActivitySettingsHelper.ActivitiesEnabledAndModuleLoaded(siteName))
                {
                    int contactId = 0;
                    // Log registration activity
                    if (ActivitySettingsHelper.UserRegistrationEnabled(siteName))
                    {
                        if (ActivitySettingsHelper.ActivitiesEnabledForThisUser(ui))
                        {
                            contactId = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui);
                            ActivityLogProvider.LogRegistrationActivity(contactId,
                                                                        ui, URLHelper.CurrentRelativePath, CMSContext.CurrentDocument.DocumentID, siteName, CMSContext.Campaign, CMSContext.CurrentDocument.DocumentCulture);
                        }
                    }

                    // Log login activity
                    if (ui.Enabled && ActivitySettingsHelper.UserLoginEnabled(siteName))
                    {
                        if (contactId <= 0)
                        {
                            contactId = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui);
                        }
                        ActivityLogHelper.UpdateContactLastLogon(contactId);    // Update last logon time
                        if (ActivitySettingsHelper.ActivitiesEnabledForThisUser(ui))
                        {
                            ActivityLogProvider.LogLoginActivity(contactId,
                                                                 ui, URLHelper.CurrentRelativePath, CMSContext.CurrentDocument.DocumentID, siteName, CMSContext.Campaign, CMSContext.CurrentDocument.DocumentCulture);
                        }
                    }
                }
            }

            #endregion

            #region "Site and roles addition and authentication"

            string[] roleList = this.AssignRoles.Split(';');
            string[] siteList;

            // If AssignToSites field set
            if (!String.IsNullOrEmpty(this.AssignToSites))
            {
                siteList = this.AssignToSites.Split(';');
            }
            else // If not set user current site
            {
                siteList = new string[] { CMSContext.CurrentSiteName };
            }

            foreach (string siteName in siteList)
            {
                // Add new user to the current site
                UserInfoProvider.AddUserToSite(ui.UserName, siteName);
                foreach (string roleName in roleList)
                {
                    if (!String.IsNullOrEmpty(roleName))
                    {
                        String sn = roleName.StartsWith(".") ? "" : siteName;

                        // Add user to desired roles
                        if (RoleInfoProvider.RoleExists(roleName, sn))
                        {
                            UserInfoProvider.AddUserToRole(ui.UserName, roleName, sn);
                        }
                    }
                }
            }

            if (this.DisplayMessage.Trim() != String.Empty)
            {
                pnlRegForm.Visible = false;
                lblInfo.Visible    = true;
                lblInfo.Text       = this.DisplayMessage;
            }
            else
            {
                if (ui.Enabled)
                {
                    CMSContext.AuthenticateUser(ui.UserName, true);
                }

                string returnUrl = QueryHelper.GetString("ReturnURL", "");
                if (!String.IsNullOrEmpty(returnUrl) && (returnUrl.StartsWith("~") || returnUrl.StartsWith("/") || QueryHelper.ValidateHash("hash")))
                {
                    URLHelper.Redirect(HttpUtility.UrlDecode(returnUrl));
                }
                else if (this.RedirectToURL != String.Empty)
                {
                    URLHelper.Redirect(this.RedirectToURL);
                }
            }

            #endregion

            lblError.Visible = false;
        }
    }