/// <summary>
 /// Sending the emails based on datasource
 /// </summary>
 /// <param name="campaignName"></param>
 /// <param name="reciepientEmail"></param>
 /// <param name="templateName"></param>
 public static void SendEmailNotification <T>(string templateName, string recipientEmail, IEnumerable <T> emailDataSource, string dataSourceName, Dictionary <string, object> macroData = null)
 {
     try
     {
         var          email     = DIContainer.Resolve <IKenticoMailProvider>().GetEmailTemplate(templateName, SiteContext.CurrentSiteID);
         var          itemTable = ConvertToDataTable(emailDataSource.ToList());
         EmailMessage msg       = new EmailMessage();
         if (email != null)
         {
             MacroResolver resolver = MacroResolver.GetInstance();
             resolver.SetNamedSourceData(dataSourceName, itemTable.Rows);
             resolver.SetNamedSourceData(macroData);
             msg.From        = resolver.ResolveMacros(email.TemplateFrom);
             msg.Recipients  = recipientEmail;
             msg.EmailFormat = EmailFormatEnum.Default;
             msg.ReplyTo     = resolver.ResolveMacros(email.TemplateReplyTo);
             msg.Subject     = resolver.ResolveMacros(email.TemplateSubject);
             msg.Body        = resolver.ResolveMacros(email.TemplateText);
             EmailSender.SendEmail(SiteContext.CurrentSite.SiteName, msg, true);
         }
     }
     catch (Exception ex)
     {
         EventLogProvider.LogException("ProductEmailNotifications", "SendEmail", ex, SiteContext.CurrentSite.SiteID, ex.Message);
     }
 }
 /// <summary>
 /// Sending the emails to users for campaign open/close
 /// </summary>
 /// <param name="campaignName"></param>
 /// <param name="reciepientEmail"></param>
 /// <param name="templateName"></param>
 public static void CampaignEmail(string campaignName, string recipientEmail, string templateName, string programName = "")
 {
     try
     {
         TreeProvider tree  = new TreeProvider(MembershipContext.AuthenticatedUser);
         var          email = EmailTemplateProvider.GetEmailTemplate(templateName, SiteContext.CurrentSite.SiteName);
         EmailMessage msg   = new EmailMessage();
         if (email != null)
         {
             MacroResolver resolver = MacroResolver.GetInstance();
             resolver.SetNamedSourceData("CampaignName", campaignName);
             resolver.SetNamedSourceData("programName", programName);
             msg.From        = resolver.ResolveMacros(email.TemplateFrom);
             msg.Recipients  = recipientEmail;
             msg.EmailFormat = EmailFormatEnum.Default;
             msg.ReplyTo     = resolver.ResolveMacros(email.TemplateReplyTo);
             msg.Subject     = resolver.ResolveMacros(email.TemplateSubject);
             msg.Body        = resolver.ResolveMacros(email.TemplateText);
             EmailSender.SendEmail(SiteContext.CurrentSite.SiteName, msg, true);
         }
     }
     catch (Exception ex)
     {
         EventLogProvider.LogException("ProductEmailNotifications", "CampaignEmail", ex, SiteContext.CurrentSite.SiteID, ex.Message);
     }
 }
Example #3
0
    /// <summary>
    /// Registers NamedDataSource to a given resolver under the specified name.
    /// </summary>
    /// <param name="resolver">Resolver object</param>
    /// <param name="name">Name of the macro - object will be accessible by this name in the resolver</param>
    /// <param name="className">Class name of the object (for the AutoCompletion to work properly)</param>
    private static void RegisterObject(this MacroResolver resolver, string name, string className)
    {
        BaseInfo obj = CMSObjectHelper.GetReadOnlyObject(className);

        if (obj != null)
        {
            resolver.SetNamedSourceData(name, obj);
        }
        else
        {
            resolver.SetNamedSourceData(name, new SimpleDataClass(className));
        }
    }
Example #4
0
    protected void Page_Load(object sender, EventArgs e)
    {
        // create a new instnace of the resolver
        MacroResolver resolver = new MacroResolver();

        // set all the available values within the template
        resolver.SetNamedSourceData("company", "*****@*****.**");
        resolver.SetNamedSourceData("contact", "Test");
        //resolver.SetNamedSourceData("eventstartdate", eventDateTime);
        //resolver.SetNamedSourceData("eventsubmissiontime", eventSubmissionDateTime);
        resolver.SetNamedSourceData("eventname", "testEvent SME  Name");

        SendEmail("EventSubmission", resolver, "*****@*****.**");
    }
    protected object grid_OnExternalDataBound(object sender, string sourceName, object parameter)
    {
        DataRowView drv = null;

        if (parameter is DataRowView)
        {
            drv = (DataRowView)parameter;
        }
        else if (parameter is GridViewRow)
        {
            drv = (DataRowView)((GridViewRow)parameter).DataItem;
        }

        var objectSettingsId = ValidationHelper.GetInteger(drv["ObjectSettingsID"], 0);

        if ((tmpObjectSettings == null) || (tmpObjectSettings.ObjectSettingsID != objectSettingsId))
        {
            tmpObjectSettings = ObjectSettingsInfo.Provider.Get(objectSettingsId);
            if (tmpObjectSettings != null)
            {
                tmpInfo = ProviderHelper.GetInfoById(tmpObjectSettings.ObjectSettingsObjectType, tmpObjectSettings.ObjectSettingsObjectID);
            }
        }

        if ((tmpInfo != null) && (tmpObjectSettings != null))
        {
            contextResolver.SetNamedSourceData("EditedObject", tmpInfo);

            switch (sourceName.ToLowerCSafe())
            {
            case "checkin":
                var checkinButton = (CMSGridActionButton)sender;

                if (tmpInfo.TypeInfo.SupportsLocking)
                {
                    checkinButton.OnClientClick = GetConfirmScript(GetString("ObjectEditMenu.CheckInConfirmation"), tmpObjectSettings.ObjectSettingsObjectType, tmpObjectSettings.ObjectSettingsObjectID, btnCheckIn);
                }
                else
                {
                    checkinButton.Enabled = false;
                }
                break;

            case "undocheckout":
                var undoCheckoutButton = (CMSGridActionButton)sender;

                if (tmpInfo.TypeInfo.SupportsLocking)
                {
                    undoCheckoutButton.OnClientClick = GetConfirmScript(CMSObjectManager.GetUndoCheckOutConfirmation(tmpInfo, null), tmpObjectSettings.ObjectSettingsObjectType, tmpObjectSettings.ObjectSettingsObjectID, btnUndoCheckOut);
                }
                else
                {
                    undoCheckoutButton.Enabled = false;
                }
                break;
            }
        }

        return(parameter);
    }
    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);
        ContactInfo   contact  = new ContactInfo();
        MacroResolver resolver = MacroContext.CurrentResolver.CreateChild();

        resolver.SetNamedSourceData("Contact", contact);
        DescriptionMacroEditor.Resolver        = resolver;
        DescriptionMacroEditor.Editor.Language = LanguageEnum.Text;
    }
        public string GetPageBuilderContainerAfter(object ComponentModel)
        {
            string HtmlContainer = "";
            string HtmlWrapper   = "";

            if (ComponentModel is IHtmlBeforeAfterContainerProperties HtmlBeforeAfterProps)
            {
                if (!string.IsNullOrWhiteSpace(HtmlBeforeAfterProps.HtmlAfter))
                {
                    HtmlWrapper = HtmlBeforeAfterProps.HtmlAfter;
                    // Apply macro engine if needed
                    if (HtmlWrapper.IndexOf("{") > -1)
                    {
                        MacroResolver Resolver = MacroResolver.GetInstance();
                        //HtmlWrapper = Resolver.ResolveMacros(HtmlWrapper, new EvaluationContext(Resolver, HtmlWrapper));
                        HtmlWrapper = Resolver.ResolveMacros(HtmlWrapper);
                    }
                }
            }
            if (ComponentModel is IPageBuilderContainerProperties ContainerProps)
            {
                if (!string.IsNullOrWhiteSpace(ContainerProps.ContainerName))
                {
                    var           Container = GetPageBuilderContainer(ContainerProps.ContainerName);
                    MacroResolver Resolver  = MacroResolver.GetInstance();
                    if (Container != null)
                    {
                        Resolver.SetNamedSourceData("ContainerTitle", ContainerProps.ContainerTitle);
                        Resolver.SetNamedSourceData("ContainerCustomContent", ContainerProps.ContainerCustomContent);
                        Resolver.SetNamedSourceData("ContainerCSSClass", ContainerProps.ContainerCSSClass);
                        HtmlContainer = Resolver.ResolveMacros(Container.ContainerTextAfter);
                    }
                }
            }
            return(HtmlContainer + HtmlWrapper);
        }
    /// <summary>
    /// Renders any IHtmlBeforeAfterContainerProperties and IPageBuilderContainerProperties
    /// </summary>
    /// <param name="helper">Html Helper</param>
    /// <param name="ComponentModel">The component model object that should inherit IHtmlBeforeAfterContainerProperties and/or IPageBuilderContainerProperties</param>
    /// <returns>The content after the component</returns>
    public static MvcHtmlString PageBuilderContainerAfter(this HtmlHelper helper, object ComponentModel)
    {
        string HtmlContainer = "";
        string HtmlWrapper   = "";

        if (ComponentModel is IHtmlBeforeAfterContainerProperties HtmlBeforeAfterProps)
        {
            if (!string.IsNullOrWhiteSpace(HtmlBeforeAfterProps.HtmlAfter))
            {
                HtmlWrapper = HtmlBeforeAfterProps.HtmlAfter;
                // Apply macro engine if needed
                if (HtmlWrapper.IndexOf("{") > -1)
                {
                    MacroResolver Resolver = MacroResolver.GetInstance();
                    HtmlWrapper = Resolver.ResolveMacros(HtmlWrapper);
                }
            }
        }
        if (ComponentModel is IPageBuilderContainerProperties ContainerProps)
        {
            if (!string.IsNullOrWhiteSpace(ContainerProps.ContainerName))
            {
                var           Container = GetPageBuilderContainer(ContainerProps.ContainerName);
                MacroResolver Resolver  = MacroResolver.GetInstance();
                if (Container != null)
                {
                    Resolver.SetNamedSourceData("ContainerTitle", ContainerProps.ContainerTitle);
                    Resolver.SetNamedSourceData("ContainerCustomContent", ContainerProps.ContainerCustomContent);
                    Resolver.SetNamedSourceData("ContainerCSSClass", ContainerProps.ContainerCSSClass);
                    string StyleContent = (!string.IsNullOrWhiteSpace(Container.ContainerCSS) ? string.Format("<style>{0}</style>", Container.ContainerCSS) : "");
                    HtmlContainer = StyleContent + Resolver.ResolveMacros(Container.ContainerTextAfter);
                }
            }
        }
        return(new MvcHtmlString(HtmlContainer + HtmlWrapper));
    }
Example #9
0
    private bool TrySendPasswordResetEmail(UserInfo userInfo)
    {
        string returnUrl = RequestContext.CurrentURL;

        returnUrl = URLHelper.AddParameterToUrl(returnUrl, "username", userInfo.UserName);

        bool success;

        MacroResolver macros = MacroResolver.GetInstance();

        macros.SetNamedSourceData("Username", userInfo.UserName);
        var resolvedURL = Request.Url.Scheme + System.Uri.SchemeDelimiter + Request.Url.Host + ResolveUrl(ResetPasswordURL);
        var result      = AuthenticationHelper.ForgottenEmailRequest(userInfo.UserName, SiteContext.CurrentSiteName, "RECOVERPASSWORDFORM", FromEmailAddress, macros, resolvedURL, out success);

        return(success);
    }
Example #10
0
    private MacroResolver GetNodeMacroResolver(int NodeID, string ClassName)
    {
        string Culture = URLHelper.GetQueryValue(Request.RawUrl, "culture");

        return(CacheHelper.Cache <MacroResolver>(cs =>
        {
            MacroResolver resolver = MacroResolver.GetInstance();

            List <string> Columns = new List <string>();

            if (!string.IsNullOrWhiteSpace(ToolTipFormat))
            {
                Columns.AddRange(DataHelper.GetNotEmpty(MacroProcessor.GetMacros(ToolTipFormat, true), "NodeName").Split(';'));
            }
            if (!string.IsNullOrWhiteSpace(DisplayNameFormat))
            {
                Columns.AddRange(DataHelper.GetNotEmpty(MacroProcessor.GetMacros(DisplayNameFormat, true), "NodeName").Split(';'));
            }
            // Get data for this node and render it out
            DataSet FullData = new DocumentQuery(ClassName)
                               .WhereEquals("NodeID", NodeID)
                               .Columns(Columns)
                               .Culture(Culture)
                               .CombineWithDefaultCulture(true).Result;

            foreach (DataColumn item in FullData.Tables[0].Columns)
            {
                resolver.SetNamedSourceData(item.ColumnName, FullData.Tables[0].Rows[0][item.ColumnName]);
            }

            if (cs.Cached)
            {
                cs.CacheDependency = CacheHelper.GetCacheDependency("nodeid|" + NodeID);
            }
            return resolver;
        }, new CacheSettings(CacheHelper.CacheMinutes(SiteContext.CurrentSiteName), "RelationshipTree_GetNodeMacroResolver", NodeID, Culture, ToolTipFormat, DisplayNameFormat)));
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        /* try
         * {
         *   Ektron.Cms.UserAPI userApi = new UserAPI();
         *   if (userApi.IsLoggedIn && userApi.UserId > 0)
         *   {
         *       loggegedin = true;
         *   }
         *
         *   ////Cache Implementation
         *
         *   IEnumerable<RootObject> data = null;
         *   string CacheKey = "Aspen::Pages:Discussions";
         *
         *
         *               string url = "https://api.connectedcommunity.org/api/v1.0/Discussions/GetLatestDiscussionPosts?maxToRetrieve={5}";
         *               var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
         *               httpWebRequest.ContentType = "application/json";
         *               httpWebRequest.Method = "GET";
         *               httpWebRequest.Headers.Add("HLIAMKey", HLIAMKey);
         *               httpWebRequest.Headers.Add("HLAuthToken", getToken());
         *
         *               var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
         *               using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
         *               {
         *                   var responseText = streamReader.ReadToEnd();
         *                   var j = JsonConvert.DeserializeObject<List<RootObject>>(responseText);
         *                   var top_three = (from person in j
         *                                    select person).Take(Maxresults);
         *                   data = top_three.OrderByDescending(x => x.DatePosted).ToList();
         *
         *               }
         *
         *
         #region "binding"
         *   if (AsList)
         *   {
         *       rptasList.DataSource = data;
         *       rptasList.DataBind();
         *       dataRepeater.Visible = false;
         *   }
         *   else
         *   {
         *
         *       rptasList.Visible = false;
         *       dataRepeater.DataSource = data;
         *       dataRepeater.DataBind();
         *   }
         *
         #endregion
         * }
         * catch (Exception ex)
         * {
         * }
         */
        // create a new instnace of the resolver
        MacroResolver resolver = new MacroResolver();

        // set all the available values within the template
        resolver.SetNamedSourceData("company", "*****@*****.**");
        resolver.SetNamedSourceData("contact", "Test");
        //resolver.SetNamedSourceData("eventstartdate", eventDateTime);
        //resolver.SetNamedSourceData("eventsubmissiontime", eventSubmissionDateTime);
        resolver.SetNamedSourceData("eventname", "testEvent Name");

        SendEmail("EventSubmission", resolver, "*****@*****.**");
    }
Example #12
0
    /// <summary>
    /// Render override.
    /// </summary>
    protected override void Render(HtmlTextWriter writer)
    {
        // if everything ok, email should be send
        if (mSendEmail)
        {
            StringBuilder    sb      = new StringBuilder();
            StringWriter     sw      = new StringWriter(sb);
            Html32TextWriter mwriter = new Html32TextWriter(sw);
            repItems.RenderControl(mwriter);

            repItems.Visible = false;

            // Prepare the macro resolver
            MacroResolver resolver = ContextResolver.CreateChild();

            string[,] replacements = new string[2, 2];
            // Prepare macro replacements
            replacements[0, 0] = "message";
            replacements[0, 1] = txtMessageText.Text;
            replacements[1, 0] = "document";
            replacements[1, 1] = URLHelper.MakeLinksAbsolute(sb.ToString());

            resolver.SetNamedSourceData(replacements);

            if (EmailTemplate != null)
            {
                EmailMessage message = new EmailMessage();
                message.EmailFormat = EmailFormatEnum.Html;

                message.From       = EmailFrom;
                message.Recipients = txtEmailTo.Text;

                // Get current css stylesheet
                string styleSheet = GetCssFileLink();
                if (!String.IsNullOrEmpty(styleSheet))
                {
                    styleSheet = URLHelper.MakeLinksAbsolute(styleSheet);
                }

                // resolve EmailSubject here
                message.Subject = resolver.ResolveMacros(EmailSubject);
                // resolve EmailTemplate, wrap to HTML code and add the CSS files
                message.Body = "<html><head>" + styleSheet + "</head><body class=\"EmailBody\">" + resolver.ResolveMacros(EmailTemplate) + "</body></html>";

                // check recipients
                if ((message.Recipients != null) && (message.Recipients.Trim() != ""))
                {
                    try
                    {
                        EmailSender.SendEmail(SiteContext.CurrentSiteName, message);

                        // Display message, email was sent successfully
                        lblInfo.Text        = GetString("sendtofriend.emailsent");
                        txtEmailTo.Text     = "";
                        txtMessageText.Text = "";

                        if (HideAfterEmailSent)
                        {
                            plcForm.Visible = false;
                        }
                    }
                    catch (Exception ex)
                    {
                        lblError.Text = GetString("SendToFriend.SendEmailError");
                        try
                        {
                            EventLogProvider.LogException("Send email", "SendToFriend", ex);
                        }
                        catch
                        {
                            // Unable to log the event
                        }
                    }
                }
            }
        }

        base.Render(writer);
    }
Example #13
0
    /// <summary>
    /// Saves the data.
    /// </summary>
    /// <param name="newsletterName">Newsletter name</param>
    /// <param name="sb">Subscriber</param>
    private bool Save(string newsletterName, SubscriberInfo sb)
    {
        bool toReturn = false;
        int  siteId   = SiteContext.CurrentSiteID;

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

        // Get nesletter info
        NewsletterInfo news = NewsletterInfoProvider.GetNewsletterInfo(newsletterName, siteId);

        if (news != null)
        {
            // Init webpart resolver
            object[] data = new object[3];
            data[0] = news;
            data[1] = sb;

            MacroResolver resolver = ContextResolver;
            resolver.SetNamedSourceData("Newsletter", news);
            resolver.SetNamedSourceData("Subscriber", sb);
            if (AllowUserSubscribers && isAuthenticated)
            {
                data[2] = CurrentUser;
                resolver.SetNamedSourceData("User", CurrentUser);
            }
            resolver.SetAnonymousSourceData(data);

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

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

                    if (!chooseMode)
                    {
                        // Display message about successful subscription
                        lblInfo.Visible = true;
                        lblInfo.Text    = SubscriptionConfirmationMessage;
                    }

                    // Track successful subscription conversion
                    if (!string.IsNullOrEmpty(TrackConversionName))
                    {
                        string siteName = SiteContext.CurrentSiteName;

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

                    // Log newsletter subscription activity if double opt-in is not required
                    if (!news.NewsletterEnableOptIn)
                    {
                        Activity activity = new ActivityNewsletterSubscribing(sb, news, AnalyticsContext.ActivityEnvironmentVariables);
                        activity.Log();
                    }
                }
                else
                {
                    lblInfo.Visible = true;
                    string message = null;

                    if (string.IsNullOrEmpty(MessageForAlreadySubscribed))
                    {
                        if (!chooseMode)
                        {
                            message = GetString("NewsletterSubscription.SubscriberIsAlreadySubscribed");
                        }
                        else
                        {
                            message = string.Format("{0} {1}.<br />", GetString("NewsletterSubscription.SubscriberIsAlreadySubscribedXY"), HTMLHelper.HTMLEncode(ResHelper.LocalizeString(news.NewsletterDisplayName)));
                        }
                    }
                    else
                    {
                        message = MessageForAlreadySubscribed;
                    }

                    // Info message - subscriber is allready in site
                    if (!chooseMode)
                    {
                        lblInfo.Text = message;
                    }
                    else
                    {
                        lblInfo.Text += message;
                    }
                }
            }
            catch (Exception ex)
            {
                lblError.Visible = true;
                lblError.Text    = ex.Message;
            }
        }
        else
        {
            lblError.Visible = true;
            lblError.Text    = GetString("NewsletterSubscription.NewsletterDoesNotExist");
        }

        return(toReturn);
    }
Example #14
0
    /// <summary>
    /// Sends e-mail with password if required.
    /// </summary>
    /// <param name="pswd">Password to send</param>
    /// <param name="userId">Not used</param>
    /// <param name="subject">Subject of the e-mail sent</param>
    /// <param name="emailType">Type of the e-mail specifying 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   = SettingsKeyInfoProvider.GetStringValue(SiteContext.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;
                }

                // 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
                            MacroResolver resolver = MacroContext.CurrentResolver;
                            resolver.SetNamedSourceData(macros);

                            // Add template attachments
                            EmailHelper.ResolveMetaFileImages(em, template.TemplateID, EmailTemplateInfo.OBJECT_TYPE, ObjectAttachmentsCategories.TEMPLATE);

                            // Send message immediately (+ resolve macros)
                            EmailSender.SendEmailWithTemplateText(SiteContext.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.LogException("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);
        }
    }
Example #15
0
    /// <summary>
    /// OK click handler (Proceed registration).
    /// </summary>
    private void btnRegister_Click(object sender, EventArgs e)
    {
        string currentSiteName = SiteContext.CurrentSiteName;

        string[] siteList = { currentSiteName };

        // If AssignToSites field set
        if (!String.IsNullOrEmpty(AssignToSites))
        {
            siteList = AssignToSites.Split(';');
        }

        if ((PageManager.ViewMode == ViewModeEnum.Design) || (HideOnCurrentPage) || (!IsVisible))
        {
            // Do not process
        }
        else
        {
            // Ban IP addresses which are blocked for registration
            if (!BannedIPInfoProvider.IsAllowed(currentSiteName, BanControlEnum.Registration))
            {
                lblError.Visible = true;
                lblError.Text    = GetString("banip.ipisbannedregistration");
                return;
            }

            // Check if captcha is required and verify captcha text
            if (DisplayCaptcha && !captchaElem.IsValid())
            {
                // Display error message if captcha text is not valid
                lblError.Visible = true;
                lblError.Text    = GetString("Webparts_Membership_RegistrationForm.captchaError");
                return;
            }

            string userName       = String.Empty;
            string nickName       = String.Empty;
            string firstName      = String.Empty;
            string lastName       = String.Empty;
            string emailValue     = String.Empty;
            string pwd            = string.Empty;
            string confPassword   = string.Empty;
            string educationLevel = String.Empty;
            string interestArea   = String.Empty;
            string industry       = String.Empty;
            string referralSource = string.Empty;

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

            FormEngineUserControl txtEmail = formUser.FieldControls["Email"];
            if (txtEmail != null)
            {
                emailValue = ValidationHelper.GetString(txtEmail.Value, String.Empty);
                userName   = emailValue;
            }

            // If user name and e-mail aren't filled stop processing and display error.
            if (string.IsNullOrEmpty(userName) && String.IsNullOrEmpty(emailValue))
            {
                formUser.StopProcessing = true;
                lblError.Visible        = true;
                lblError.Text           = GetString("customregistrationform.usernameandemail");
                return;
            }
            else
            {
                formUser.Data.SetValue("UserName", userName);
            }

            //check if email is valid
            if (!ValidationHelper.IsEmail(txtEmail.Text.ToLowerCSafe()))
            {
                lblError.Visible = true;
                lblError.Text    = GetString("Webparts_Membership_RegistrationForm.EmailIsNotValid");
                return;
            }

            FormEngineUserControl txtNickName = formUser.FieldControls["UserNickName"];
            if (txtNickName != null)
            {
                nickName = ValidationHelper.GetString(txtNickName.Value, String.Empty);
            }

            FormEngineUserControl txtFirstName = formUser.FieldControls["FirstName"];
            if (txtFirstName != null)
            {
                firstName = ValidationHelper.GetString(txtFirstName.Value, String.Empty);
            }

            FormEngineUserControl txtLastName = formUser.FieldControls["LastName"];
            if (txtLastName != null)
            {
                lastName = ValidationHelper.GetString(txtLastName.Value, String.Empty);
            }

            FormEngineUserControl txtPwd = formUser.FieldControls["UserPassword"];
            if (txtPwd != null)
            {
                pwd = ValidationHelper.GetString(txtPwd.Value, String.Empty);
            }

            FormEngineUserControl txtConfPassword = formUser.FieldControls["ReenterPassword"];
            if (txtConfPassword != null)
            {
                confPassword = ValidationHelper.GetString(txtConfPassword.Value, String.Empty);
            }

            if (string.IsNullOrEmpty(pwd) || string.IsNullOrEmpty(confPassword))
            {
                lblError.Visible = true;
                lblError.Text    = "please enter password with confirmation";
                return;
            }

            if (pwd != confPassword)
            {
                lblError.Visible = true;
                lblError.Text    = "Password doesn't match";
                return;
            }


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

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

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

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

                // Check whether email is unique if it is required
                if (!UserInfoProvider.IsEmailUnique(emailValue, siteList, 0))
                {
                    lblError.Visible = true;
                    lblError.Text    = GetString("UserInfo.EmailAlreadyExist");
                    return;
                }

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

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

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

                ui.Enabled         = EnableUserAfterRegistration;
                ui.UserURLReferrer = MembershipContext.AuthenticatedUser.URLReferrer;
                ui.UserCampaign    = AnalyticsHelper.Campaign;

                ui.SetPrivilegeLevel(UserPrivilegeLevelEnum.None);

                // Fill optionally full user name
                if (String.IsNullOrEmpty(ui.FullName))
                {
                    ui.FullName = UserInfoProvider.GetFullName(ui.FirstName, ui.MiddleName, ui.LastName);
                }

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

                ui.UserSettings.UserRegistrationInfo.IPAddress = RequestContext.UserHostAddress;
                ui.UserSettings.UserRegistrationInfo.Agent     = HttpContext.Current.Request.UserAgent;
                ui.UserSettings.UserLogActivities        = true;
                ui.UserSettings.UserShowIntroductionTile = true;

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

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

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

                var customerToken = PersonifyRegistered(emailValue, password, firstName, lastName);
                if (string.IsNullOrEmpty(customerToken))
                {
                    UserInfoProvider.DeleteUser(ui);
                    return;
                }
                else
                {
                    var    roles      = GetImsroles(customerToken);
                    string groupslist = "";
                    if (roles.Length > 0)
                    {
                        foreach (string s in roles)
                        {
                            if (s.Length > 0)
                            {
                                groupslist += s + ",";
                            }
                        }
                    }

                    //we need this mispelling.
                    groupslist += "peronifyUser" + ",";

                    new LoginUsertokentico().AddUserToRole(ui, groupslist, true, false);
                }


                // Prepare macro data source for email resolver
                UserInfo userForMail = ui.Clone();
                userForMail.SetValue("UserPassword", string.Empty);

                object[] data = new object[1];
                data[0] = userForMail;

                // Prepare resolver for notification and welcome emails
                MacroResolver resolver = MacroContext.CurrentResolver;
                resolver.SetAnonymousSourceData(data);

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

                bool error = false;
                EmailTemplateInfo template = null;

                // Prepare macro replacements
                string[,] replacements = new string[6, 2];
                replacements[0, 0]     = "confirmaddress";
                replacements[0, 1]     = AuthenticationHelper.GetRegistrationApprovalUrl(ApprovalPage, ui.UserGUID, currentSiteName, NotifyAdministrator);
                replacements[1, 0]     = "username";
                replacements[1, 1]     = userName;
                replacements[2, 0]     = "password";
                replacements[2, 1]     = password;
                replacements[3, 0]     = "Email";
                replacements[3, 1]     = emailValue;
                replacements[4, 0]     = "FirstName";
                replacements[4, 1]     = firstName;
                replacements[5, 0]     = "LastName";
                replacements[5, 1]     = lastName;

                // Set resolver
                resolver.SetNamedSourceData(replacements);

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

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

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

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

                    try
                    {
                        EmailHelper.ResolveMetaFileImages(emailMessage, template.TemplateID, EmailTemplateInfo.OBJECT_TYPE, ObjectAttachmentsCategories.TEMPLATE);
                        // Send the e-mail immediately
                        EmailSender.SendEmail(currentSiteName, emailMessage, true);
                    }
                    catch (Exception ex)
                    {
                        EventLogProvider.LogException("E", "RegistrationForm - SendEmail", ex);
                        error = true;
                    }
                }

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

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

                #endregion


                #region "Administrator notification email"

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

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

                    if (mEmailTemplate == null)
                    {
                        EventLogProvider.LogEvent(EventType.ERROR, "RegistrationForm", "GetEmailTemplate", eventUrl: RequestContext.RawURL);
                    }
                    else
                    {
                        // E-mail template ok
                        replacements       = new string[4, 2];
                        replacements[0, 0] = "firstname";
                        replacements[0, 1] = ui.FirstName;
                        replacements[1, 0] = "lastname";
                        replacements[1, 1] = ui.LastName;
                        replacements[2, 0] = "email";
                        replacements[2, 1] = ui.Email;
                        replacements[3, 0] = "username";
                        replacements[3, 1] = userName;

                        // Set resolver
                        resolver.SetNamedSourceData(replacements);
                        // Enable macro encoding for body
                        resolver.Settings.EncodeResolvedValues = true;

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

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

                        try
                        {
                            // Attach template meta-files to e-mail
                            EmailHelper.ResolveMetaFileImages(message, mEmailTemplate.TemplateID, EmailTemplateInfo.OBJECT_TYPE, ObjectAttachmentsCategories.TEMPLATE);
                            EmailSender.SendEmail(currentSiteName, message);
                        }
                        catch
                        {
                            EventLogProvider.LogEvent(EventType.ERROR, "Membership", "RegistrationEmail");
                        }
                    }
                }

                #endregion


                #region "Web analytics"

                // Track successful registration conversion
                if (TrackConversionName != String.Empty)
                {
                    if (AnalyticsHelper.AnalyticsEnabled(currentSiteName) && AnalyticsHelper.TrackConversionsEnabled(currentSiteName) && !AnalyticsHelper.IsIPExcluded(currentSiteName, RequestContext.UserHostAddress))
                    {
                        HitLogProvider.LogConversions(currentSiteName, LocalizationContext.PreferredCultureCode, TrackConversionName, 0, ConversionValue);
                    }
                }

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

                #endregion


                #region "On-line marketing - activity"

                // Log registered user if confirmation is not required
                if (!requiresConfirmation)
                {
                    Activity activity = new ActivityRegistration(ui, DocumentContext.CurrentDocument, AnalyticsContext.ActivityEnvironmentVariables);
                    if (activity.Data != null)
                    {
                        activity.Data.ContactID = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui);
                        activity.Log();
                    }

                    // Log login activity
                    if (ui.Enabled)
                    {
                        // Log activity
                        int      contactID     = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui);
                        Activity activityLogin = new ActivityUserLogin(contactID, ui, DocumentContext.CurrentDocument, AnalyticsContext.ActivityEnvironmentVariables);
                        activityLogin.Log();
                    }
                }

                #endregion

                #region "Site and roles addition and authentication"

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

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

                            // Add user to desired roles
                            if (RoleInfoProvider.RoleExists(roleName, sn))
                            {
                                UserInfoProvider.AddUserToRole(ui.UserName, roleName, sn);
                            }
                        }
                    }
                }
                if (ui.Enabled)
                {
                    if (this.AutoLoginAfterRegistration)
                    {
                        Session["UserName"]   = userName;
                        Session["Password"]   = password;
                        Session["RememberMe"] = true;
                        Session["RetryCount"] = null;

                        if (this.Request.QueryString["ReturnURL"] != null)
                        {
                            var returnURL = this.Request.QueryString["ReturnURL"];

                            Session["ReturnURL"] = returnURL;
                        }
                        else if (!String.IsNullOrEmpty(this.RedirectToURL))
                        {
                            var returnURL = this.Request.QueryString["ReturnURL"];

                            Session["ReturnURL"] = returnURL;
                        }
                        Response.Redirect("~/sso/ssohandler.aspx", true);
                    }
                    else if (!String.IsNullOrEmpty(this.LoginURL))
                    {
                        Response.Redirect(string.Format(this.LoginURL, userName), true);
                    }
                    else if (!String.IsNullOrEmpty(this.RedirectToURL))
                    {
                        Response.Redirect(this.RedirectToURL, true);
                    }
                }
                #endregion

                lblError.Visible = false;
            }
        }
    }
    /// <summary>
    /// Sends new registration notification e-mail to administrator.
    /// </summary>
    private void SendRegistrationNotification(UserInfo ui)
    {
        SiteInfo currentSite = SiteContext.CurrentSite;

        // Notify administrator
        if ((ui != null) && (currentSite != null) && (ShoppingCartControl.SendNewRegistrationNotificationToAddress != ""))
        {
            EmailTemplateInfo mEmailTemplate = null;
            if (!ui.UserEnabled)
            {
                mEmailTemplate = EmailTemplateProvider.GetEmailTemplate("Registration.Approve", currentSite.SiteName);
            }
            else
            {
                mEmailTemplate = EmailTemplateProvider.GetEmailTemplate("Registration.New", currentSite.SiteName);
            }

            if (mEmailTemplate == null)
            {
                // Email template not exist
                EventLogProvider.LogEvent(EventType.ERROR, "RegistrationForm", "GetEmailTemplate", eventUrl: RequestContext.RawURL);
            }
            else
            {
                // Initialize email message
                EmailMessage message = new EmailMessage();
                message.EmailFormat = EmailFormatEnum.Default;

                message.From    = EmailHelper.GetSender(mEmailTemplate, ECommerceSettings.SendEmailsFrom(currentSite.SiteName));
                message.Subject = GetString("RegistrationForm.EmailSubject");

                message.Recipients = ShoppingCartControl.SendNewRegistrationNotificationToAddress;
                message.Body       = mEmailTemplate.TemplateText;

                // Init macro resolving
                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;

                MacroResolver resolver = MacroContext.CurrentResolver;
                resolver.SetNamedSourceData(replacements);

                try
                {
                    // Add template metafiles to e-mail
                    EmailHelper.ResolveMetaFileImages(message, mEmailTemplate.TemplateID, EmailTemplateInfo.OBJECT_TYPE, ObjectAttachmentsCategories.TEMPLATE);
                    // Send e-mail
                    EmailSender.SendEmailWithTemplateText(currentSite.SiteName, message, mEmailTemplate, resolver, false);
                }
                catch
                {
                    // Email sending failed
                    EventLogProvider.LogEvent(EventType.ERROR, "Membership", "RegistrationEmail");
                }
            }
        }
    }
Example #17
0
    /// <summary>
    /// Unigrid external data bound handler.
    /// </summary>
    protected object uniGrid_OnExternalDataBound(object sender, string sourceName, object parameter)
    {
        switch (sourceName.ToLowerInvariant())
        {
        case "yesno":
            return(UniGridFunctions.ColoredSpanYesNo(parameter));

        case "select":
        {
            var ti = iObjectType.TypeInfo;

            DataRowView drv = (DataRowView)parameter;

            // Get item ID
            string itemID = drv[returnColumnName].ToString();

            // Add global object name prefix if required
            if (AddGlobalObjectNamePrefix && HasSiteIdColumn(ti) && (DataHelper.GetIntValue(drv.Row, ti.SiteIDColumn) == 0))
            {
                itemID = "." + itemID;
            }

            // Add checkbox for multiple selection
            switch (selectionMode)
            {
            case SelectionModeEnum.Multiple:
            case SelectionModeEnum.MultipleTextBox:
            case SelectionModeEnum.MultipleButton:
            {
                var itemWithSeparators = string.Format("{0}{1}{0}", valuesSeparator, itemID);

                string checkBox = string.Format("<span class=\"checkbox\"><input id=\"chk{0}\" type=\"checkbox\" onclick=\"ProcessItem(this,false); UpdateCheckboxAllElement();\" class=\"chckbox\" ", itemID);
                if (hidItem.Value.IndexOf(itemWithSeparators, StringComparison.OrdinalIgnoreCase) >= 0)
                {
                    checkBox += "checked=\"checked\" ";
                }
                else
                {
                    allRowsChecked = false;
                }

                if (disabledItems.Contains(itemWithSeparators))
                {
                    checkBox += "disabled=\"disabled\" ";
                }

                checkBox += string.Format("/><label for=\"chk{0}\">&nbsp;</label></span>", itemID);

                return(checkBox);
            }
            }
        }
        break;

        case "itemname":
        {
            DataRowView drv = (DataRowView)parameter;

            // Get item ID
            string itemID = drv[returnColumnName].ToString();

            // Get item name
            string itemName;

            // Special formatted user name
            if (displayNameFormat == UniSelector.USER_DISPLAY_FORMAT)
            {
                string userName = DataHelper.GetStringValue(drv.Row, "UserName");
                string fullName = DataHelper.GetStringValue(drv.Row, "FullName");

                itemName = Functions.GetFormattedUserName(userName, fullName, IsLiveSite);
            }
            else if (displayNameFormat == null)
            {
                itemName = drv[iObjectType.DisplayNameColumn].ToString();
            }
            else
            {
                MacroResolver resolver = MacroResolver.GetInstance();
                foreach (DataColumn item in drv.Row.Table.Columns)
                {
                    resolver.SetNamedSourceData(item.ColumnName, drv.Row[item.ColumnName]);
                }
                itemName = resolver.ResolveMacros(displayNameFormat);
            }

            if (RemoveMultipleCommas)
            {
                itemName = TextHelper.RemoveMultipleCommas(itemName);
            }

            // Add the prefixes
            itemName = ItemPrefix + itemName;
            itemID   = ItemPrefix + itemID;

            var ti = iObjectType.TypeInfo;

            // Add global object name prefix if required
            if (AddGlobalObjectNamePrefix && HasSiteIdColumn(ti) && (DataHelper.GetIntValue(drv.Row, ti.SiteIDColumn) == 0))
            {
                itemID = "." + itemID;
            }

            if (String.IsNullOrEmpty(itemName))
            {
                itemName = emptyReplacement;
            }

            if (AddGlobalObjectSuffix && HasSiteIdColumn(ti))
            {
                itemName += (DataHelper.GetIntValue(drv.Row, ti.SiteIDColumn) > 0 ? string.Empty : " " + GlobalObjectSuffix);
            }

            // Link action
            string onclick  = null;
            bool   disabled = disabledItems.Contains(";" + itemID + ";");
            if (!disabled)
            {
                string safeItemID = GetSafe(itemID);
                string itemHash   = ValidationHelper.GetHashString(itemID, new HashSettings(ClientID));
                switch (selectionMode)
                {
                case SelectionModeEnum.Multiple:
                case SelectionModeEnum.MultipleTextBox:
                case SelectionModeEnum.MultipleButton:
                    onclick = string.Format("ProcessItem(document.getElementById('chk{0}'),true); UpdateCheckboxAllElement(); return false;", ScriptHelper.GetString(itemID).Trim('\''));
                    break;

                case SelectionModeEnum.SingleButton:
                    onclick = string.Format("SelectItems({0},'{1}'); return false;", safeItemID, itemHash);
                    break;

                case SelectionModeEnum.SingleTextBox:
                    if (allowEditTextBox)
                    {
                        if (!mHasDependingFields)
                        {
                            onclick = string.Format("SelectItems({0},{0},{1},{2},{3},'{4}'); return false;", safeItemID, ScriptHelper.GetString(hdnClientId), ScriptHelper.GetString(txtClientId), ScriptHelper.GetString(hashId), itemHash);
                        }
                        else
                        {
                            onclick = string.Format("SelectItemsReload({0},{0},{1},{2},{3},{4},'{5}'); return false;", safeItemID, ScriptHelper.GetString(hdnClientId), ScriptHelper.GetString(txtClientId), ScriptHelper.GetString(hdnDrpId), ScriptHelper.GetString(hashId), itemHash);
                        }
                    }
                    else
                    {
                        if (!mHasDependingFields)
                        {
                            onclick = string.Format("SelectItems({0},{1},{2},{3},{4},'{5}'); return false;", safeItemID, GetSafe(itemName), ScriptHelper.GetString(hdnClientId), ScriptHelper.GetString(txtClientId), ScriptHelper.GetString(hashId), itemHash);
                        }
                        else
                        {
                            onclick = string.Format("SelectItemsReload({0},{1},{2},{3},{4},{5},'{6}'); return false;", safeItemID, GetSafe(itemName), ScriptHelper.GetString(hdnClientId), ScriptHelper.GetString(txtClientId), ScriptHelper.GetString(hdnDrpId), ScriptHelper.GetString(hashId), itemHash);
                        }
                    }
                    break;

                default:
                    onclick = string.Format("SelectItemsReload({0},{1},{2},{3},{4},{5},'{6}'); return false;", safeItemID, GetSafe(itemName), ScriptHelper.GetString(hdnClientId), ScriptHelper.GetString(txtClientId), ScriptHelper.GetString(hdnDrpId), ScriptHelper.GetString(hashId), itemHash);
                    break;
                }

                onclick = "onclick=\"" + onclick + "\" ";
            }

            if (LocalizeItems)
            {
                itemName = ResHelper.LocalizeString(itemName);
            }

            // Custom Tooltip
            string tooltip = "";
            if (!string.IsNullOrWhiteSpace(toolTipFormat))
            {
                MacroResolver resolver = MacroResolver.GetInstance();
                foreach (DataColumn item in drv.Row.Table.Columns)
                {
                    resolver.SetNamedSourceData(item.ColumnName, drv.Row[item.ColumnName]);
                }
                tooltip = resolver.ResolveMacros(toolTipFormat);
            }
            if (!string.IsNullOrWhiteSpace(tooltip))
            {
                tooltip = "title=\"" + CMS.Helpers.HTMLHelper.EncodeForHtmlAttribute(tooltip) + "\" ";
            }

            return("<div " + (!disabled ? "class=\"SelectableItem\" " : null) + onclick + tooltip + ">" + HTMLHelper.HTMLEncode(TextHelper.LimitLength(itemName, 100)) + "</div>");
        }
        }

        return(null);
    }
Example #18
0
    /// <summary>
    /// Send notifications.
    /// </summary>
    private void SentNotification()
    {
        if (SendNotificationMessage || SendNotificationEmail)
        {
            // Get e-mail template
            EmailTemplateInfo template = null;
            // Get message subject
            string messageSubject = null;

            switch (action)
            {
            case FriendsActionEnum.Approve:
                template = EmailTemplateProvider.GetEmailTemplate("Friends.Approve",
                                                                  SiteContext.CurrentSiteName);
                messageSubject = ApprovedCaption;
                break;

            case FriendsActionEnum.Reject:
                template = EmailTemplateProvider.GetEmailTemplate("Friends.Reject",
                                                                  SiteContext.CurrentSiteName);
                messageSubject = RejectedCaption;
                break;
            }
            if (template == null)
            {
                return;
            }

            // Get user infos
            UserInfo recipient = UserInfoProvider.GetFullUserInfo(friendship.FriendUserID);
            UserInfo sender    = UserInfoProvider.GetFullUserInfo(friendship.FriendRequestedUserID);

            MacroResolver resolver = MacroContext.CurrentResolver;
            resolver.SetAnonymousSourceData(sender, recipient, friendship);
            resolver.SetNamedSourceData("Sender", sender);
            resolver.SetNamedSourceData("Recipient", recipient);
            resolver.SetNamedSourceData("Friendship", friendship);
            resolver.SetNamedSourceData("FORMATTEDSENDERNAME", Functions.GetFormattedUserName(sender.UserName), false);

            if (SendNotificationMessage)
            {
                // Set message info object
                MessageInfo mi = new MessageInfo();
                mi.MessageLastModified      = DateTime.Now;
                mi.MessageSent              = DateTime.Now;
                mi.MessageRecipientUserID   = recipient.UserID;
                mi.MessageRecipientNickName = TextHelper.LimitLength(Functions.GetFormattedUserName(recipient.UserName, recipient.FullName, recipient.UserNickName, true), 200);
                mi.MessageSenderUserID      = friendship.FriendRequestedUserID;
                mi.MessageSenderNickName    = TextHelper.LimitLength(Functions.GetFormattedUserName(sender.UserName, sender.FullName, sender.UserNickName, true), 200);
                mi.MessageSenderDeleted     = true;
                mi.MessageSubject           = TextHelper.LimitLength(resolver.ResolveMacros(template.TemplateSubject), 200);
                mi.MessageBody              = resolver.ResolveMacros(template.TemplatePlainText);
                MessageInfoProvider.SetMessageInfo(mi);
            }
            if (SendNotificationEmail && !String.IsNullOrEmpty(recipient.Email) &&
                !String.IsNullOrEmpty(sender.Email))
            {
                // Send e-mail
                EmailMessage message = new EmailMessage();
                message.EmailFormat = EmailFormatEnum.Default;
                message.Recipients  = Functions.GetFormattedUserName(recipient.UserName, true) + " <" + recipient.Email + ">";
                message.From        = Functions.GetFormattedUserName(sender.UserName, true) + " <" + sender.Email + ">";
                message.Subject     = messageSubject;

                EmailSender.SendEmailWithTemplateText(SiteContext.CurrentSiteName, message, template, resolver, false);
            }
        }
    }
    /// <summary>
    /// Saves the data.
    /// </summary>
    private bool Save(string newsletterName, ContactInfo contact)
    {
        bool toReturn = false;

        if ((contact == null) || string.IsNullOrEmpty(newsletterName))
        {
            return(false);
        }

        // Get newsletter info
        var newsletter = NewsletterInfoProvider.GetNewsletterInfo(newsletterName, SiteContext.CurrentSiteID);

        if (newsletter != null)
        {
            try
            {
                // Check if subscriber is not marketable
                if (!mSubscriptionService.IsMarketable(contact, newsletter))
                {
                    toReturn = true;

                    if (!AllowUserSubscribersIsAuthenticated || String.IsNullOrEmpty(CurrentUser.Email))
                    {
                        if (!SaveDataForm())
                        {
                            return(false);
                        }
                    }

                    mSubscriptionService.Subscribe(contact, newsletter, new SubscribeSettings()
                    {
                        SendConfirmationEmail = SendConfirmationEmail,
                        AllowOptIn            = true,
                        RemoveUnsubscriptionFromNewsletter         = true,
                        RemoveAlsoUnsubscriptionFromAllNewsletters = true,
                        SourceSubscriber = subscriber
                    });

                    if (!mChooseMode)
                    {
                        // Display message about successful subscription
                        lblInfo.Visible = true;
                        lblInfo.Text    = SubscriptionConfirmationMessage;
                    }

                    // Track successful subscription conversion
                    if (!string.IsNullOrEmpty(TrackConversionName))
                    {
                        string siteName = SiteContext.CurrentSiteName;

                        if (AnalyticsHelper.AnalyticsEnabled(siteName) && Service.Resolve <IAnalyticsConsentProvider>().HasConsentForLogging() && !AnalyticsHelper.IsIPExcluded(siteName, RequestContext.UserHostAddress))
                        {
                            // Log conversion
                            HitLogProvider.LogConversions(siteName, LocalizationContext.PreferredCultureCode, TrackConversionName, 0, ConversionValue);
                        }
                    }
                }
                else
                {
                    // Init web part resolver
                    object[] data = new object[3];
                    data[0] = newsletter;
                    data[1] = subscriber;

                    MacroResolver resolver = ContextResolver;
                    resolver.SetNamedSourceData("Newsletter", newsletter);
                    resolver.SetNamedSourceData("Subscriber", subscriber);
                    if (AllowUserSubscribersIsAuthenticated)
                    {
                        data[2] = CurrentUser;
                        resolver.SetNamedSourceData("User", CurrentUser);
                    }
                    resolver.SetAnonymousSourceData(data);

                    lblInfo.Visible = true;
                    string message = null;

                    if (string.IsNullOrEmpty(MessageForAlreadySubscribed))
                    {
                        if (!mChooseMode)
                        {
                            message = GetString("NewsletterSubscription.SubscriberIsAlreadySubscribed");
                        }
                        else
                        {
                            message = string.Format("{0} {1}.<br />", GetString("NewsletterSubscription.SubscriberIsAlreadySubscribedXY"), HTMLHelper.HTMLEncode(newsletter.NewsletterDisplayName));
                        }
                    }
                    else
                    {
                        message = MessageForAlreadySubscribed;
                    }

                    // Info message - subscriber is already in site
                    if (!mChooseMode)
                    {
                        lblInfo.Text = message;
                    }
                    else
                    {
                        lblInfo.Text += message;
                    }
                }
            }
            catch (Exception ex)
            {
                lblError.Visible = true;
                lblError.Text    = ex.Message;
            }
        }
        else
        {
            lblError.Visible = true;
            lblError.Text    = GetString("NewsletterSubscription.NewsletterDoesNotExist");
        }

        return(toReturn);
    }
    /// <summary>
    /// 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.GetStringValue(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;

                    string[,] replacements = new string[1, 2];
                    // Prepare macro replacements
                    replacements[0, 0] = "homepageurl";
                    replacements[0, 1] = URLHelper.GetAbsoluteUrl("~/");

                    MacroResolver resolver = MacroContext.CurrentResolver;
                    resolver.Settings.EncodeResolvedValues = true;
                    resolver.SetNamedSourceData(replacements);
                    email.Body = resolver.ResolveMacros(template.TemplateText);

                    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 (MembershipContext.AuthenticatedUser.IsPublic())
                {
                    // Get logon URL
                    string logonUrl = AuthenticationHelper.GetSecuredAreasLogonPage(SiteContext.CurrentSiteName);
                    logonUrl = DataHelper.GetNotEmpty(LoginURL, logonUrl);

                    // Create redirect URL
                    logonUrl = UrlResolver.ResolveUrl(logonUrl) + "?ReturnURL=" + HttpUtility.UrlEncode(RequestContext.CurrentURL);
                    URLHelper.Redirect(logonUrl);
                }
                else
                {
                    // Get invitation by GUID
                    Guid invitationGuid = QueryHelper.GetGuid("invitationguid", Guid.Empty);
                    if (invitationGuid != Guid.Empty)
                    {
                        InvitationInfo invitation = InvitationInfoProvider.GetInvitationInfo(invitationGuid);
                        if (invitation != null)
                        {
                            // Check if invitation is valid
                            if ((invitation.InvitationValidTo == DateTimeHelper.ZERO_TIME) ||
                                (invitation.InvitationValidTo >= DateTime.Now))
                            {
                                GroupInfo group = GroupInfoProvider.GetGroupInfo(invitation.InvitationGroupID);

                                if (group != null)
                                {
                                    // Check whether current user is the user who should be invited
                                    if ((invitation.InvitedUserID > 0) && (invitation.InvitedUserID != MembershipContext.AuthenticatedUser.UserID))
                                    {
                                        lblInfo.CssClass = "InvitationErrorLabel";
                                        lblInfo.Text     = InvitationIsNotValid;
                                        lblInfo.Visible  = true;
                                        return;
                                    }

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

                                    if (!GroupMemberInfoProvider.IsMemberOfGroup(invitation.InvitedUserID, invitation.InvitationGroupID))
                                    {
                                        // Create group member info object
                                        GroupMemberInfo groupMember = new GroupMemberInfo();
                                        groupMember.MemberInvitedByUserID = invitation.InvitedByUserID;
                                        groupMember.MemberUserID          = MembershipContext.AuthenticatedUser.UserID;
                                        groupMember.MemberGroupID         = invitation.InvitationGroupID;
                                        groupMember.MemberJoined          = DateTime.Now;

                                        // Set proper status depending on grouo settings
                                        switch (group.GroupApproveMembers)
                                        {
                                        // Only approved members can join
                                        case GroupApproveMembersEnum.ApprovedCanJoin:
                                            groupMember.MemberStatus = GroupMemberStatus.WaitingForApproval;
                                            lblInfo.Text             = MemberWaiting.Replace("##GROUPNAME##", HTMLHelper.HTMLEncode(group.GroupDisplayName));
                                            break;

                                        // Only invited members
                                        case GroupApproveMembersEnum.InvitedWithoutApproval:
                                        // Any site members can join
                                        case GroupApproveMembersEnum.AnyoneCanJoin:
                                            groupMember.MemberApprovedWhen = DateTime.Now;
                                            groupMember.MemberStatus       = GroupMemberStatus.Approved;
                                            lblInfo.Text = MemberJoined.Replace("##GROUPNAME##", HTMLHelper.HTMLEncode(group.GroupDisplayName));
                                            break;
                                        }
                                        // Store info object to database
                                        GroupMemberInfoProvider.SetGroupMemberInfo(groupMember);

                                        // Handle sending e-mails
                                        if (SendEmailToInviter || SendDefaultGroupEmails)
                                        {
                                            UserInfo sender    = UserInfoProvider.GetFullUserInfo(groupMember.MemberUserID);
                                            UserInfo recipient = UserInfoProvider.GetFullUserInfo(groupMember.MemberInvitedByUserID);

                                            if (SendEmailToInviter)
                                            {
                                                EmailTemplateInfo template = EmailTemplateProvider.GetEmailTemplate("Groups.MemberAcceptedInvitation", SiteContext.CurrentSiteName);

                                                // Resolve macros
                                                MacroResolver resolver = MacroContext.CurrentResolver;
                                                resolver.SetAnonymousSourceData(sender, recipient, group, groupMember);
                                                resolver.SetNamedSourceData("Sender", sender);
                                                resolver.SetNamedSourceData("Recipient", recipient);
                                                resolver.SetNamedSourceData("Group", group);
                                                resolver.SetNamedSourceData("GroupMember", groupMember);

                                                if (!String.IsNullOrEmpty(recipient.Email) && !String.IsNullOrEmpty(sender.Email))
                                                {
                                                    // Send e-mail
                                                    EmailMessage message = new EmailMessage();
                                                    message.EmailFormat = EmailFormatEnum.Default;
                                                    message.Recipients  = recipient.Email;
                                                    message.From        = SettingsKeyInfoProvider.GetValue(SiteContext.CurrentSiteName + ".CMSNoreplyEmailAddress");

                                                    EmailSender.SendEmailWithTemplateText(SiteContext.CurrentSiteName, message, template, resolver, false);
                                                }
                                            }

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

                                                // Send 'waiting for approval' notification
                                                if (group.GroupSendWaitingForApprovalNotification && (groupMember.MemberStatus == GroupMemberStatus.WaitingForApproval))
                                                {
                                                    GroupMemberInfoProvider.SendNotificationMail("Groups.MemberWaitingForApproval", SiteContext.CurrentSiteName, groupMember, true);
                                                    GroupMemberInfoProvider.SendNotificationMail("Groups.MemberJoinedWaitingForApproval", SiteContext.CurrentSiteName, groupMember, false);
                                                }
                                            }
                                        }

                                        // Delete all invitations to specified group for specified user (based on e-mail or userId)
                                        string whereCondition = "InvitationGroupID = " + invitation.InvitationGroupID + " AND (InvitedUserID=" + MembershipContext.AuthenticatedUser.UserID + " OR InvitationUserEmail = N'" + SqlHelper.GetSafeQueryString(MembershipContext.AuthenticatedUser.Email, false) + "')";
                                        InvitationInfoProvider.DeleteInvitations(whereCondition);
                                    }
                                    else
                                    {
                                        lblInfo.Text     = UserIsAlreadyMember.Replace("##GROUPNAME##", HTMLHelper.HTMLEncode(group.GroupDisplayName));
                                        lblInfo.CssClass = "InvitationErrorLabel";

                                        // Delete this invitation
                                        InvitationInfoProvider.DeleteInvitationInfo(invitation);
                                    }
                                }
                                else
                                {
                                    lblInfo.Text     = GroupNoLongerExists;
                                    lblInfo.CssClass = "InvitationErrorLabel";
                                    // Delete this invitation
                                    InvitationInfoProvider.DeleteInvitationInfo(invitation);
                                }
                            }
                            else
                            {
                                lblInfo.Text     = InvitationIsNotValid;
                                lblInfo.CssClass = "InvitationErrorLabel";
                                // Delete this invitation
                                InvitationInfoProvider.DeleteInvitationInfo(invitation);
                            }
                        }
                        else
                        {
                            lblInfo.Text     = InvitationNoLongerExists;
                            lblInfo.CssClass = "InvitationErrorLabel";
                        }
                        lblInfo.Visible = true;
                    }
                    else
                    {
                        // Hide control if invitation GUID isn't set
                        Visible = false;
                    }
                }
            }
        }
    }
    /// <summary>
    /// OK click handler (Proceed registration).
    /// </summary>
    protected void btnOK_Click(object sender, EventArgs e)
    {
        if (PortalContext.IsDesignMode(PortalContext.ViewMode) || (HideOnCurrentPage) || (!IsVisible))
        {
            // Do not process
        }
        else
        {
            String siteName = SiteContext.CurrentSiteName;


            #region "Banned IPs"

            // Ban IP addresses which are blocked for registration
            if (!BannedIPInfoProvider.IsAllowed(siteName, BanControlEnum.Registration))
            {
                lblError.Visible = true;
                lblError.Text    = GetString("banip.ipisbannedregistration");
                return;
            }

            #endregion


            #region "Check Email & password"

            string[] siteList = { siteName };

            // If AssignToSites field set
            if (!String.IsNullOrEmpty(AssignToSites))
            {
                siteList = AssignToSites.Split(';');
            }

            // Check whether user with same email does not exist
            UserInfo ui     = UserInfoProvider.GetUserInfo(txtEmail.Text);
            SiteInfo si     = SiteContext.CurrentSite;
            UserInfo siteui = UserInfoProvider.GetUserInfo(UserInfoProvider.EnsureSitePrefixUserName(txtEmail.Text, si));

            if ((ui != null) || (siteui != null))
            {
                lblError.Visible = true;
                lblError.Text    = GetString("Webparts_Membership_RegistrationForm.UserAlreadyExists").Replace("%%name%%", HTMLHelper.HTMLEncode(txtEmail.Text));
                return;
            }

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

            if ((PasswordMinLength > 0) && (passStrength.Text.Length < PasswordMinLength))
            {
                lblError.Visible = true;
                lblError.Text    = String.Format(GetString("Webparts_Membership_RegistrationForm.PasswordMinLength"), PasswordMinLength.ToString());
                return;
            }

            if (!passStrength.IsValid())
            {
                lblError.Visible = true;
                lblError.Text    = AuthenticationHelper.GetPolicyViolationMessage(SiteContext.CurrentSiteName);
                return;
            }

            if (!ValidationHelper.IsEmail(txtEmail.Text.ToLowerCSafe()))
            {
                lblError.Visible = true;
                lblError.Text    = GetString("Webparts_Membership_RegistrationForm.EmailIsNotValid");
                return;
            }

            #endregion


            #region "Captcha"

            // Check if captcha is required and verifiy captcha text
            if (DisplayCaptcha && !scCaptcha.IsValid())
            {
                // Display error message if catcha text is not valid
                lblError.Visible = true;
                lblError.Text    = GetString("Webparts_Membership_RegistrationForm.captchaError");
                return;
            }

            #endregion


            #region "User properties"

            ui = new UserInfo();
            ui.PreferredCultureCode = "";
            ui.Email          = txtEmail.Text.Trim();
            ui.FirstName      = txtFirstName.Text.Trim();
            ui.LastName       = txtLastName.Text.Trim();
            ui.FullName       = UserInfoProvider.GetFullName(ui.FirstName, String.Empty, ui.LastName);
            ui.MiddleName     = "";
            ui.UserMFRequired = chkUseMultiFactorAutentization.Checked;

            // User name as put by user (no site prefix included)
            String plainUserName = txtEmail.Text.Trim();
            ui.UserName = plainUserName;

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

            ui.Enabled         = EnableUserAfterRegistration;
            ui.UserURLReferrer = MembershipContext.AuthenticatedUser.URLReferrer;
            ui.UserCampaign    = AnalyticsHelper.Campaign;

            ui.SetPrivilegeLevel(UserPrivilegeLevelEnum.None);

            ui.UserSettings.UserRegistrationInfo.IPAddress = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
            ui.UserSettings.UserRegistrationInfo.Agent     = HttpContext.Current.Request.UserAgent;

            // Check whether confirmation is required
            bool requiresConfirmation = SettingsKeyInfoProvider.GetBoolValue(siteName + ".CMSRegistrationEmailConfirmation");
            bool requiresAdminApprove = false;

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

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

            #endregion


            #region "Reserved names"

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

            if (UserInfoProvider.NameIsReserved(siteName, plainUserName))
            {
                lblError.Visible = true;
                lblError.Text    = GetString("Webparts_Membership_RegistrationForm.UserNameReserved").Replace("%%name%%", HTMLHelper.HTMLEncode(ui.UserNickName));
                return;
            }

            #endregion


            #region "License limitations"

            string errorMessage = String.Empty;
            UserInfoProvider.CheckLicenseLimitation(ui, ref errorMessage);

            if (!String.IsNullOrEmpty(errorMessage))
            {
                lblError.Visible = true;
                lblError.Text    = errorMessage;
                return;
            }

            #endregion


            // Check whether email is unique if it is required
            if (!UserInfoProvider.IsEmailUnique(txtEmail.Text.Trim(), siteList, 0))
            {
                lblError.Visible = true;
                lblError.Text    = GetString("UserInfo.EmailAlreadyExist");
                return;
            }

            // Set password
            UserInfoProvider.SetPassword(ui, passStrength.Text);


            // Prepare macro data source for email resolver
            UserInfo userForMail = ui.Clone();
            userForMail.SetValue("UserPassword", string.Empty);

            object[] data = new object[1];
            data[0] = userForMail;

            // Prepare resolver for notification and welcome emails
            MacroResolver resolver = MacroContext.CurrentResolver;
            resolver.SetAnonymousSourceData(data);
            resolver.Settings.EncodeResolvedValues = true;

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

            bool error = false;
            EmailTemplateInfo template = null;

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

            if (template != null)
            {
                // Retrieve contact ID for confirmation e-mail
                int contactId = 0;
                if (ActivitySettingsHelper.ActivitiesEnabledAndModuleLoaded(siteName))
                {
                    // Check if loggin registration activity is enabled
                    if (ActivitySettingsHelper.UserRegistrationEnabled(siteName))
                    {
                        if (ActivitySettingsHelper.ActivitiesEnabledForThisUser(ui))
                        {
                            contactId = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui);
                        }
                    }
                }

                // Prepare macro replacements
                string[,] replacements = new string[6, 2];
                replacements[0, 0]     = "confirmaddress";
                replacements[0, 1]     = AuthenticationHelper.GetRegistrationApprovalUrl(ApprovalPage, ui.UserGUID, siteName, NotifyAdministrator, contactId);
                replacements[1, 0]     = "username";
                replacements[1, 1]     = plainUserName;
                replacements[2, 0]     = "password";
                replacements[2, 1]     = passStrength.Text;
                replacements[3, 0]     = "Email";
                replacements[3, 1]     = txtEmail.Text;
                replacements[4, 0]     = "FirstName";
                replacements[4, 1]     = txtFirstName.Text;
                replacements[5, 0]     = "LastName";
                replacements[5, 1]     = txtLastName.Text;

                // Set resolver
                resolver.SetNamedSourceData(replacements);

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

                email.From = EmailHelper.GetSender(template, SettingsKeyInfoProvider.GetStringValue(siteName + ".CMSNoreplyEmailAddress"));
                email.Body = resolver.ResolveMacros(template.TemplateText);

                resolver.Settings.EncodeResolvedValues = false;
                email.PlainTextBody = resolver.ResolveMacros(template.TemplatePlainText);
                email.Subject       = resolver.ResolveMacros(emailSubject);

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

                try
                {
                    EmailHelper.ResolveMetaFileImages(email, template.TemplateID, EmailTemplateInfo.OBJECT_TYPE, ObjectAttachmentsCategories.TEMPLATE);
                    // Send the e-mail immediately
                    EmailSender.SendEmail(siteName, email, true);
                }
                catch (Exception ex)
                {
                    EventLogProvider.LogException("E", "RegistrationForm - SendEmail", ex);
                    error = true;
                }
            }

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

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

            #endregion


            #region "Administrator notification email"

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

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

                if (mEmailTemplate == null)
                {
                    // Log missing e-mail template
                    EventLogProvider.LogEvent(EventType.ERROR, "RegistrationForm", "GetEmailTemplate", eventUrl: RequestContext.RawURL);
                }
                else
                {
                    string[,] replacements = new string[4, 2];
                    replacements[0, 0]     = "firstname";
                    replacements[0, 1]     = ui.FirstName;
                    replacements[1, 0]     = "lastname";
                    replacements[1, 1]     = ui.LastName;
                    replacements[2, 0]     = "email";
                    replacements[2, 1]     = ui.Email;
                    replacements[3, 0]     = "username";
                    replacements[3, 1]     = plainUserName;

                    // Set resolver
                    resolver.SetNamedSourceData(replacements);

                    EmailMessage message = new EmailMessage();

                    message.EmailFormat = EmailFormatEnum.Default;
                    message.From        = EmailHelper.GetSender(mEmailTemplate, FromAddress);
                    message.Recipients  = ToAddress;
                    message.Body        = resolver.ResolveMacros(mEmailTemplate.TemplateText);

                    resolver.Settings.EncodeResolvedValues = false;
                    message.PlainTextBody = resolver.ResolveMacros(mEmailTemplate.TemplatePlainText);
                    message.Subject       = resolver.ResolveMacros(EmailHelper.GetSubject(mEmailTemplate, GetString("RegistrationForm.EmailSubject")));

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

                    try
                    {
                        // Attach template meta-files to e-mail
                        EmailHelper.ResolveMetaFileImages(message, mEmailTemplate.TemplateID, EmailTemplateInfo.OBJECT_TYPE, ObjectAttachmentsCategories.TEMPLATE);
                        EmailSender.SendEmail(siteName, message);
                    }
                    catch
                    {
                        EventLogProvider.LogEvent(EventType.ERROR, "Membership", "RegistrationEmail");
                    }
                }
            }

            #endregion


            #region "Web analytics"

            // Track successful registration conversion
            if (TrackConversionName != String.Empty)
            {
                if (AnalyticsHelper.AnalyticsEnabled(siteName) && AnalyticsHelper.TrackConversionsEnabled(siteName) && !AnalyticsHelper.IsIPExcluded(siteName, RequestContext.UserHostAddress))
                {
                    // Log conversion
                    HitLogProvider.LogConversions(siteName, LocalizationContext.PreferredCultureCode, TrackConversionName, 0, ConversionValue);
                }
            }

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

            #endregion


            #region "On-line marketing - activity"

            // Log registered user if confirmation is not required
            if (!requiresConfirmation)
            {
                Activity activity = new ActivityRegistration(ui, DocumentContext.CurrentDocument, AnalyticsContext.ActivityEnvironmentVariables);
                if (activity.Data != null)
                {
                    activity.Data.ContactID = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui);
                    activity.Log();
                }
                // Log login activity
                if (ui.Enabled)
                {
                    // Log activity
                    int      contactID     = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui);
                    Activity activityLogin = new ActivityUserLogin(contactID, ui, DocumentContext.CurrentDocument, AnalyticsContext.ActivityEnvironmentVariables);
                    activityLogin.Log();
                }
            }

            #endregion


            #region "Roles & authentication"

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

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

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

            if (DisplayMessage.Trim() != String.Empty)
            {
                pnlForm.Visible = false;
                lblText.Visible = true;
                lblText.Text    = DisplayMessage;
            }
            else
            {
                if (ui.Enabled)
                {
                    AuthenticationHelper.AuthenticateUser(ui.UserName, true);
                }

                if (RedirectToURL != String.Empty)
                {
                    URLHelper.Redirect(RedirectToURL);
                }

                else if (QueryHelper.GetString("ReturnURL", "") != String.Empty)
                {
                    string url = QueryHelper.GetString("ReturnURL", "");

                    // Do url decode
                    url = Server.UrlDecode(url);

                    // Check that url is relative path or hash is ok
                    if (url.StartsWithCSafe("~") || url.StartsWithCSafe("/") || QueryHelper.ValidateHash("hash"))
                    {
                        URLHelper.Redirect(url);
                    }
                    // Absolute path with wrong hash
                    else
                    {
                        URLHelper.Redirect(ResolveUrl("~/CMSMessages/Error.aspx?title=" + ResHelper.GetString("general.badhashtitle") + "&text=" + ResHelper.GetString("general.badhashtext")));
                    }
                }
            }

            #endregion


            lblError.Visible = false;
        }
    }
Example #23
0
 /// <summary>
 /// Registers NamedDataSource to a given resolver under the specified name.
 /// </summary>
 /// <param name="resolver">Resolver object</param>
 /// <param name="name">Name of the macro - object will be accessible by this name in the resolver</param>
 /// <param name="classObject">Class object to register</param>
 private static void RegisterObject(this MacroResolver resolver, string name, object classObject)
 {
     resolver.SetNamedSourceData(name, classObject);
 }
Example #24
0
    /// <summary>
    /// Send notifications.
    /// </summary>
    private void SentNotification()
    {
        if (SendNotificationMessage || SendNotificationEmail)
        {
            // Get e-mail template
            EmailTemplateInfo template = null;
            // Get message subject
            string messageSubject = null;

            switch (action)
            {
            case FriendsActionEnum.Approve:
                template = EmailTemplateProvider.GetEmailTemplate("Friends.Approve",
                                                                  CMSContext.CurrentSiteName);
                messageSubject = ApprovedCaption;
                break;

            case FriendsActionEnum.Reject:
                template = EmailTemplateProvider.GetEmailTemplate("Friends.Reject",
                                                                  CMSContext.CurrentSiteName);
                messageSubject = RejectedCaption;
                break;
            }
            if (template == null)
            {
                return;
            }

            // Get user infos
            UserInfo recipient = UserInfoProvider.GetFullUserInfo(friendship.FriendUserID);
            UserInfo sender    = UserInfoProvider.GetFullUserInfo(friendship.FriendRequestedUserID);

            MacroResolver resolver = CMSContext.CurrentResolver;
            resolver.SourceData = new object[] { sender, recipient, friendship };
            resolver.SetNamedSourceData("Sender", sender);
            resolver.SetNamedSourceData("Recipient", recipient);
            resolver.SetNamedSourceData("Friendship", friendship);

            string[,] replacements = new string[1, 2];
            replacements[0, 0]     = "FORMATTEDSENDERNAME";
            replacements[0, 1]     = Functions.GetFormattedUserName(sender.UserName);

            resolver.SourceParameters = replacements;

            if (SendNotificationMessage)
            {
                // Set message info object
                MessageInfo mi = new MessageInfo();
                mi.MessageLastModified      = DateTime.Now;
                mi.MessageSent              = DateTime.Now;
                mi.MessageRecipientUserID   = recipient.UserID;
                mi.MessageRecipientNickName = TextHelper.LimitLength(Functions.GetFormattedUserName(recipient.UserName, recipient.FullName, recipient.UserNickName, true), 200);
                mi.MessageSenderUserID      = friendship.FriendRequestedUserID;
                mi.MessageSenderNickName    = TextHelper.LimitLength(Functions.GetFormattedUserName(sender.UserName, sender.FullName, sender.UserNickName, true), 200);
                mi.MessageSenderDeleted     = true;
                mi.MessageSubject           = TextHelper.LimitLength(resolver.ResolveMacros(template.TemplateSubject), 200);
                mi.MessageBody              = resolver.ResolveMacros(template.TemplatePlainText);
                MessageInfoProvider.SetMessageInfo(mi);
            }
            if (SendNotificationEmail && !String.IsNullOrEmpty(recipient.Email) &&
                !String.IsNullOrEmpty(sender.Email))
            {
                // Send e-mail
                EmailMessage message = new EmailMessage();
                message.Recipients    = Functions.GetFormattedUserName(recipient.UserName, true) + " <" + recipient.Email + ">";
                message.From          = EmailHelper.GetSender(template, Functions.GetFormattedUserName(sender.UserName, true) + " <" + sender.Email + ">");
                message.Subject       = EmailHelper.GetSubject(template, messageSubject);
                message.CcRecipients  = template.TemplateCc;
                message.BccRecipients = template.TemplateBcc;
                message.EmailFormat   = EmailFormatEnum.Default;

                // Replace replacements, resolve macros
                resolver.EncodeResolvedValues = true;
                resolver.EncodeSpecialMacros  = true;
                message.Body = resolver.ResolveMacros(template.TemplateText);

                // Do not encode plain text body and subject
                resolver.EncodeResolvedValues = false;
                resolver.EncodeSpecialMacros  = false;
                message.Subject       = resolver.ResolveMacros(message.Subject);
                message.PlainTextBody = resolver.ResolveMacros(template.TemplatePlainText);

                MetaFileInfoProvider.ResolveMetaFileImages(message, template.TemplateID, EmailObjectType.EMAILTEMPLATE, MetaFileInfoProvider.OBJECT_CATEGORY_TEMPLATE);
                EmailSender.SendEmail(CMSContext.CurrentSiteName, message);
            }
        }
    }
    protected object grid_OnExternalDataBound(object sender, string sourceName, object parameter)
    {
        DataRowView drv = null;

        if (parameter is DataRowView)
        {
            drv = (DataRowView)parameter;
        }
        else if (parameter is GridViewRow)
        {
            drv = (DataRowView)((GridViewRow)parameter).DataItem;
        }

        var objectSettingsId = ValidationHelper.GetInteger(drv["ObjectSettingsID"], 0);

        if ((tmpObjectSettings == null) || (tmpObjectSettings.ObjectSettingsID != objectSettingsId))
        {
            tmpObjectSettings = ObjectSettingsInfoProvider.GetObjectSettingsInfo(objectSettingsId);
            if (tmpObjectSettings != null)
            {
                tmpInfo = BaseAbstractInfoProvider.GetInfoById(tmpObjectSettings.ObjectSettingsObjectType, tmpObjectSettings.ObjectSettingsObjectID);
            }
        }

        if ((tmpInfo != null) && (tmpObjectSettings != null))
        {
            contextResolver.SetNamedSourceData("EditedObject", tmpInfo);

            switch (sourceName.ToLowerCSafe())
            {
            case "edit":
                var editButton = (CMSGridActionButton)sender;

                var url = tmpInfo.Generalized.GetEditingPageURL();

                if (!string.IsNullOrEmpty(url))
                {
                    url = contextResolver.ResolveMacros(url);

                    // Resolve dialog relative url
                    if (url.StartsWith("~/"))
                    {
                        url = AuthenticationHelper.ResolveDialogUrl(url);
                    }

                    string queryString = URLHelper.GetQuery(url);
                    if (queryString.IndexOfCSafe("&hash=", true) < 0)
                    {
                        url = URLHelper.AddParameterToUrl(url, "hash", QueryHelper.GetHash(queryString));
                    }

                    editButton.OnClientClick = string.Format("modalDialog('{0}', 'objectEdit', '85%', '85%'); return false", url);
                }
                else
                {
                    editButton.Enabled = false;
                }
                break;

            case "checkin":
                var checkinButton = (CMSGridActionButton)sender;

                if (tmpInfo.TypeInfo.SupportsLocking)
                {
                    checkinButton.OnClientClick = GetConfirmScript(GetString("ObjectEditMenu.CheckInConfirmation"), tmpObjectSettings.ObjectSettingsObjectType, tmpObjectSettings.ObjectSettingsObjectID, btnCheckIn);
                }
                else
                {
                    checkinButton.Enabled = false;
                }
                break;

            case "undocheckout":
                var undoCheckoutButton = (CMSGridActionButton)sender;

                if (tmpInfo.TypeInfo.SupportsLocking)
                {
                    undoCheckoutButton.OnClientClick = GetConfirmScript(CMSObjectManager.GetUndoCheckOutConfirmation(tmpInfo, null), tmpObjectSettings.ObjectSettingsObjectType, tmpObjectSettings.ObjectSettingsObjectID, btnUndoCheckOut);
                }
                else
                {
                    undoCheckoutButton.Enabled = false;
                }
                break;
            }
        }

        return(parameter);
    }
Example #26
0
    /// <summary>
    /// Unigrid external data bound handler.
    /// </summary>
    protected object uniGrid_OnExternalDataBound(object sender, string sourceName, object parameter)
    {
        switch (sourceName.ToLowerCSafe())
        {
        case "yesno":
            return(UniGridFunctions.ColoredSpanYesNo(parameter));

        case "select":
        {
            DataRowView drv = (parameter as DataRowView);

            // Get item ID
            string itemID  = drv[returnColumnName].ToString();
            string hashKey = itemID;

            // Add global object name prefix if required
            if (AddGlobalObjectNamePrefix && !String.IsNullOrEmpty(iObjectType.SiteIDColumn) && (ValidationHelper.GetInteger(DataHelper.GetDataRowValue(drv.Row, iObjectType.SiteIDColumn), 0) == 0))
            {
                itemID = "." + itemID;
            }

            // Store hash codes for grid items
            if (!hashItems.ContainsKey(hashKey))
            {
                hashItems.Add(hashKey, ValidationHelper.GetHashString(itemID));
            }

            // Add checkbox for multiple selection
            switch (selectionMode)
            {
            case SelectionModeEnum.Multiple:
            case SelectionModeEnum.MultipleTextBox:
            case SelectionModeEnum.MultipleButton:
            {
                string checkBox = string.Format("<span class=\"checkbox\"><input id=\"chk{0}\" type=\"checkbox\" onclick=\"ProcessItem(this,'{1}',false,true);\" class=\"chckbox\" ", itemID, hashItems[hashKey]);
                if (hidItem.Value.IndexOfCSafe(valuesSeparator + itemID + valuesSeparator, true) >= 0)
                {
                    checkBox += "checked=\"checked\" ";
                }
                if (disabledItems.Contains(string.Format("{0}{1}{0}", valuesSeparator, itemID)))
                {
                    checkBox += "disabled=\"disabled\" ";
                }

                checkBox += string.Format("/><label for=\"chk{0}\">&nbsp;</label></span>", itemID);

                return(checkBox);
            }
            }
        }
        break;

        case "itemname":
        {
            DataRowView drv = (parameter as DataRowView);

            // Get item ID
            string itemID  = drv[returnColumnName].ToString();
            string hashKey = itemID;

            // Get item name
            string itemName;

            // Special formatted user name
            if (displayNameFormat == UniSelector.USER_DISPLAY_FORMAT)
            {
                string userName = ValidationHelper.GetString(DataHelper.GetDataRowValue(drv.Row, "UserName"), String.Empty);
                string fullName = ValidationHelper.GetString(DataHelper.GetDataRowValue(drv.Row, "FullName"), String.Empty);

                itemName = Functions.GetFormattedUserName(userName, fullName, IsLiveSite);
            }
            else if (displayNameFormat == null)
            {
                itemName = drv[iObjectType.DisplayNameColumn].ToString();
            }
            else
            {
                MacroResolver resolver = MacroResolver.GetInstance();
                foreach (DataColumn item in drv.Row.Table.Columns)
                {
                    resolver.SetNamedSourceData(item.ColumnName, drv.Row[item.ColumnName]);
                }
                itemName = resolver.ResolveMacros(displayNameFormat);
            }

            if (RemoveMultipleCommas)
            {
                itemName = TextHelper.RemoveMultipleCommas(itemName);
            }

            // Add the prefixes
            itemName = ItemPrefix + itemName;
            itemID   = ItemPrefix + itemID;

            // Add global object name prefix if required
            if (AddGlobalObjectNamePrefix && !String.IsNullOrEmpty(iObjectType.SiteIDColumn) && (ValidationHelper.GetInteger(DataHelper.GetDataRowValue(drv.Row, iObjectType.SiteIDColumn), 0) == 0))
            {
                itemID = "." + itemID;
            }

            if (String.IsNullOrEmpty(itemName))
            {
                itemName = emptyReplacement;
            }

            if (AddGlobalObjectSuffix)
            {
                if ((iObjectType != null) && !string.IsNullOrEmpty(iObjectType.SiteIDColumn))
                {
                    itemName += (ValidationHelper.GetInteger(DataHelper.GetDataRowValue(drv.Row, iObjectType.SiteIDColumn), 0) > 0 ? string.Empty : " " + GlobalObjectSuffix);
                }
            }

            // Link action
            string onclick  = null;
            bool   disabled = disabledItems.Contains(";" + itemID + ";");
            if (!disabled)
            {
                string safeItemID = GetSafe(itemID);
                string itemHash   = ValidationHelper.GetHashString(itemID);
                switch (selectionMode)
                {
                case SelectionModeEnum.Multiple:
                case SelectionModeEnum.MultipleTextBox:
                case SelectionModeEnum.MultipleButton:
                    onclick = string.Format("ProcessItem(document.getElementById('chk{0}'),'{1}',true,true); return false;", ScriptHelper.GetString(itemID).Trim('\''), hashItems[hashKey]);
                    break;

                case SelectionModeEnum.SingleButton:
                    onclick = string.Format("SelectItems({0},'{1}'); return false;", safeItemID, itemHash);
                    break;

                case SelectionModeEnum.SingleTextBox:
                    if (allowEditTextBox)
                    {
                        onclick = string.Format("SelectItems({0},{0},{1},{2},{3},'{4}'); return false;", safeItemID, ScriptHelper.GetString(hdnClientId), ScriptHelper.GetString(txtClientId), ScriptHelper.GetString(hashId), itemHash);
                    }
                    else
                    {
                        onclick = string.Format("SelectItems({0},{1},{2},{3},{4},'{5}'); return false;", safeItemID, GetSafe(itemName), ScriptHelper.GetString(hdnClientId), ScriptHelper.GetString(txtClientId), ScriptHelper.GetString(hashId), itemHash);
                    }
                    break;

                default:
                    onclick = string.Format("SelectItemsReload({0},{1},{2},{3},{4},{5},'{6}'); return false;", safeItemID, GetSafe(itemName), ScriptHelper.GetString(hdnClientId), ScriptHelper.GetString(txtClientId), ScriptHelper.GetString(hdnDrpId), ScriptHelper.GetString(hashId), itemHash);
                    break;
                }

                onclick = "onclick=\"" + onclick + "\" ";
            }

            if (LocalizeItems)
            {
                itemName = ResHelper.LocalizeString(itemName);
            }

            return("<div " + (!disabled ? "class=\"SelectableItem\" " : null) + onclick + ">" + HTMLHelper.HTMLEncode(TextHelper.LimitLength(itemName, 100)) + "</div>");
        }
        }

        return(null);
    }
Example #27
0
    /// <summary>
    /// Updates the current Group or creates new if no GroupID is present.
    /// </summary>
    public void SaveData()
    {
        // Check banned IP
        if (!BannedIPInfoProvider.IsAllowed(SiteContext.CurrentSiteName, BanControlEnum.AllNonComplete))
        {
            ShowError(GetString("General.BannedIP"));
            return;
        }

        // Validate form entries
        string errorMessage = ValidateForm();

        if (errorMessage == string.Empty)
        {
            try
            {
                codeName = GetSafeCodeName();
                codeName = GetUniqueCodeName(codeName);

                GroupInfo group = new GroupInfo();
                group.GroupDisplayName    = txtDisplayName.Text;
                group.GroupName           = codeName;
                group.GroupDescription    = txtDescription.Text;
                group.GroupAccess         = GetGroupAccess();
                group.GroupSiteID         = mSiteId;
                group.GroupApproveMembers = GetGroupApproveMembers();

                // Set columns GroupCreatedByUserID and GroupApprovedByUserID to current user
                var user = MembershipContext.AuthenticatedUser;

                if (user != null)
                {
                    group.GroupCreatedByUserID = user.UserID;

                    if ((!RequireApproval) || (CurrentUserIsAdmin()))
                    {
                        group.GroupApprovedByUserID = user.UserID;
                        group.GroupApproved         = true;
                    }
                }

                // Save Group in the database
                GroupInfoProvider.SetGroupInfo(group);

                // Create group admin role
                RoleInfo roleInfo = new RoleInfo();
                roleInfo.DisplayName = "Group admin";
                roleInfo.RoleName    = group.GroupName + "_groupadmin";
                roleInfo.RoleGroupID = group.GroupID;
                roleInfo.RoleIsGroupAdministrator = true;
                roleInfo.SiteID = mSiteId;
                // Save group admin role
                RoleInfoProvider.SetRoleInfo(roleInfo);

                if (user != null)
                {
                    // Set user as member of group
                    GroupMemberInfo gmi = new GroupMemberInfo();
                    gmi.MemberUserID           = user.UserID;
                    gmi.MemberGroupID          = group.GroupID;
                    gmi.MemberJoined           = DateTime.Now;
                    gmi.MemberStatus           = GroupMemberStatus.Approved;
                    gmi.MemberApprovedWhen     = DateTime.Now;
                    gmi.MemberApprovedByUserID = user.UserID;

                    // Save user as member of group
                    GroupMemberInfoProvider.SetGroupMemberInfo(gmi);

                    // Set user as member of admin group role
                    UserRoleInfo userRole = new UserRoleInfo();
                    userRole.UserID = user.UserID;
                    userRole.RoleID = roleInfo.RoleID;

                    // Save user as member of admin group role
                    UserRoleInfoProvider.SetUserRoleInfo(userRole);
                }

                // Clear user session a request
                MembershipContext.AuthenticatedUser.Generalized.Invalidate(false);
                MembershipContext.AuthenticatedUser = null;

                string culture = CultureHelper.EnglishCulture.ToString();
                if (DocumentContext.CurrentDocument != null)
                {
                    culture = DocumentContext.CurrentDocument.DocumentCulture;
                }

                // Copy document
                errorMessage = GroupInfoProvider.CopyGroupDocument(group, GroupTemplateSourceAliasPath, GroupTemplateTargetAliasPath, GroupProfileURLPath, culture, CombineWithDefaultCulture, MembershipContext.AuthenticatedUser, roleInfo);

                if (!String.IsNullOrEmpty(errorMessage))
                {
                    // Display error message
                    ShowError(errorMessage);
                    return;
                }

                // Create group forum
                if (CreateForum)
                {
                    CreateGroupForum(group);

                    // Create group forum search index
                    if (CreateSearchIndexes)
                    {
                        CreateGroupForumSearchIndex(group);
                    }
                }

                // Create group media library
                if (CreateMediaLibrary)
                {
                    CreateGroupMediaLibrary(group);
                }

                // Create search index for group documents
                if (CreateSearchIndexes)
                {
                    CreateGroupContentSearchIndex(group);
                }

                // Display information on success
                ShowConfirmation(GetString("group.group.createdinfo"));

                // If URL is set, redirect user to specified page
                if (!String.IsNullOrEmpty(RedirectToURL))
                {
                    URLHelper.Redirect(ResolveUrl(DocumentURLProvider.GetUrl(RedirectToURL)));
                }

                // After registration message
                if ((RequireApproval) && (!CurrentUserIsAdmin()))
                {
                    ShowConfirmation(SuccessfullRegistrationWaitingForApprovalText);

                    // Send approval email to admin
                    if (!String.IsNullOrEmpty(SendWaitingForApprovalEmailTo))
                    {
                        // Create the message
                        EmailTemplateInfo eti = EmailTemplateProvider.GetEmailTemplate("Groups.WaitingForApproval", SiteContext.CurrentSiteName);
                        if (eti != null)
                        {
                            EmailMessage message = new EmailMessage();
                            if (String.IsNullOrEmpty(eti.TemplateFrom))
                            {
                                message.From = SettingsKeyInfoProvider.GetStringValue(SiteContext.CurrentSiteName + ".CMSSendEmailNotificationsFrom");
                            }
                            else
                            {
                                message.From = eti.TemplateFrom;
                            }

                            MacroResolver resolver = MacroContext.CurrentResolver;
                            resolver.SetAnonymousSourceData(group);
                            resolver.SetNamedSourceData("Group", group);

                            message.Recipients = SendWaitingForApprovalEmailTo;
                            message.Subject    = resolver.ResolveMacros(eti.TemplateSubject);
                            message.Body       = resolver.ResolveMacros(eti.TemplateText);

                            resolver.Settings.EncodeResolvedValues = false;
                            message.PlainTextBody = resolver.ResolveMacros(eti.TemplatePlainText);

                            // Send the message using email engine
                            EmailSender.SendEmail(message);
                        }
                    }
                }
                else
                {
                    string groupPath = SettingsKeyInfoProvider.GetStringValue(SiteContext.CurrentSiteName + ".CMSGroupProfilePath");
                    string url       = String.Empty;

                    if (!String.IsNullOrEmpty(groupPath))
                    {
                        url = DocumentURLProvider.GetUrl(groupPath.Replace("{GroupName}", group.GroupName));
                    }
                    ShowConfirmation(String.Format(SuccessfullRegistrationText, url));
                }

                // Hide form
                if (HideFormAfterRegistration)
                {
                    plcForm.Visible = false;
                }
                else
                {
                    ClearForm();
                }
            }
            catch (Exception ex)
            {
                // Display error message
                ShowError(GetString("general.saveerror"), ex.Message, null);
            }
        }
        else
        {
            // Display error message
            ShowError(errorMessage);
        }
    }
    /// <summary>
    /// Sends e-mail to all attendees.
    /// </summary>
    protected void Send()
    {
        // Check 'Modify' permission
        if (!CheckPermissions("cms.eventmanager", "Modify"))
        {
            return;
        }

        txtSenderName.Text  = txtSenderName.Text.Trim();
        txtSenderEmail.Text = txtSenderEmail.Text.Trim();
        txtSubject.Text     = txtSubject.Text.Trim();

        // Validate the fields
        string errorMessage = new Validator()
                              .NotEmpty(txtSenderName.Text, GetString("Events_SendEmail.EmptySenderName"))
                              .NotEmpty(txtSenderEmail.Text, GetString("Events_SendEmail.EmptySenderEmail"))
                              .MatchesCondition(txtSenderEmail, input => input.IsValid(), GetString("Events_SendEmail.InvalidEmailFormat"))
                              .NotEmpty(txtSubject.Text, GetString("Events_SendEmail.EmptyEmailSubject"))
                              .Result;

        if (!String.IsNullOrEmpty(errorMessage))
        {
            ShowError(errorMessage);
            return;
        }

        string subject   = txtSubject.Text;
        string emailBody = htmlEmail.ResolvedValue;

        // Get event node data
        TreeProvider mTree = new TreeProvider();
        DocTreeNode  node  = mTree.SelectSingleNode(EventID);

        if (node != null && CMSString.Equals(node.NodeClassName, "cms.bookingevent", true))
        {
            // Initialize macro resolver
            MacroResolver resolver = MacroResolver.GetInstance();
            resolver.Settings.KeepUnresolvedMacros = true;
            resolver.SetAnonymousSourceData(node);
            // Add named source data
            resolver.SetNamedSourceData("Event", node);

            // Event date string macro
            DateTime eventDate    = ValidationHelper.GetDateTime(node.GetValue("EventDate"), DateTimeHelper.ZERO_TIME);
            DateTime eventEndDate = ValidationHelper.GetDateTime(node.GetValue("EventEndDate"), DateTimeHelper.ZERO_TIME);
            bool     isAllDay     = ValidationHelper.GetBoolean(node.GetValue("EventAllDay"), false);

            resolver.SetNamedSourceData("eventdatestring", EventProvider.GetEventDateString(eventDate, eventEndDate, isAllDay, TimeZoneHelper.GetTimeZoneInfo(SiteContext.CurrentSite), SiteContext.CurrentSiteName), false);

            // Resolve e-mail body and subject macros and make links absolute
            emailBody = resolver.ResolveMacros(emailBody);
            emailBody = URLHelper.MakeLinksAbsolute(emailBody);
            subject   = TextHelper.LimitLength(resolver.ResolveMacros(subject), 450);

            // EventSendEmail manages sending e-mails to all attendees
            EventSendEmail ese = new EventSendEmail(EventID, SiteContext.CurrentSiteName,
                                                    subject, emailBody, txtSenderName.Text.Trim(), txtSenderEmail.Text.Trim());

            ShowConfirmation(GetString("Events_SendEmail.EmailSent"));
        }
    }
Example #29
0
    /// <summary>
    /// Send e-mail to administrator about new registration.
    /// </summary>
    /// <param name="administrationApproval">Indicates if administration approval is required</param>
    private void SendEmailToAdministrator(bool administrationApproval)
    {
        EmailTemplateInfo template = null;

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

        if (template == null)
        {
            EventLogProvider.LogEvent(EventType.ERROR, "RegistrationForm", "GetEmailTemplate", eventUrl: RequestContext.RawURL);
        }
        else
        {
            // E-mail template ok
            string from = EmailHelper.GetSender(template, (!String.IsNullOrEmpty(FromAddress)) ? FromAddress : SettingsKeyInfoProvider.GetStringValue(SiteContext.CurrentSiteName + ".CMSNoreplyEmailAddress"));
            if (!String.IsNullOrEmpty(from))
            {
                // Prepare macro replacements
                string[,] replacements = new string[4, 2];
                replacements[0, 0]     = "firstname";
                replacements[0, 1]     = RegisteredUser.FirstName;
                replacements[1, 0]     = "lastname";
                replacements[1, 1]     = RegisteredUser.LastName;
                replacements[2, 0]     = "email";
                replacements[2, 1]     = RegisteredUser.Email;
                replacements[3, 0]     = "username";
                replacements[3, 1]     = RegisteredUser.UserName;

                // Set resolver
                MacroResolver resolver = MacroContext.CurrentResolver;
                resolver.SetNamedSourceData(replacements);
                resolver.Settings.EncodeResolvedValues = true;

                // Add user info data
                resolver.SetAnonymousSourceData(new object[1] {
                    RegisteredUser
                });

                // Email message
                EmailMessage email = new EmailMessage();
                email.EmailFormat = EmailFormatEnum.Default;
                email.Recipients  = AdministratorEmail;

                // Get e-mail sender and subject from template, if used
                email.From = from;
                email.Body = resolver.ResolveMacros(template.TemplateText);

                resolver.Settings.EncodeResolvedValues = false;
                email.PlainTextBody = resolver.ResolveMacros(template.TemplatePlainText);

                string emailSubject = EmailHelper.GetSubject(template, GetString("RegistrationForm.EmailSubject"));
                email.Subject       = resolver.ResolveMacros(emailSubject);
                email.CcRecipients  = template.TemplateCc;
                email.BccRecipients = template.TemplateBcc;

                try
                {
                    EmailHelper.ResolveMetaFileImages(email, template.TemplateID, EmailTemplateInfo.OBJECT_TYPE, ObjectAttachmentsCategories.TEMPLATE);
                    // Send the e-mail immediately
                    EmailSender.SendEmail(SiteContext.CurrentSiteName, email, true);
                }
                catch
                {
                    EventLogProvider.LogEvent(EventType.ERROR, "Membership", "RegistrationApprovalEmail");
                }
            }
            else
            {
                EventLogProvider.LogEvent(EventType.ERROR, "RegistrationApproval", "EmailSenderNotSpecified");
            }
        }
    }
Example #30
0
        protected void OnTabCreated(object sender, TabCreatedEventArgs e)
        {
            if (e.Tab == null)
            {
                return;
            }

            var tab     = e.Tab;
            var element = e.UIElement;
            PageTemplateInfo UITemplate = PageTemplateInfoProvider.GetPageTemplateInfo(e.UIElement.ElementPageTemplateID);
            var manager = DocumentManager;
            var node    = manager.Node;

            bool splitViewSupported = PortalContext.ViewMode != ViewModeEnum.EditLive;

            string elementName = element.ElementName.ToLowerCSafe();

            if (UITemplate.CodeName.ToLower().Contains("editrelationship"))
            {
                XmlDocument properties = new XmlDocument();
                properties.LoadXml(e.UIElement.ElementProperties);
                XmlNode LeftSideMacro  = properties.SelectSingleNode("/Data[1]/IsLeftSideMacro[1]");
                XmlNode RightSideMacro = properties.SelectSingleNode("/Data[1]/IsRightSideMacro[1]");
                XmlNode AutoHide       = properties.SelectSingleNode("/Data[1]/AutoHide[1]");

                if (AutoHide != null && ValidationHelper.GetBoolean(AutoHide.InnerText, false) && LeftSideMacro != null && RightSideMacro != null)
                {
                    MacroResolver pageResolver = MacroResolver.GetInstance();
                    // Get current node's class, then full document so it has related data.
                    int      NodeID          = ValidationHelper.GetInteger(URLHelper.GetQueryValue(RequestContext.RawURL, "nodeid"), 1);
                    string   Culture         = DataHelper.GetNotEmpty(URLHelper.GetQueryValue(RequestContext.RawURL, "culture"), "en-US");
                    TreeNode CurrentDocument = CacheHelper.Cache <TreeNode>(cs =>
                    {
                        TreeNode Document = new DocumentQuery().WhereEquals("NodeID", NodeID).Columns("ClassName").FirstOrDefault();
                        Document          = new DocumentQuery(Document.ClassName).WhereEquals("NodeID", NodeID).Culture(Culture).FirstOrDefault();
                        if (cs.Cached)
                        {
                            cs.CacheDependency = CacheHelper.GetCacheDependency(new string[] { string.Format("node|{0}|{1}|{2}", Document.NodeSiteName, Document.NodeAliasPath, Culture,
                                                                                                             PageTemplateInfo.OBJECT_TYPE + "|byid|" + e.UIElement.ElementPageTemplateID) });
                        }
                        return(Document);
                    }, new CacheSettings(CacheHelper.CacheMinutes(SiteContext.CurrentSiteName), NodeID, Culture, e.UIElement.ElementPageTemplateID));
                    pageResolver.SetNamedSourceData("CurrentDocument", CurrentDocument);
                    if (!(ValidationHelper.GetBoolean(pageResolver.ResolveMacros(LeftSideMacro.InnerText), true) || ValidationHelper.GetBoolean(pageResolver.ResolveMacros(RightSideMacro.InnerText), true)))
                    {
                        e.Tab = null;
                    }
                }
            }

            if (DocumentUIHelper.IsElementHiddenForNode(element, node))
            {
                e.Tab = null;
                return;
            }

            // Ensure split view mode
            if (splitViewSupported && PortalUIHelper.DisplaySplitMode)
            {
                tab.RedirectUrl = DocumentUIHelper.GetSplitViewUrl(tab.RedirectUrl);
            }
        }