/// <summary>
    /// Logs activity for subscribing/unsubscribing
    /// </summary>
    /// <param name="ui">User</param>
    /// <param name="newsletterId">Newsletter ID</param>
    /// <param name="subscribe">Subscribing/unsubscribing flag</param>
    /// <param name="siteId">Site ID</param>
    private void LogActivity(UserInfo ui, int newsletterId, bool subscribe, int siteId)
    {
        if ((sb == null) || (ui == null) || (CMSContext.ViewMode != ViewModeEnum.LiveSite) ||
            !ActivitySettingsHelper.ActivitiesEnabledAndModuleLoaded(siteId) || !ActivitySettingsHelper.ActivitiesEnabledForThisUser(ui))
        {
            return;
        }

        if (sb.SubscriberType == SiteObjectType.USER)
        {
            if (subscribe && ActivitySettingsHelper.NewsletterSubscribeEnabled(siteId) ||
                !subscribe && ActivitySettingsHelper.NewsletterUnsubscribeEnabled(siteId))
            {
                Newsletter news = NewsletterProvider.GetNewsletter(newsletterId);
                if ((news != null) && news.NewsletterLogActivity)
                {
                    var data = new ActivityData()
                    {
                        ContactID = ModuleCommands.OnlineMarketingGetCurrentContactID(),
                        SiteID    = sb.SubscriberSiteID,
                        Type      = PredefinedActivityType.NEWSLETTER_UNSUBSCRIBING,
                        TitleData = news.NewsletterName,
                        ItemID    = newsletterId,
                        URL       = URLHelper.CurrentRelativePath,
                        Campaign  = CMSContext.Campaign
                    };
                    ActivityLogProvider.LogActivity(data);
                }
            }
        }
    }
    /// <summary>
    /// Logs activity for unsubscribing.
    /// </summary>
    /// <param name="sb">Subscriber (optional - can be null if subscriber ID is used)</param>
    /// <param name="subscriberId">Subscriber ID (optional - can be zero if subscriber object is used)</param>
    /// <param name="newsletterId">Newsletter ID</param>
    /// <param name="siteId">Site ID</param>
    /// <param name="issueId">Issue ID</param>
    /// <param name="issueGuid">Issue GUID</param>
    /// <param name="contactId">Contact ID is present if the mail is sent to a contact group</param>
    private void LogActivity(Subscriber sb, int subscriberId, int newsletterId, int siteId, int issueId, Guid issueGuid, int contactId)
    {
        // Check if activities logging is enabled
        if ((newsletterId <= 0) || (CMSContext.ViewMode != ViewModeEnum.LiveSite) || !ActivitySettingsHelper.ActivitiesEnabledAndModuleLoaded(siteId) ||
            !ActivitySettingsHelper.NewsletterSubscribeEnabled(siteId))
        {
            return;
        }

        // Load subscriber info object according to its ID if not given
        if (sb == null)
        {
            if (subscriberId <= 0)
            {
                return;
            }
            sb = SubscriberProvider.GetSubscriber(subscriberId);
        }

        if (sb == null)
        {
            return;
        }

        Newsletter news = NewsletterProvider.GetNewsletter(newsletterId);

        if ((news != null) && news.NewsletterLogActivity)
        {
            bool isFromContactGroup = (contactId > 0);

            // Try to retrieve contact IDs for particular subscriber from membership relations
            if (!isFromContactGroup)
            {
                contactId = ActivityTrackingHelper.GetContactID(sb);
            }

            if (contactId > 0)
            {
                // Load additional info (issue id)
                if ((issueId <= 0) && (issueGuid != Guid.Empty))
                {
                    Issue issue = IssueProvider.GetIssue(issueGuid, siteId);
                    if (issue != null)
                    {
                        issueId = issue.IssueID;
                    }
                }

                var data = new ActivityData()
                {
                    ContactID    = contactId,
                    SiteID       = sb.SubscriberSiteID,
                    Type         = PredefinedActivityType.NEWSLETTER_UNSUBSCRIBING,
                    TitleData    = news.NewsletterName,
                    ItemID       = newsletterId,
                    URL          = URLHelper.CurrentRelativePath,
                    ItemDetailID = issueId,
                    Value        = (isFromContactGroup ? "contactgroup(" + sb.SubscriberRelatedID + ")" : null)
                };
                ActivityLogProvider.LogActivity(data);
            }
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        // If StopProcessing flag is set, do nothing
        if (StopProcessing)
        {
            Visible = false;
            return;
        }

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

        DateTime datetime = DateTimeHelper.ZERO_TIME;

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

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

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

        return(toReturn);
    }