/// <summary>
    /// Initializes the control properties.
    /// </summary>
    protected void SetupControl()
    {
        if (StopProcessing)
        {
            // Do nothing
        }
        else
        {
            int siteId = 0;

            // Get current id
            if (CMSContext.CurrentSite != null)
            {
                siteId = CMSContext.CurrentSiteID;
            }

            // Get subscriber and newsletter guid from query string
            Guid   subscriberGuid   = QueryHelper.GetGuid("subscriberguid", Guid.Empty);
            Guid   newsletterGuid   = QueryHelper.GetGuid("newsletterguid", Guid.Empty);
            string subscriptionHash = QueryHelper.GetString("subscriptionhash", string.Empty);
            int    issueId          = QueryHelper.GetInteger("issueid", 0);
            Guid   issueGuid        = QueryHelper.GetGuid("issueguid", Guid.Empty);
            int    contactId        = QueryHelper.GetInteger("contactid", 0);

            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
                {
                    lblError.Visible = true;
                    lblError.Text    = GetString("newsletter.unsubscribefailed");
                    return;
                }
            }

            // Check whether both guid exists
            if ((subscriberGuid != Guid.Empty) && (newsletterGuid != Guid.Empty))
            {
                Subscriber subscriber = SubscriberProvider.GetSubscriber(subscriberGuid, siteId);
                if (subscriber == null)
                {
                    lblError.Visible = true;
                    lblError.Text    = GetString("Unsubscribe.SubscriberDoesNotExist");
                    return;
                }
                // Show error message if subscriber type is 'Role'
                if (!string.IsNullOrEmpty(subscriber.SubscriberType) && subscriber.SubscriberType.Equals(SiteObjectType.ROLE, StringComparison.InvariantCultureIgnoreCase))
                {
                    lblError.Visible = true;
                    lblError.Text    = GetString("Unsubscriber.CannotUnsubscribeRole");
                    return;
                }

                Newsletter newsletter = NewsletterProvider.GetNewsletter(newsletterGuid, siteId);
                if (newsletter == null)
                {
                    lblError.Visible = true;
                    lblError.Text    = GetString("Unsubscribe.NewsletterDoesNotExist");
                    return;
                }

                // Check whether subscription is valid
                if (SubscriberProvider.IsSubscribed(subscriber.SubscriberID, newsletter.NewsletterID))
                {
                    bool isSubscribed = true;

                    if (string.IsNullOrEmpty(subscriber.SubscriberType) || !subscriber.SubscriberType.Equals(PredefinedObjectType.CONTACTGROUP, StringComparison.InvariantCultureIgnoreCase))
                    {
                        // Unsubscribe action
                        SubscriberProvider.Unsubscribe(subscriber.SubscriberID, newsletter.NewsletterID, SendConfirmationEmail);
                    }
                    else
                    {
                        // Check if the contact group member has unsubscription activity for the specified newsletter
                        isSubscribed = (contactId > 0) && !ModuleCommands.OnlineMarketingIsContactUnsubscribed(contactId, newsletter.NewsletterID, siteId);
                    }

                    if (isSubscribed)
                    {
                        // Log newsletter unsubscription activity
                        LogActivity(subscriber, subscriber.SubscriberID, newsletter.NewsletterID, subscriber.SubscriberSiteID, issueId, issueGuid, contactId);

                        // Display confirmation
                        DisplayConfirmation();
                    }
                    else
                    {
                        // Contact group member is already unsubscribed
                        lblError.Visible = true;
                        lblError.Text    = GetString("Unsubscribe.NotSubscribed");
                    }
                }
                else
                {
                    lblError.Visible = true;
                    lblError.Text    = GetString("Unsubscribe.NotSubscribed");
                }
            }
            // Check if subscriptionGUID is supplied
            else if (!string.IsNullOrEmpty(subscriptionHash))
            {
                // Check if given subscription exists
                SubscriberNewsletterInfo sni = SubscriberNewsletterInfoProvider.GetSubscriberNewsletterInfo(subscriptionHash);
                if (sni != null)
                {
                    SubscriberProvider.ApprovalResult result = SubscriberProvider.Unsubscribe(subscriptionHash, true, CMSContext.CurrentSiteName, datetime);

                    switch (result)
                    {
                    // Approving subscription was successful
                    case SubscriberProvider.ApprovalResult.Success:
                        bool isSubscribed = true;

                        // Get subscriber
                        Subscriber subscriber = SubscriberProvider.GetSubscriber(sni.SubscriberID);
                        if ((subscriber != null) && !string.IsNullOrEmpty(subscriber.SubscriberType) && subscriber.SubscriberType.Equals(PredefinedObjectType.CONTACTGROUP, StringComparison.InvariantCultureIgnoreCase))
                        {
                            // Check if the contact group member has unsubscription activity for the specified newsletter
                            isSubscribed = (contactId > 0) && !ModuleCommands.OnlineMarketingIsContactUnsubscribed(contactId, sni.NewsletterID, siteId);
                        }

                        if (isSubscribed)
                        {
                            // Log newsletter unsubscription activity
                            LogActivity(subscriber, subscriber.SubscriberID, sni.NewsletterID, siteId, issueId, issueGuid, contactId);

                            // Display confirmation
                            DisplayConfirmation();
                        }
                        else
                        {
                            // Contact group member is already unsubscribed
                            lblError.Visible = true;
                            lblError.Text    = GetString("Unsubscribe.NotSubscribed");
                        }
                        break;

                    // Subscription was already approved
                    case SubscriberProvider.ApprovalResult.Failed:
                        lblError.Visible = true;
                        lblError.Text    = GetString("newsletter.unsubscribefailed");
                        break;

                    case SubscriberProvider.ApprovalResult.TimeExceeded:
                        lblError.Visible = true;
                        lblError.Text    = GetString("newsletter.approval_timeexceeded");
                        break;

                    // Subscription not found
                    default:
                    case SubscriberProvider.ApprovalResult.NotFound:
                        lblError.Visible = true;
                        lblError.Text    = GetString("Unsubscribe.NotSubscribed");
                        break;
                    }
                }
                else
                {
                    lblError.Visible = true;
                    lblError.Text    = GetString("Unsubscribe.NotSubscribed");
                }
            }
            else
            {
                Visible = false;
            }
        }
    }
Пример #2
0
    /// <summary>
    /// Reload data.
    /// </summary>
    public override void ReloadData()
    {
        requestedUserId = ValidationHelper.GetInteger(ContextMenu.Parameter, 0);

        DataTable table = new DataTable();

        table.Columns.Add("ActionIcon");
        table.Columns.Add("ActionDisplayName");
        table.Columns.Add("ActionScript");

        // Get resource strings prefix
        string resourcePrefix = ContextMenu.ResourcePrefix;

        // Add only if community is present
        if (CommunityPresent)
        {
            // Friendship request
            if ((requestedUserId != currentUser.UserID) && UIHelper.IsFriendsModuleEnabled(CMSContext.CurrentSiteName))
            {
                FriendshipStatusEnum status = currentUser.HasFriend(requestedUserId);
                // If friendship exists add reject action or request friendship
                if (status == FriendshipStatusEnum.Approved)
                {
                    table.Rows.Add(new object[] { "friendshipreject.png", ResHelper.GetString(resourcePrefix + ".rejectfriendship|friends.rejectfriendship"), currentUser.IsAuthenticated() ? "ContextFriendshipReject(GetContextMenuParameter('" + ContextMenu.MenuID + "'))" : "ContextRedirectToSignInUrl()" });
                }
                else if ((status == FriendshipStatusEnum.None) || currentUser.IsPublic())
                {
                    table.Rows.Add(new object[] { "friendshiprequest.png", ResHelper.GetString(resourcePrefix + ".requestfriendship|friends.requestfriendship"), currentUser.IsAuthenticated() ? "ContextFriendshipRequest(GetContextMenuParameter('" + ContextMenu.MenuID + "'))" : "ContextRedirectToSignInUrl()" });
                }
                // Group invitation
                table.Rows.Add(new object[] { "invitetogroup.png", ResHelper.GetString(resourcePrefix + ".invite|groupinvitation.invite"), currentUser.IsAuthenticated() ? "ContextGroupInvitation(GetContextMenuParameter('" + ContextMenu.MenuID + "'))" : "ContextRedirectToSignInUrl()" });
            }
        }

        // Add only if messaging is present
        if (MessagingPresent)
        {
            // Check if user is in ignore list
            isInIgnoreList = ModuleCommands.MessagingIsInIgnoreList(currentUser.UserID, requestedUserId);

            // Check if user is in contact list
            isInContactList = ModuleCommands.MessagingIsInContactList(currentUser.UserID, requestedUserId);

            table.Rows.Add(new object[] { "sendmessage.png", ResHelper.GetString(resourcePrefix + ".sendmessage|sendmessage.sendmessage"), currentUser.IsAuthenticated() ? "ContextPrivateMessage(GetContextMenuParameter('" + ContextMenu.MenuID + "'))" : "ContextRedirectToSignInUrl()" });

            // Not for the same user
            if (requestedUserId != currentUser.UserID)
            {
                // Add to ignore list or add to contact list actions
                if (!isInIgnoreList)
                {
                    table.Rows.Add(new object[] { "addtoignorelist.png", ResHelper.GetString(resourcePrefix + ".addtoignorelist|messsaging.addtoignorelist"), currentUser.IsAuthenticated() ? "ContextAddToIgnoretList(GetContextMenuParameter('" + ContextMenu.MenuID + "'))" : "ContextRedirectToSignInUrl()" });
                }

                if (!isInContactList)
                {
                    table.Rows.Add(new object[] { "addtocontactlist.png", ResHelper.GetString(resourcePrefix + ".addtocontactlist|messsaging.addtocontactlist"), currentUser.IsAuthenticated() ? "ContextAddToContactList(GetContextMenuParameter('" + ContextMenu.MenuID + "'))" : "ContextRedirectToSignInUrl()" });
                }
            }
        }

        // Add count column
        DataColumn countColumn = new DataColumn();

        countColumn.ColumnName   = "Count";
        countColumn.DefaultValue = table.Rows.Count;

        table.Columns.Add(countColumn);
        repItem.DataSource = table;
        repItem.DataBind();
    }
    /// <summary>
    /// Handles reset button click. Resets zones of specified type to default settings.
    /// </summary>
    protected void btnReset_Click(object sender, EventArgs e)
    {
        // Security check
        if (!DisplayResetButton || !resetAllowed)
        {
            return;
        }

        if (pi == null)
        {
            return;
        }

        if ((zoneType == WidgetZoneTypeEnum.Editor) || (zoneType == WidgetZoneTypeEnum.Group))
        {
            // Clear document webparts/group webparts
            TreeNode node = DocumentHelper.GetDocument(pi.DocumentID, TreeProvider);

            if (node != null)
            {
                if (zoneType == WidgetZoneTypeEnum.Editor)
                {
                    node.SetValue("DocumentWebParts", String.Empty);

                    // Delete all variants
                    if (pi.UsedPageTemplateInfo != null)
                    {
                        foreach (WebPartZoneInstance zoneInstance in zoneInstances)
                        {
                            if (zoneInstance.WebPartsContainVariants)
                            {
                                ModuleCommands.OnlineMarketingResetMVTWidgetZone(zoneInstance.ZoneID, pi.UsedPageTemplateInfo.PageTemplateId, node.DocumentID);
                                ModuleCommands.OnlineMarketingResetContentPersonalizationWidgetZone(zoneInstance.ZoneID, pi.UsedPageTemplateInfo.PageTemplateId, node.DocumentID);
                            }
                        }
                    }
                }
                else if (zoneType == WidgetZoneTypeEnum.Group)
                {
                    node.SetValue("DocumentGroupWebParts", String.Empty);
                }

                // Save the document
                DocumentHelper.UpdateDocument(node, TreeProvider);
            }
        }
        else if (zoneType == WidgetZoneTypeEnum.User)
        {
            // Delete user personalization info
            PersonalizationInfo up = PersonalizationInfoProvider.GetUserPersonalization(CMSContext.CurrentUser.UserID, pi.DocumentID);
            PersonalizationInfoProvider.DeletePersonalizationInfo(up);

            // Clear cached values
            TreeNode node = DocumentHelper.GetDocument(pi.DocumentID, TreeProvider);
            if (node != null)
            {
                CacheHelper.TouchKeys(TreeProvider.GetDependencyCacheKeys(node, CMSContext.CurrentSiteName));
            }
        }
        else if (zoneType == WidgetZoneTypeEnum.Dashboard)
        {
            // Delete user personalization info
            PersonalizationInfo up = PersonalizationInfoProvider.GetDashBoardPersonalization(CMSContext.CurrentUser.UserID, PortalContext.DashboardName, PortalContext.DashboardSiteName);
            PersonalizationInfoProvider.DeletePersonalizationInfo(up);

            // Clear cached page template
            if (pi.UsedPageTemplateInfo != null)
            {
                CacheHelper.TouchKey("cms.pagetemplate|byid|" + pi.UsedPageTemplateInfo.PageTemplateId);
            }
        }

        // Make redirect to see changes after load
        string url = URLRewriter.CurrentURL;

        URLHelper.Redirect(url);
    }
    /// <summary>
    /// Reloads control.
    /// </summary>
    /// <param name="forceReload">Forces nested CMSForm to reload if true</param>
    public void ReloadData(bool forceReload)
    {
        if (StopProcessing)
        {
            return;
        }

        if (!mFormLoaded || forceReload)
        {
            // Check License
            LicenseHelper.CheckFeatureAndRedirect(RequestContext.CurrentDomain, FeatureEnum.UserContributions);

            if (!StopProcessing)
            {
                // Set document manager mode
                if (NewDocument)
                {
                    DocumentManager.Mode           = FormModeEnum.Insert;
                    DocumentManager.ParentNodeID   = NodeID;
                    DocumentManager.NewNodeClassID = ClassID;
                    DocumentManager.CultureCode    = CultureCode;
                    DocumentManager.SiteName       = SiteName;
                }
                else if (NewCulture)
                {
                    DocumentManager.Mode             = FormModeEnum.InsertNewCultureVersion;
                    DocumentManager.NodeID           = NodeID;
                    DocumentManager.CultureCode      = CultureCode;
                    DocumentManager.SiteName         = SiteName;
                    DocumentManager.SourceDocumentID = CopyDefaultDataFromDocumentID;
                }
                else
                {
                    DocumentManager.Mode        = FormModeEnum.Update;
                    DocumentManager.NodeID      = NodeID;
                    DocumentManager.SiteName    = SiteName;
                    DocumentManager.CultureCode = CultureCode;
                }

                ScriptHelper.RegisterDialogScript(Page);

                titleElem.TitleText = String.Empty;

                pnlSelectClass.Visible = false;
                pnlEdit.Visible        = false;
                pnlInfo.Visible        = false;
                pnlNewCulture.Visible  = false;
                pnlDelete.Visible      = false;

                // If node found, init the form

                if (NewDocument || (Node != null))
                {
                    // Delete action
                    if (Delete)
                    {
                        // Delete document
                        pnlDelete.Visible = true;

                        titleElem.TitleText = GetString("Content.DeleteTitle");
                        chkAllCultures.Text = GetString("ContentDelete.AllCultures");
                        chkDestroy.Text     = GetString("ContentDelete.Destroy");

                        lblQuestion.Text = GetString("ContentDelete.Question");
                        btnYes.Text      = GetString("general.yes");
                        // Prevent button double-click
                        btnYes.Attributes.Add("onclick", string.Format("document.getElementById('{0}').disabled=true;this.disabled=true;{1};", btnNo.ClientID, ControlsHelper.GetPostBackEventReference(btnYes, string.Empty, true, false)));
                        btnNo.Text = GetString("general.no");

                        DataSet culturesDS = CultureSiteInfoProvider.GetSiteCultures(SiteName);
                        if ((DataHelper.DataSourceIsEmpty(culturesDS)) || (culturesDS.Tables[0].Rows.Count <= 1))
                        {
                            chkAllCultures.Visible = false;
                            chkAllCultures.Checked = true;
                        }

                        if (Node.IsLink)
                        {
                            titleElem.TitleText    = GetString("Content.DeleteTitleLink") + " \"" + HTMLHelper.HTMLEncode(Node.NodeName) + "\"";
                            lblQuestion.Text       = GetString("ContentDelete.QuestionLink");
                            chkAllCultures.Checked = true;
                            plcCheck.Visible       = false;
                        }
                        else
                        {
                            titleElem.TitleText = GetString("Content.DeleteTitle") + " \"" + HTMLHelper.HTMLEncode(Node.NodeName) + "\"";
                        }
                    }
                    // New document or edit action
                    else
                    {
                        if (NewDocument)
                        {
                            titleElem.TitleText = GetString("Content.NewTitle");
                        }

                        // Document type selection
                        if (NewDocument && (ClassID <= 0))
                        {
                            // Use parent node
                            TreeNode parentNode = DocumentManager.ParentNode;
                            if (parentNode != null)
                            {
                                // Select document type
                                pnlSelectClass.Visible = true;

                                // Apply document type scope
                                var whereCondition = DocumentTypeScopeInfoProvider.GetScopeClassWhereCondition(parentNode);

                                var parentClassId = ValidationHelper.GetInteger(parentNode.GetValue("NodeClassID"), 0);
                                var siteId        = SiteInfoProvider.GetSiteID(SiteName);

                                // Get the allowed child classes
                                DataSet ds = AllowedChildClassInfoProvider.GetAllowedChildClasses(parentClassId, siteId)
                                             .Where(whereCondition)
                                             .OrderBy("ClassID")
                                             .Columns("ClassName", "ClassDisplayName", "ClassID");

                                ArrayList deleteRows = new ArrayList();

                                if (!DataHelper.DataSourceIsEmpty(ds))
                                {
                                    // Get the unwanted classes
                                    string allowed = AllowedChildClasses.Trim().ToLowerCSafe();
                                    if (!string.IsNullOrEmpty(allowed))
                                    {
                                        allowed = String.Format(";{0};", allowed);
                                    }

                                    var    userInfo  = MembershipContext.AuthenticatedUser;
                                    string className = null;
                                    // Check if the user has 'Create' permission per Content
                                    bool isAuthorizedToCreateInContent = userInfo.IsAuthorizedPerResource("CMS.Content", "Create");
                                    bool hasNodeAllowCreate            = (userInfo.IsAuthorizedPerTreeNode(parentNode, NodePermissionsEnum.Create) == AuthorizationResultEnum.Allowed);
                                    foreach (DataRow dr in ds.Tables[0].Rows)
                                    {
                                        className = DataHelper.GetStringValue(dr, "ClassName", String.Empty).ToLowerCSafe();
                                        // Document type is not allowed or user hasn't got permission, remove it from the data set
                                        if ((!string.IsNullOrEmpty(allowed) && (!allowed.Contains(";" + className + ";"))) ||
                                            (CheckPermissions && CheckDocPermissionsForInsert && !(isAuthorizedToCreateInContent || userInfo.IsAuthorizedPerClassName(className, "Create") || (userInfo.IsAuthorizedPerClassName(className, "CreateSpecific") && hasNodeAllowCreate))))
                                        {
                                            deleteRows.Add(dr);
                                        }
                                    }

                                    // Remove the rows
                                    foreach (DataRow dr in deleteRows)
                                    {
                                        ds.Tables[0].Rows.Remove(dr);
                                    }
                                }

                                // Check if some classes are available
                                if (!DataHelper.DataSourceIsEmpty(ds))
                                {
                                    // If number of classes is more than 1 display them in grid
                                    if (ds.Tables[0].Rows.Count > 1)
                                    {
                                        ds.Tables[0].DefaultView.Sort = "ClassDisplayName";
                                        lblError.Visible = false;
                                        lblInfo.Visible  = true;
                                        lblInfo.Text     = GetString("Content.NewInfo");

                                        DataSet sortedResult = new DataSet();
                                        sortedResult.Tables.Add(ds.Tables[0].DefaultView.ToTable());
                                        gridClass.DataSource = sortedResult;
                                        gridClass.ReloadData();
                                    }
                                    // else show form of the only class
                                    else
                                    {
                                        ClassID = DataHelper.GetIntValue(ds.Tables[0].Rows[0], "ClassID");
                                        ReloadData(true);
                                        return;
                                    }
                                }
                                else
                                {
                                    // Display error message
                                    lblError.Visible  = true;
                                    lblError.Text     = GetString("Content.NoAllowedChildDocuments");
                                    lblInfo.Visible   = false;
                                    gridClass.Visible = false;
                                }
                            }
                            else
                            {
                                pnlInfo.Visible  = true;
                                lblFormInfo.Text = GetString("EditForm.DocumentNotFound");
                            }
                        }
                        // Insert or update of a document
                        else
                        {
                            // Display the form
                            pnlEdit.Visible = true;

                            // Try to get GroupID if group context exists
                            int currentGroupId = ModuleCommands.CommunityGetCurrentGroupID();

                            btnDelete.Attributes.Add("style", "display: none;");
                            btnRefresh.Attributes.Add("style", "display: none;");

                            // CMSForm initialization
                            formElem.NodeID                 = Node.NodeID;
                            formElem.SiteName               = SiteName;
                            formElem.CultureCode            = CultureCode;
                            formElem.ValidationErrorMessage = HTMLHelper.HTMLEncode(ValidationErrorMessage);
                            formElem.IsLiveSite             = IsLiveSite;

                            // Set group ID if group context exists
                            formElem.GroupID = currentGroupId;

                            // External editing is allowed for live site only if the permissions are checked or user is global administrator or for group context - user is group administrator
                            formElem.AllowExternalEditing = !IsLiveSite || CheckPermissions || MembershipContext.AuthenticatedUser.CheckPrivilegeLevel(UserPrivilegeLevelEnum.Admin) || MembershipContext.AuthenticatedUser.IsGroupAdministrator(currentGroupId);

                            // Set the form mode
                            if (NewDocument)
                            {
                                ci = DataClassInfoProvider.GetDataClassInfo(ClassID);
                                if (ci == null)
                                {
                                    throw new Exception(String.Format("[CMSAdminControls/EditForm.aspx]: Class ID '{0}' not found.", ClassID));
                                }

                                string classDisplayName = HTMLHelper.HTMLEncode(ResHelper.LocalizeString(ci.ClassDisplayName));
                                titleElem.TitleText = GetString("Content.NewTitle") + ": " + classDisplayName;

                                // Set default template ID
                                formElem.DefaultPageTemplateID = TemplateID > 0 ? TemplateID : ci.ClassDefaultPageTemplateID;

                                // Set document owner
                                formElem.OwnerID  = OwnerID;
                                formElem.FormMode = FormModeEnum.Insert;
                                string newClassName = ci.ClassName;
                                string newFormName  = newClassName + ".default";
                                if (!String.IsNullOrEmpty(AlternativeFormName))
                                {
                                    // Set the alternative form full name
                                    formElem.AlternativeFormFullName = GetAltFormFullName(ci.ClassName);
                                }
                                if (newFormName.ToLowerCSafe() != formElem.FormName.ToLowerCSafe())
                                {
                                    formElem.FormName = newFormName;
                                }
                            }
                            else if (NewCulture)
                            {
                                formElem.FormMode = FormModeEnum.InsertNewCultureVersion;
                                // Default data document ID
                                formElem.CopyDefaultDataFromDocumentId = CopyDefaultDataFromDocumentID;

                                ci = DataClassInfoProvider.GetDataClassInfo(Node.NodeClassName);
                                formElem.FormName = Node.NodeClassName + ".default";
                                if (!String.IsNullOrEmpty(AlternativeFormName))
                                {
                                    // Set the alternative form full name
                                    formElem.AlternativeFormFullName = GetAltFormFullName(ci.ClassName);
                                }
                            }
                            else
                            {
                                formElem.FormMode = FormModeEnum.Update;
                                ci = DataClassInfoProvider.GetDataClassInfo(Node.NodeClassName);
                                formElem.FormName = String.Empty;
                                if (!String.IsNullOrEmpty(AlternativeFormName))
                                {
                                    // Set the alternative form full name
                                    formElem.AlternativeFormFullName = GetAltFormFullName(ci.ClassName);
                                }
                            }

                            // Allow the CMSForm
                            formElem.StopProcessing = false;

                            ReloadForm();
                            formElem.LoadForm(true);
                        }
                    }
                }
                // New culture version
                else
                {
                    // Switch to new culture version mode
                    DocumentManager.Mode        = FormModeEnum.InsertNewCultureVersion;
                    DocumentManager.NodeID      = NodeID;
                    DocumentManager.CultureCode = CultureCode;
                    DocumentManager.SiteName    = SiteName;

                    if (Node != null)
                    {
                        // Offer a new culture creation
                        pnlNewCulture.Visible = true;

                        titleElem.TitleText    = GetString("Content.NewCultureVersionTitle") + " (" + HTMLHelper.HTMLEncode(LocalizationContext.PreferredCultureCode) + ")";
                        lblNewCultureInfo.Text = GetString("ContentNewCultureVersion.Info");
                        radCopy.Text           = GetString("ContentNewCultureVersion.Copy");
                        radEmpty.Text          = GetString("ContentNewCultureVersion.Empty");

                        radCopy.Attributes.Add("onclick", "ShowSelection();");
                        radEmpty.Attributes.Add("onclick", "ShowSelection()");

                        AddScript(
                            "function ShowSelection() { \n" +
                            "   if (document.getElementById('" + radCopy.ClientID + "').checked) { document.getElementById('divCultures').style.display = 'block'; } \n" +
                            "   else { document.getElementById('divCultures').style.display = 'none'; } \n" +
                            "} \n"
                            );

                        btnOk.Text = GetString("ContentNewCultureVersion.Create");

                        // Load culture versions
                        SiteInfo si = SiteInfoProvider.GetSiteInfo(Node.NodeSiteID);
                        if (si != null)
                        {
                            lstCultures.Items.Clear();

                            DataSet nodes = TreeProvider.SelectNodes(si.SiteName, Node.NodeAliasPath, TreeProvider.ALL_CULTURES, false, null, null, null, 1, false);
                            foreach (DataRow nodeCulture in nodes.Tables[0].Rows)
                            {
                                ListItem li = new ListItem();
                                li.Text  = CultureInfoProvider.GetCultureInfo(nodeCulture["DocumentCulture"].ToString()).CultureName;
                                li.Value = nodeCulture["DocumentID"].ToString();
                                lstCultures.Items.Add(li);
                            }
                            if (lstCultures.Items.Count > 0)
                            {
                                lstCultures.SelectedIndex = 0;
                            }
                        }
                    }
                    else
                    {
                        pnlInfo.Visible  = true;
                        lblFormInfo.Text = GetString("EditForm.DocumentNotFound");
                    }
                }
            }
            // Set flag that the form is loaded
            mFormLoaded = true;
        }
    }
Пример #5
0
    /// <summary>
    /// Handles the PreRender event of the Page control.
    /// </summary>
    protected void Page_PreRender(object sender, EventArgs e)
    {
        if (stopProcessing)
        {
            this.Visible = false;
            return;
        }

        // Show the warning panel when there is a running MVT test
        if ((viewMode != ViewModeEnum.Preview) &&
            (ModuleCommands.OnlineMarketingContainsRunningMVTest(CMSContext.CurrentAliasPath, CMSContext.CurrentSiteID, CMSContext.CurrentPageInfo.DocumentCulture)))
        {
            plcRunningTestWarning.Visible = true;
        }

        // Setup the Update progress panel
        loading.ProgressHTML = "<div class=\"MVTLoading\" style=\"display: none;\" id=\"" + loading.ClientID + "\">" + CMSUpdateProgress.GetDefaultContent(this.Page) + "</div>";
        loading.DisplayAfter = 200;

        if (RequestHelper.IsPostBack())
        {
            // Reload the combination panel because one of the combination could have been removed
            ReloadData(true);
        }

        // Set the OnChange attribute => Save the variant slider configuration into a cookie and raise a postback
        combinationSelector.DropDownSelect.Attributes.Add("onchange", "SaveCombinationPanelSelection(); " + Page.ClientScript.GetPostBackEventReference(this, "combinationchanged") + "; return false;");


        MVTCombinationInfo ci = null;

        if (CMSContext.CurrentDocument != null)
        {
            // Get the combination name from cookie
            string combinationName = CookieHelper.GetValue(cookieTestName);
            if (string.IsNullOrEmpty(combinationName))
            {
                // CombinationName is not defined, use the default combination for the page template
                ci = MVTCombinationInfoProvider.GetDefaultCombinationInfo(CMSContext.CurrentDocument.DocumentPageTemplateID);
            }
            else
            {
                // Keep current instance node
                TreeNode tn = CMSContext.CurrentDocument;

                // Use the defined combination
                ci = MVTCombinationInfoProvider.GetMVTCombinationInfo(tn.NodeAliasPath, combinationName, CMSContext.CurrentSiteName, tn.DocumentCulture);

                if (ci == null)
                {
                    // Combination not found (can happen after deleting a variant), use the default combination for the page template
                    ci = MVTCombinationInfoProvider.GetDefaultCombinationInfo(CMSContext.CurrentDocument.DocumentPageTemplateID);
                }
            }
        }

        // Show the combination panel only if there are any combinations for the document
        pnlMvtCombination.Enabled = combinationSelector.HasData;

        if (ci != null)
        {
            int combinationId = ci.MVTCombinationID;

            // Setup the combination panel values
            combinationSelector.DropDownSelect.SelectedValue = ci.MVTCombinationName.ToString();
            chkEnabled.Checked = ci.MVTCombinationEnabled;
            txtCustomName.Text = ResHelper.LocalizeString(ci.MVTCombinationCustomName, currentUser.PreferredUICultureCode);

            // Create javascript variables of the combination panel. Used when changing combination by the variation slider/arrows
            StringBuilder combinationJSList = new StringBuilder();
            combinationJSList.Append("var mvtCPselector = document.getElementById('" + combinationSelector.DropDownSelect.ClientID + "');");
            combinationJSList.Append("var mvtCPenabled = document.getElementById('" + chkEnabled.ClientID + "');");
            combinationJSList.Append("var mvtCPcustomName = document.getElementById('" + txtCustomName.ClientID + "');");
            combinationJSList.Append("var mvtCPcurrentCombinationName = document.getElementById('" + hdnCurrentCombination.ClientID + "');");
            // Move the update progress panel to the body element. This will fix the absolute/relative positioning issue.
            combinationJSList.Append("function InitUpdateProgress() { $j(document.body).prepend($j('#", loading.ClientID, "')); }");

            // Generate the JS configuration array for the Edit and Design view modes only (modes where the variatn sliders can be used)
            if ((viewMode == ViewModeEnum.Edit) || (viewMode == ViewModeEnum.EditDisabled) ||
                (viewMode == ViewModeEnum.Design) || (viewMode == ViewModeEnum.DesignDisabled))
            {
                // Get variants for the selected combination
                DataSet dsSelectedCombinationVariants = MVTVariantInfoProvider.GetMVTVariants(ci.MVTCombinationPageTemplateID, combinationId);

                #region "Generate javascript arrays used for changing the selected combination according to the selected variants"

                // List of compulsory combination variants (used for the combination JS array only).
                // For example:
                // Selected combination contains WidgetVariantID3 + ZoneVariantID5 and the user is in the Edit mode.
                // Therefore compulsory combination variants will be only containing the zone variant ID 5-> that means: only combinations with this compulsory variant will be proceed
                // This ensures a correct behaviour of the combination panel when changing the variant sliders.
                combinationJSList.Append("var compulsoryCombinationVariants = [");
                int compulsoryCombinationVariantsCounter = 0;

                // Fill the array 'compulsoryCombinationVariants'
                if (!SqlHelperClass.DataSourceIsEmpty(dsSelectedCombinationVariants))
                {
                    // Edit mode
                    if ((viewMode == ViewModeEnum.Edit) || (viewMode == ViewModeEnum.EditDisabled))
                    {
                        foreach (DataRow row in dsSelectedCombinationVariants.Tables[0].Rows)
                        {
                            // Process web part and zones only
                            if (ValidationHelper.GetInteger(row["MVTVariantDocumentID"], 0) == 0)
                            {
                                if (compulsoryCombinationVariantsCounter > 0)
                                {
                                    combinationJSList.Append(",");
                                }
                                // Add the web part/zone to the JS array
                                combinationJSList.Append(ValidationHelper.GetInteger(row["MVTVariantID"], 0));
                                compulsoryCombinationVariantsCounter++;
                            }
                        }
                    }
                    // Design mode
                    else if ((viewMode == ViewModeEnum.Design) || (viewMode == ViewModeEnum.DesignDisabled))
                    {
                        foreach (DataRow row in dsSelectedCombinationVariants.Tables[0].Rows)
                        {
                            // Process widgets only
                            if (ValidationHelper.GetInteger(row["MVTVariantDocumentID"], 0) > 0)
                            {
                                if (compulsoryCombinationVariantsCounter > 0)
                                {
                                    combinationJSList.Append(",");
                                }
                                // Add the widget to the JS array
                                combinationJSList.Append(ValidationHelper.GetInteger(row["MVTVariantID"], 0));
                                compulsoryCombinationVariantsCounter++;
                            }
                        }
                    }
                }

                combinationJSList.Append("];");

                // combinationsArray - array containg configuration of each combination displayed in the combination panel.
                // This array is used after the user changes a variant slider and the new combination (selected by the combination panel) is to be calculated.
                combinationJSList.Append("var combinationsArray = [");
                int combinationCount = 0;

                foreach (ListItem item in combinationSelector.DropDownSelect.Items)
                {
                    // Get the combination object
                    MVTCombinationInfo cObj = MVTCombinationInfoProvider.GetMVTCombinationInfo(combinationSelector.PageTemplateID, item.Value);

                    if (cObj != null)
                    {
                        DataSet cVariants = MVTVariantInfoProvider.GetMVTVariants(cObj.MVTCombinationPageTemplateID, cObj.MVTCombinationID);
                        if (combinationCount > 0)
                        {
                            combinationJSList.Append(",");
                        }

                        combinationJSList.Append("['");
                        combinationJSList.Append(cObj.MVTCombinationName);
                        combinationJSList.Append("',");
                        combinationJSList.Append(cObj.MVTCombinationEnabled.ToString().ToLower());
                        combinationJSList.Append(",");
                        combinationJSList.Append(ScriptHelper.GetString(ResHelper.LocalizeString(cObj.MVTCombinationCustomName, currentUser.PreferredUICultureCode)));

                        // Generate the unique variant IDs code (format: 155_158_180) - must be ordered by variantID
                        combinationJSList.Append(",'");
                        if (!SqlHelperClass.DataSourceIsEmpty(cVariants))
                        {
                            int variantCount = 0;
                            foreach (DataRow row in cVariants.Tables[0].Rows)
                            {
                                if (variantCount > 0)
                                {
                                    combinationJSList.Append("_");
                                }

                                combinationJSList.Append(ValidationHelper.GetString(row["MVTVariantID"], "0"));
                                variantCount++;
                            }
                        }

                        combinationJSList.Append("']");
                    }

                    combinationCount++;
                }

                combinationJSList.Append("];");

                #endregion

                // Temporary variables
                Guid   instanceGuid      = Guid.Empty;
                string variantGuid       = string.Empty;
                string itemIdentifier    = string.Empty;
                int    itemVariantId     = 0;
                bool   itemIsZoneVariant = false;

                // Choose the correct variant from all rendered variants for a current web part (used in Content->Desing/Edit page)
                if (!SqlHelperClass.DataSourceIsEmpty(dsSelectedCombinationVariants))
                {
                    combinationJSList.Append("function SetCombinationVariants() {");
                    bool variantWasSet = false;

                    // Process all the variants of the selected combination
                    foreach (DataRow row in dsSelectedCombinationVariants.Tables[0].Rows)
                    {
                        itemIsZoneVariant = string.IsNullOrEmpty(ValidationHelper.GetString(row["MVTVariantInstanceGUID"], string.Empty));
                        itemVariantId     = ValidationHelper.GetInteger(row["MVTVariantID"], 0);

                        if (itemIsZoneVariant)
                        {
                            // Zone
                            itemIdentifier = "Variant_Zone_" + HTMLHelper.HTMLEncode(ValidationHelper.GetString(row["MVTVariantZoneID"], string.Empty));
                        }
                        else
                        {
                            // Web part/widget
                            itemIdentifier = "Variant_WP_" + ValidationHelper.GetGuid(row["MVTVariantInstanceGUID"], Guid.Empty).ToString("N");
                        }

                        // Set the appropriate variant
                        combinationJSList.Append("SetVariant('" + itemIdentifier + "', " + itemVariantId + ");");
                        variantWasSet = true;
                    }

                    if (variantWasSet)
                    {
                        // Refresh the combination panel if any variant was set manually
                        combinationJSList.Append("UpdateCombinationPanel();");
                    }

                    combinationJSList.Append("}");
                }
            }

            // Save the current combination id in javascript
            combinationJSList.Append("mvtCPcurrentCombinationName.value = '" + ci.MVTCombinationName + "';");

            // Register the JS arrays and current variants
            ScriptHelper.RegisterStartupScript(this, typeof(string), "combinationJSList", ScriptHelper.GetScript(combinationJSList.ToString()));
        }

        // Display the "set as result" button when there any MVT variants in the page
        if ((currentUser != null) &&
            (currentUser.IsAuthorizedPerResource("CMS.Design", "Design")))
        {
            plcUseCombination.Visible = combinationSelector.DropDownSelect.Items.Count > 1;
        }
    }
    /// <summary>
    /// Page Load.
    /// </summary>
    protected void Page_Load(object sender, EventArgs e)
    {
        // If StopProcessing flag is set, do nothing
        if (StopProcessing)
        {
            Visible = false;
            return;
        }

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

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

            UserInfo ui = UserInfoProvider.GetUserInfoByGUID(userGuid);

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

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

            #endregion


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

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

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

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

                // If user is already waiting for approval, dont send email again, just show info label
                if (ui.UserSettings.UserWaitingForApproval)
                {
                    return;
                }

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

            // Save changes
            UserInfoProvider.SetUserInfo(ui);

            Activity activity = new ActivityRegistration(ui, CMSContext.CurrentDocument, CMSContext.ActivityEnvironmentVariables);
            if (activity.Data != null)
            {
                int contactId = QueryHelper.GetInteger("contactid", 0);
                if (contactId <= 0)
                {
                    contactId = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui);
                }

                activity.Data.ContactID = contactId;
                activity.CheckViewMode  = false;
                activity.Log();
            }

            #region "Administrator notification email"

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

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

                EventLogProvider ev = new EventLogProvider();

                if (template == null)
                {
                    ev.LogEvent("E", DateTime.Now, "RegistrationForm", "GetEmailTemplate", HTTPHelper.GetAbsoluteUri());
                }
                //email template ok
                else
                {
                    string from = EmailHelper.GetSender(template, (!String.IsNullOrEmpty(FromAddress)) ? FromAddress : SettingsKeyProvider.GetStringValue(CMSContext.CurrentSiteName + ".CMSNoreplyEmailAddress"));
                    if (!String.IsNullOrEmpty(from))
                    {
                        // Prepare macro replacements
                        string[,] replacements = new string[4, 2];
                        replacements[0, 0]     = "firstname";
                        replacements[0, 1]     = ui.FirstName;
                        replacements[1, 0]     = "lastname";
                        replacements[1, 1]     = ui.LastName;
                        replacements[2, 0]     = "email";
                        replacements[2, 1]     = ui.Email;
                        replacements[3, 0]     = "username";
                        replacements[3, 1]     = ui.UserName;

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



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

                        // Get e-mail sender and subject from template, if used
                        email.From = from;

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

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

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

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

                        try
                        {
                            MetaFileInfoProvider.ResolveMetaFileImages(email, template.TemplateID, EmailObjectType.EMAILTEMPLATE, MetaFileInfoProvider.OBJECT_CATEGORY_TEMPLATE);
                            // Send the e-mail immediately
                            EmailSender.SendEmail(CMSContext.CurrentSiteName, email, true);
                        }
                        catch
                        {
                            ev.LogEvent("E", DateTime.Now, "Membership", "RegistrationApprovalEmail", CMSContext.CurrentSite.SiteID);
                        }
                    }
                    else
                    {
                        EventLogProvider eventLog = new EventLogProvider();
                        eventLog.LogEvent(EventLogProvider.EVENT_TYPE_ERROR, DateTime.Now, "RegistrationApproval", "EmailSenderNotSpecified");
                    }
                }
            }

            #endregion
        }
        else
        {
            Visible = false;
        }
    }
Пример #7
0
    /// <summary>
    /// Saves webpart properties.
    /// </summary>
    public bool Save()
    {
        // Check MVT/CP security
        if (VariantID > 0)
        {
            // Check OnlineMarketing permissions.
            if (!CheckPermissions("Manage"))
            {
                lblError.Visible = true;
                lblError.Text    = GetString("general.modifynotallowed");
                return(false);
            }
        }

        // Save the data
        if ((pi != null) && (pti != null) && (templateInstance != null) && SaveForm(form))
        {
            // Add web part if new
            if (IsNewWebPart)
            {
                AddWebPart();
            }

            WebPartInstance originalWebPartInstance = webPartInstance;
            if (IsNewVariant)
            {
                webPartInstance             = webPartInstance.Clone();
                webPartInstance.VariantMode = VariantModeFunctions.GetVariantModeEnum(QueryHelper.GetString("variantmode", String.Empty).ToLower());
            }

            // Get basicform's datarow and update webpart
            SaveFormToWebPart(form);

            bool isWebPartVariant = (VariantID > 0) || (ZoneVariantID > 0) || IsNewVariant;
            if (!isWebPartVariant)
            {
                // Save the changes
                CMSPortalManager.SaveTemplateChanges(pi, pti, templateInstance, WidgetZoneTypeEnum.None, ViewModeEnum.Design, tree);
            }
            else
            {
                // Save the variant properties
                if ((webPartInstance != null) &&
                    (webPartInstance.ParentZone != null) &&
                    (!webPartInstance.ParentZone.HasVariants) && // Save only if the parent zone does not have any variants
                    (webPartInstance.ParentZone.ParentTemplateInstance != null) &&
                    (webPartInstance.ParentZone.ParentTemplateInstance.ParentPageTemplate != null))
                {
                    string      variantName             = string.Empty;
                    string      variantDisplayName      = string.Empty;
                    string      variantDisplayCondition = string.Empty;
                    string      variantDescription      = string.Empty;
                    bool        variantEnabled          = true;
                    string      zoneId       = webPartInstance.ParentZone.ZoneID;
                    int         templateId   = webPartInstance.ParentZone.ParentTemplateInstance.ParentPageTemplate.PageTemplateId;
                    Guid        instanceGuid = Guid.Empty;
                    XmlDocument doc          = new XmlDocument();
                    XmlNode     xmlWebParts  = null;

                    if (ZoneVariantID > 0)
                    {
                        // This webpart is in a zone variant therefore save the whole variant webparts
                        xmlWebParts = webPartInstance.ParentZone.GetXmlNode(doc);
                        if (VariantMode == VariantModeEnum.MVT)
                        {
                            // MVT variant
                            ModuleCommands.OnlineMarketingSaveMVTVariantWebParts(ZoneVariantID, xmlWebParts);
                        }
                        else if (VariantMode == VariantModeEnum.ContentPersonalization)
                        {
                            // Content personalization variant
                            ModuleCommands.OnlineMarketingSaveContentPersonalizationVariantWebParts(ZoneVariantID, xmlWebParts);
                        }
                    }
                    else
                    {
                        // web part/widget variant
                        xmlWebParts  = webPartInstance.GetXmlNode(doc);
                        instanceGuid = InstanceGUID;

                        Hashtable properties = WindowHelper.GetItem("variantProperties") as Hashtable;
                        if (properties != null)
                        {
                            variantName        = ValidationHelper.GetString(properties["codename"], string.Empty);
                            variantDisplayName = ValidationHelper.GetString(properties["displayname"], string.Empty);
                            variantDescription = ValidationHelper.GetString(properties["description"], string.Empty);
                            variantEnabled     = ValidationHelper.GetBoolean(properties["enabled"], true);
                            if (VariantMode == VariantModeEnum.ContentPersonalization)
                            {
                                variantDisplayCondition = ValidationHelper.GetString(properties["condition"], string.Empty);
                            }
                        }

                        // Save the web part variant properties
                        if (VariantMode == VariantModeEnum.MVT)
                        {
                            // MVT variant
                            ModuleCommands.OnlineMarketingSaveMVTVariant(VariantID, variantName, variantDisplayName, variantDescription, variantEnabled, zoneId, webPartInstance.InstanceGUID, templateId, 0, xmlWebParts);
                        }
                        else if (VariantMode == VariantModeEnum.ContentPersonalization)
                        {
                            // Content personalization variant
                            ModuleCommands.OnlineMarketingSaveContentPersonalizationVariant(VariantID, variantName, variantDisplayName, variantDescription, variantEnabled, variantDisplayCondition, zoneId, webPartInstance.InstanceGUID, templateId, 0, xmlWebParts);
                        }

                        // The variants are cached -> Reload
                        if (originalWebPartInstance != null)
                        {
                            originalWebPartInstance.LoadVariants(true, VariantMode);
                        }
                    }
                }
            }

            // Reload the form (because of macro values set only by JS)
            form.ReloadData();

            // Clear the cached web part
            if (InstanceGUID != null)
            {
                CacheHelper.TouchKey("webpartinstance|" + InstanceGUID.ToString().ToLower());
            }

            return(true);
        }
        else if ((webPartInstance != null) && (webPartInstance.ParentZone != null))
        {
            // Reload the zone/web part variants when saving of the form fails
            webPartInstance.ParentZone.LoadVariants(true, VariantModeEnum.None);
        }

        return(false);
    }
    /// <summary>
    /// On items selected event handling.
    /// </summary>
    private void usRoles_OnItemsSelected(object sender, EventArgs e)
    {
        // Remove old items
        string newValues = ValidationHelper.GetString(usRoles.Value, null);
        string items     = DataHelper.GetNewItemsInList(newValues, CurrentValues);

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

            // Add all new items to site
            foreach (string item in newItems)
            {
                int roleID = ValidationHelper.GetInteger(item, 0);

                if (PollID > 0)
                {
                    // Remove role from poll
                    ModuleCommands.PollsRemoveRoleFromPoll(roleID, PollID);
                }
                else if (FormID > 0)
                {
                    // Remove role from form
                    BizFormRoleInfoProvider.DeleteBizFormRoleInfo(roleID, FormID);
                }
                else if (BoardID > 0)
                {
                    // Remove message board from board
                    ModuleCommands.MessageBoardRemoveRoleFromBoard(roleID, BoardID);
                }
                else if (Node != null)
                {
                    RoleInfo ri = RoleInfoProvider.GetRoleInfo(roleID);
                    // Remove role from treenode
                    AclItemInfoProvider.RemoveRole(NodeID, ri);
                }
            }
        }

        // Add new items
        items = DataHelper.GetNewItemsInList(CurrentValues, newValues);
        if (!String.IsNullOrEmpty(items))
        {
            string[] newItems = items.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);

            // Add all new items to site
            foreach (string item in newItems)
            {
                int roleID = ValidationHelper.GetInteger(item, 0);

                if (PollID > 0)
                {
                    // Add poll role
                    ModuleCommands.PollsAddRoleToPoll(roleID, PollID);
                }
                else if (FormID > 0)
                {
                    // Add BizForm role
                    BizFormRoleInfoProvider.SetBizFormRoleInfo(roleID, FormID);
                }
                else if (BoardID > 0)
                {
                    // Add role to the message board
                    ModuleCommands.MessageBoardAddRoleToBoard(roleID, BoardID);
                }
                else if (Node != null)
                {
                    RoleInfo ri = RoleInfoProvider.GetRoleInfo(roleID);
                    // Add role to treenode
                    AclItemInfoProvider.SetRolePermissions(Node, 0, 0, ri);
                }
            }
        }

        // Log synchronization task
        if (Node != null)
        {
            DocumentSynchronizationHelper.LogDocumentChange(Node, TaskTypeEnum.UpdateDocument, Node.TreeProvider);
        }

        RaiseOnChanged();
    }
Пример #9
0
    /// <summary>
    /// Runs the search.
    /// </summary>
    private void Search()
    {
        if (!string.IsNullOrEmpty(txtWord.Text))
        {
            string url = SearchResultsPageUrl;

            if (url.StartsWith("~"))
            {
                url = ResolveUrl(url.Trim());
            }

            url = URLHelper.UpdateParameterInUrl(url, "searchtext", HttpUtility.UrlEncode(txtWord.Text));
            url = URLHelper.UpdateParameterInUrl(url, "searchmode", SearchHelper.GetSearchModeString(SearchMode));

            // Log "internal search" activity
            string siteName = CMSContext.CurrentSiteName;
            if ((CMSContext.ViewMode == ViewModeEnum.LiveSite) && ActivitySettingsHelper.ActivitiesEnabledAndModuleLoaded(siteName) &&
                ActivitySettingsHelper.ActivitiesEnabledForThisUser(CMSContext.CurrentUser) &&
                ActivitySettingsHelper.SearchEnabled(siteName))
            {
                ActivityLogProvider.LogInternalSearchActivity(CMSContext.CurrentDocument, ModuleCommands.OnlineMarketingGetCurrentContactID(),
                                                              CMSContext.CurrentSiteID, URLHelper.CurrentRelativePath, txtWord.Text, CMSContext.Campaign);
            }

            URLHelper.Redirect(url.Trim());
        }
    }
Пример #10
0
    /// <summary>
    /// On items selected event handling.
    /// </summary>
    private void usRoles_OnItemsSelected(object sender, EventArgs e)
    {
        AclProvider aclProv = null;

        // Create Acl provider to current treenode
        if (Node != null)
        {
            aclProv = new AclProvider(Tree);
        }

        // Remove old items
        string newValues = ValidationHelper.GetString(usRoles.Value, null);
        string items     = DataHelper.GetNewItemsInList(newValues, CurrentValues);

        if (!String.IsNullOrEmpty(items))
        {
            string[] newItems = items.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
            if (newItems != null)
            {
                // Add all new items to site
                foreach (string item in newItems)
                {
                    int roleID = ValidationHelper.GetInteger(item, 0);

                    if (PollID > 0)
                    {
                        // Remove role from poll
                        ModuleCommands.PollsRemoveRoleFromPoll(roleID, PollID);
                    }
                    else if (FormID > 0)
                    {
                        // Remove role from form
                        BizFormInfoProvider.RemoveRoleFromForm(roleID, FormID);
                    }
                    else if (BoardID > 0)
                    {
                        // Check permissions
                        if (CMSContext.CurrentUser.IsAuthorizedPerResource("cms.messageboards", CMSAdminControl.PERMISSION_MODIFY))
                        {
                            // Remove message board from board
                            ModuleCommands.MessageBoardRemoveRoleFromBoard(roleID, BoardID);
                        }
                    }
                    else if (Node != null)
                    {
                        if (aclProv != null)
                        {
                            // Remove role from treenode
                            aclProv.RemoveRole(NodeID, roleID);
                        }
                    }
                }
            }
        }

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

                    if (PollID > 0)
                    {
                        // Add poll role
                        ModuleCommands.PollsAddRoleToPoll(roleID, PollID);
                    }
                    else if (FormID > 0)
                    {
                        // Add BizForm role
                        BizFormInfoProvider.AddRoleToForm(roleID, FormID);
                    }
                    else if (BoardID > 0)
                    {
                        // Add role to the message board
                        ModuleCommands.MessageBoardAddRoleToBoard(roleID, BoardID);
                    }
                    else if (Node != null)
                    {
                        // Add role to treenode
                        if (aclProv != null)
                        {
                            aclProv.SetRolePermissions(Node, 0, 0, roleID);
                        }
                    }
                }
            }
        }

        // Log synchronization task
        if (Node != null)
        {
            DocumentSynchronizationHelper.LogDocumentChange(Node, TaskTypeEnum.UpdateDocument, Node.TreeProvider);
        }

        RaiseOnChanged();
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        // Add event handling
        usRoles.OnItemsSelected += usRoles_OnItemsSelected;

        // Check if document is owned by group
        if (GroupID > 0)
        {
            if (NodeID > 0)
            {
                usRoles.SetValue("GroupID", GroupID.ToString());
            }
            else
            {
                usRoles.WhereCondition = "RoleGroupID=" + GroupID;
            }
        }
        else
        {
            usRoles.WhereCondition = SqlHelper.AddWhereCondition(usRoles.WhereCondition, "RoleGroupID IS NULL");
        }

        // Check if site filter should be displayed
        if (ShowSiteFilter)
        {
            usRoles.SetValue("DefaultFilterValue", SiteContext.CurrentSiteID);
            usRoles.SetValue("FilterMode", "role");
            usRoles.SetValue("ShowSiteFilter", true);
            usRoles.FilterControl = "~/CMSFormControls/Filters/SiteFilter.ascx";
        }
        else
        {
            usRoles.WhereCondition = SqlHelper.AddWhereCondition(usRoles.WhereCondition, "(SiteID IS NULL OR SiteID = " + SiteContext.CurrentSiteID + ")");
        }

        // Check node permissions
        if (Node != null)
        {
            // Check if filter should be used
            if ((GroupID > 0) || ShowSiteFilter)
            {
                // Add sites filter
                usRoles.FilterControl = "~/CMSFormControls/Filters/SiteGroupFilter.ascx";
                usRoles.SetValue("FilterMode", "role");
            }

            // Allow group administrator edit group document permissions on live site
            if ((GroupID > 0) && IsLiveSite)
            {
                if (MembershipContext.AuthenticatedUser.IsGroupAdministrator(GroupID))
                {
                    usRoles.Enabled = true;
                    return;
                }
            }

            if (MembershipContext.AuthenticatedUser.IsAuthorizedPerDocument(Node, NodePermissionsEnum.ModifyPermissions) != AuthorizationResultEnum.Allowed)
            {
                usRoles.Enabled = false;
                return;
            }
        }

        // Check bizform 'EditForm' permission
        if (FormID > 0)
        {
            if (!MembershipContext.AuthenticatedUser.IsAuthorizedPerResource("cms.form", "EditForm"))
            {
                usRoles.Enabled = false;
                return;
            }
        }

        // Check poll permission
        if (PollID > 0)
        {
            if (GroupID > 0)
            {
                if (!MembershipContext.AuthenticatedUser.IsGroupAdministrator(GroupID))
                {
                    usRoles.Enabled = false;
                    return;
                }
            }
            else
            {
                if (!MembershipContext.AuthenticatedUser.IsAuthorizedPerResource("cms.polls", "Modify"))
                {
                    usRoles.Enabled = false;
                    return;
                }
            }
        }

        // Check message board permission
        if (BoardID > 0)
        {
            GeneralizedInfo boardObj = ModuleCommands.MessageBoardGetMessageBoardInfo(BoardID);
            if (boardObj != null)
            {
                int boardGroupId = ValidationHelper.GetInteger(boardObj.GetValue("BoardGroupID"), 0);
                if (boardGroupId > 0)
                {
                    if (!MembershipContext.AuthenticatedUser.IsGroupAdministrator(boardGroupId))
                    {
                        usRoles.Enabled = false;
                        return;
                    }
                }
                else if (!MembershipContext.AuthenticatedUser.IsAuthorizedPerResource("CMS.MessageBoards", "Modify"))
                {
                    usRoles.Enabled = false;
                    return;
                }
            }
        }

        if (!IsLiveSite)
        {
            ScriptHelper.RegisterDialogScript(Page);
        }
    }
Пример #12
0
    /// <summary>
    /// Handles btnOkNew click, creates new user and joins it with LinkedIn member id.
    /// </summary>
    protected void btnOkNew_Click(object sender, EventArgs e)
    {
        if (!String.IsNullOrEmpty(linkedInHelper.MemberId))
        {
            string currentSiteName = SiteContext.CurrentSiteName;

            // Validate entered values
            string errorMessage = new Validator().IsRegularExp(txtUserNameNew.Text, "^([a-zA-Z0-9_\\-\\.@]+)$", GetString("mem.linkedin.fillcorrectusername"))
                                  .IsEmail(txtEmail.Text, GetString("mem.linkedin.fillvalidemail")).Result;

            string password = passStrength.Text;

            // If password is enabled to set, check it
            if (plcPasswordNew.Visible && (String.IsNullOrEmpty(errorMessage)))
            {
                if (String.IsNullOrEmpty(password))
                {
                    errorMessage = GetString("mem.linkedin.specifyyourpass");
                }
                else if (password != txtConfirmPassword.Text.Trim())
                {
                    errorMessage = GetString("webparts_membership_registrationform.passwordonotmatch");
                }

                // Check policy
                if (!passStrength.IsValid())
                {
                    errorMessage = AuthenticationHelper.GetPolicyViolationMessage(SiteContext.CurrentSiteName);
                }
            }

            // Check whether email is unique if it is required
            if ((String.IsNullOrEmpty(errorMessage)) && !UserInfoProvider.IsEmailUnique(txtEmail.Text.Trim(), currentSiteName, 0))
            {
                errorMessage = GetString("UserInfo.EmailAlreadyExist");
            }

            // Check reserved names
            if ((String.IsNullOrEmpty(errorMessage)) && UserInfoProvider.NameIsReserved(currentSiteName, txtUserNameNew.Text.Trim()))
            {
                errorMessage = GetString("Webparts_Membership_RegistrationForm.UserNameReserved").Replace("%%name%%", HTMLHelper.HTMLEncode(txtUserNameNew.Text.Trim()));
            }

            if (String.IsNullOrEmpty(errorMessage))
            {
                // Check if user with given username already exists
                UserInfo ui = UserInfoProvider.GetUserInfo(txtUserNameNew.Text.Trim());

                // User with given username is already registered
                if (ui != null)
                {
                    plcError.Visible = true;
                    lblError.Text    = GetString("mem.openid.usernameregistered");
                }
                else
                {
                    // Register new user
                    string error = DisplayMessage;
                    ui             = AuthenticationHelper.AuthenticateLinkedInUser(linkedInHelper.MemberId, linkedInHelper.FirstName, linkedInHelper.LastName, currentSiteName, true, false, ref error);
                    DisplayMessage = error;

                    if (ui != null)
                    {
                        // Set additional information
                        ui.UserName = ui.UserNickName = txtUserNameNew.Text.Trim();
                        ui.Email    = txtEmail.Text;

                        if (linkedInHelper.BirthDate != DateTimeHelper.ZERO_TIME)
                        {
                            ui.UserSettings.UserDateOfBirth = linkedInHelper.BirthDate;
                        }

                        // Set password
                        if (plcPasswordNew.Visible)
                        {
                            UserInfoProvider.SetPassword(ui, password);

                            // If user can choose password then is not considered external(external user can't login in common way)
                            ui.IsExternal = false;
                        }

                        UserInfoProvider.SetUserInfo(ui);

                        // Remove live user object from session, won't be needed
                        SessionHelper.Remove(SESSION_NAME_USERDATA);

                        // Notify administrator
                        bool requiresConfirmation = SettingsKeyInfoProvider.GetBoolValue(SiteContext.CurrentSiteName + ".CMSRegistrationEmailConfirmation");
                        if (!requiresConfirmation && NotifyAdministrator && (FromAddress != String.Empty) && (ToAddress != String.Empty))
                        {
                            AuthenticationHelper.NotifyAdministrator(ui, FromAddress, ToAddress);
                        }

                        // Send registration e-mails
                        AuthenticationHelper.SendRegistrationEmails(ui, ApprovalPage, password, true, SendWelcomeEmail);

                        // Log user registration into the web analytics and track conversion if set
                        AnalyticsHelper.TrackUserRegistration(currentSiteName, ui, TrackConversionName, ConversionValue);

                        Activity activity = new ActivityRegistration(ui, DocumentContext.CurrentDocument, AnalyticsContext.ActivityEnvironmentVariables);
                        if (activity.Data != null)
                        {
                            activity.Data.ContactID = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui);
                            activity.Log();
                        }

                        // Set authentication cookie and redirect to page
                        SetAuthCookieAndRedirect(ui);

                        if (!String.IsNullOrEmpty(DisplayMessage))
                        {
                            lblInfo.Visible = true;
                            lblInfo.Text    = DisplayMessage;
                            plcForm.Visible = false;
                        }
                        else
                        {
                            URLHelper.Redirect(ResolveUrl("~/Default.aspx"));
                        }
                    }
                }
            }
            // Validation failed - display error message
            else
            {
                lblError.Text    = errorMessage;
                plcError.Visible = true;
            }
        }
    }
Пример #13
0
    /// <summary>
    /// Initializes the control properties.
    /// </summary>
    protected void SetupControl()
    {
        if (StopProcessing)
        {
            // Do nothing
        }
        else
        {
            plcOther.Controls.Clear();

            if (CMSContext.CurrentUser.IsAuthenticated())
            {
                // Set the layout of tab menu
                tabMenu.TabControlLayout = BasicTabControl.GetTabMenuLayout(TabControlLayout);

                // Remove 'saved' parameter from query string
                string absoluteUri = URLHelper.RemoveParameterFromUrl(URLRewriter.CurrentURL, "saved");

                CurrentUserInfo currentUser = CMSContext.CurrentUser;

                // Get customer info
                GeneralizedInfo customer       = ModuleCommands.ECommerceGetCustomerInfoByUserId(currentUser.UserID);
                bool            userIsCustomer = (customer != null);

                // Get friends enabled setting
                bool friendsEnabled = UIHelper.IsFriendsModuleEnabled(CMSContext.CurrentSiteName);

                // Get customer ID
                int customerId = 0;
                if (userIsCustomer)
                {
                    customerId = ValidationHelper.GetInteger(customer.ObjectID, 0);
                }

                // Selected page URL
                string selectedPage = string.Empty;

                // Menu initialization
                tabMenu.UrlTarget = "_self";
                ArrayList activeTabs = new ArrayList();
                string    tabName    = string.Empty;

                // Set array size of tab control
                int arraySize = 0;
                if (DisplayMyPersonalSettings)
                {
                    arraySize++;
                }
                if (DisplayMyMessages)
                {
                    arraySize++;
                }

                // Handle 'Notifications' tab displaying
                bool hideUnavailableUI       = SettingsKeyProvider.GetBoolValue("CMSHideUnavailableUserInterface");
                bool showNotificationsTab    = (DisplayMyNotifications && ModuleEntry.IsModuleLoaded(ModuleEntry.NOTIFICATIONS) && (!hideUnavailableUI || LicenseHelper.CheckFeature(URLHelper.GetCurrentDomain(), FeatureEnum.Notifications)));
                bool isWindowsAuthentication = RequestHelper.IsWindowsAuthentication();

                // Notification tab
                if (showNotificationsTab)
                {
                    arraySize++;
                }

                // Friends tab
                if (DisplayMyFriends && friendsEnabled)
                {
                    arraySize++;
                }

                // User password tab
                if (DisplayChangePassword && !currentUser.IsExternal && !isWindowsAuthentication)
                {
                    arraySize++;
                }

                // Subscriptions tab
                if (DisplayMySubscriptions)
                {
                    arraySize++;
                }

                // Memberships tab
                if (DisplayMyMemberships)
                {
                    arraySize++;
                }

                // Categories tab
                if (DisplayMyCategories)
                {
                    arraySize++;
                }

                // Ecommerce tabs
                if (DisplayMyCredits && userIsCustomer)
                {
                    arraySize++;
                }
                if (DisplayMyDetails && userIsCustomer)
                {
                    arraySize++;
                }
                if (DisplayMyAddresses && userIsCustomer)
                {
                    arraySize++;
                }
                if (DisplayMyOrders && userIsCustomer)
                {
                    arraySize++;
                }
                tabMenu.Tabs = new string[arraySize, 5];

                // Personal tab
                if (DisplayMyPersonalSettings)
                {
                    // Set new tab
                    tabName = personalTab;
                    activeTabs.Add(tabName);
                    tabMenu.Tabs[activeTabs.IndexOf(tabName), 0] = GetString("MyAccount.MyPersonalSettings");
                    tabMenu.Tabs[activeTabs.IndexOf(tabName), 2] = HTMLHelper.HTMLEncode(URLHelper.AddParameterToUrl(absoluteUri, ParameterName, personalTab));

                    if (currentUser != null)
                    {
                        selectedPage = tabName;
                    }
                }

                // These items can be displayed only for customer
                if (userIsCustomer && ModuleEntry.IsModuleLoaded(ModuleEntry.ECOMMERCE))
                {
                    if (DisplayMyDetails)
                    {
                        // Try to load the control dynamically (if available)
                        ucMyDetails = Page.LoadUserControl("~/CMSModules/Ecommerce/Controls/MyDetails/MyDetails.ascx") as CMSAdminControl;
                        if (ucMyDetails != null)
                        {
                            ucMyDetails.ID = "ucMyDetails";
                            plcOther.Controls.Add(ucMyDetails);

                            // Set new tab
                            tabName = detailsTab;
                            activeTabs.Add(tabName);
                            tabMenu.Tabs[activeTabs.IndexOf(tabName), 0] = GetString("MyAccount.MyDetails");
                            tabMenu.Tabs[activeTabs.IndexOf(tabName), 2] = HTMLHelper.HTMLEncode(URLHelper.AddParameterToUrl(absoluteUri, ParameterName, detailsTab));

                            if (selectedPage == string.Empty)
                            {
                                selectedPage = tabName;
                            }
                        }
                    }

                    if (DisplayMyAddresses)
                    {
                        // Try to load the control dynamically (if available)
                        ucMyAddresses = Page.LoadUserControl("~/CMSModules/Ecommerce/Controls/MyDetails/MyAddresses.ascx") as CMSAdminControl;
                        if (ucMyAddresses != null)
                        {
                            ucMyAddresses.ID = "ucMyAddresses";
                            plcOther.Controls.Add(ucMyAddresses);

                            // Set new tab
                            tabName = addressesTab;
                            activeTabs.Add(tabName);
                            tabMenu.Tabs[activeTabs.IndexOf(tabName), 0] = GetString("MyAccount.MyAddresses");
                            tabMenu.Tabs[activeTabs.IndexOf(tabName), 2] = HTMLHelper.HTMLEncode(URLHelper.AddParameterToUrl(absoluteUri, ParameterName, addressesTab));

                            if (selectedPage == string.Empty)
                            {
                                selectedPage = tabName;
                            }
                        }
                    }

                    if (DisplayMyOrders)
                    {
                        // Try to load the control dynamically (if available)
                        ucMyOrders = Page.LoadUserControl("~/CMSModules/Ecommerce/Controls/MyDetails/MyOrders.ascx") as CMSAdminControl;
                        if (ucMyOrders != null)
                        {
                            ucMyOrders.ID = "ucMyOrders";
                            plcOther.Controls.Add(ucMyOrders);

                            // Set new tab
                            tabName = ordersTab;
                            activeTabs.Add(tabName);
                            tabMenu.Tabs[activeTabs.IndexOf(tabName), 0] = GetString("MyAccount.MyOrders");
                            tabMenu.Tabs[activeTabs.IndexOf(tabName), 2] = HTMLHelper.HTMLEncode(URLHelper.AddParameterToUrl(absoluteUri, ParameterName, ordersTab));

                            if (selectedPage == string.Empty)
                            {
                                selectedPage = tabName;
                            }
                        }
                    }

                    if (DisplayMyCredits)
                    {
                        // Try to load the control dynamically (if available)
                        ucMyCredit = Page.LoadUserControl("~/CMSModules/Ecommerce/Controls/MyDetails/MyCredit.ascx") as CMSAdminControl;
                        if (ucMyCredit != null)
                        {
                            ucMyCredit.ID = "ucMyCredit";
                            plcOther.Controls.Add(ucMyCredit);

                            // Set new tab
                            tabName = creditTab;
                            activeTabs.Add(tabName);
                            tabMenu.Tabs[activeTabs.IndexOf(tabName), 0] = GetString("MyAccount.MyCredit");
                            tabMenu.Tabs[activeTabs.IndexOf(tabName), 2] = HTMLHelper.HTMLEncode(URLHelper.AddParameterToUrl(absoluteUri, ParameterName, creditTab));

                            if (selectedPage == string.Empty)
                            {
                                selectedPage = tabName;
                            }
                        }
                    }
                }

                if (DisplayChangePassword && !currentUser.IsExternal && !isWindowsAuthentication)
                {
                    // Set new tab
                    tabName = passwordTab;
                    activeTabs.Add(tabName);
                    tabMenu.Tabs[activeTabs.IndexOf(tabName), 0] = GetString("MyAccount.ChangePassword");
                    tabMenu.Tabs[activeTabs.IndexOf(tabName), 2] = HTMLHelper.HTMLEncode(URLHelper.AddParameterToUrl(absoluteUri, ParameterName, passwordTab));

                    if (selectedPage == string.Empty)
                    {
                        selectedPage = tabName;
                    }
                }

                if ((ucMyNotifications == null) && showNotificationsTab)
                {
                    // Try to load the control dynamically (if available)
                    ucMyNotifications = Page.LoadUserControl("~/CMSModules/Notifications/Controls/UserNotifications.ascx") as CMSAdminControl;
                    if (ucMyNotifications != null)
                    {
                        ucMyNotifications.ID = "ucMyNotifications";
                        plcOther.Controls.Add(ucMyNotifications);

                        // Set new tab
                        tabName = notificationsTab;
                        activeTabs.Add(tabName);
                        tabMenu.Tabs[activeTabs.IndexOf(tabName), 0] = GetString("MyAccount.MyNotifications");
                        tabMenu.Tabs[activeTabs.IndexOf(tabName), 2] = HTMLHelper.HTMLEncode(URLHelper.AddParameterToUrl(absoluteUri, ParameterName, notificationsTab));

                        if (selectedPage == string.Empty)
                        {
                            selectedPage = tabName;
                        }
                    }
                }

                if ((ucMyMessages == null) && DisplayMyMessages && ModuleEntry.IsModuleLoaded(ModuleEntry.MESSAGING))
                {
                    // Try to load the control dynamically (if available)
                    ucMyMessages = Page.LoadUserControl("~/CMSModules/Messaging/Controls/MyMessages.ascx") as CMSAdminControl;
                    if (ucMyMessages != null)
                    {
                        ucMyMessages.ID = "ucMyMessages";
                        plcOther.Controls.Add(ucMyMessages);

                        // Set new tab
                        tabName = messagesTab;
                        activeTabs.Add(tabName);
                        tabMenu.Tabs[activeTabs.IndexOf(tabName), 0] = GetString("MyAccount.MyMessages");
                        tabMenu.Tabs[activeTabs.IndexOf(tabName), 2] = HTMLHelper.HTMLEncode(URLHelper.AddParameterToUrl(absoluteUri, ParameterName, messagesTab));

                        if (selectedPage == string.Empty)
                        {
                            selectedPage = tabName;
                        }
                    }
                }

                if ((ucMyFriends == null) && DisplayMyFriends && ModuleEntry.IsModuleLoaded(ModuleEntry.COMMUNITY) && friendsEnabled)
                {
                    // Try to load the control dynamically (if available)
                    ucMyFriends = Page.LoadUserControl("~/CMSModules/Friends/Controls/MyFriends.ascx") as CMSAdminControl;
                    if (ucMyFriends != null)
                    {
                        ucMyFriends.ID = "ucMyFriends";
                        plcOther.Controls.Add(ucMyFriends);

                        // Set new tab
                        tabName = friendsTab;
                        activeTabs.Add(tabName);
                        tabMenu.Tabs[activeTabs.IndexOf(tabName), 0] = GetString("MyAccount.MyFriends");
                        tabMenu.Tabs[activeTabs.IndexOf(tabName), 2] = HTMLHelper.HTMLEncode(URLHelper.AddParameterToUrl(absoluteUri, ParameterName, friendsTab));

                        if (selectedPage == string.Empty)
                        {
                            selectedPage = tabName;
                        }
                    }
                }

                if ((ucMyAllSubscriptions == null) && DisplayMySubscriptions)
                {
                    // Try to load the control dynamically (if available)
                    ucMyAllSubscriptions = Page.LoadUserControl("~/CMSModules/Membership/Controls/Subscriptions.ascx") as CMSAdminControl;
                    if (ucMyAllSubscriptions != null)
                    {
                        // Set control
                        ucMyAllSubscriptions.Visible = false;

                        ucMyAllSubscriptions.SetValue("ShowBlogs", DisplayBlogs);
                        ucMyAllSubscriptions.SetValue("ShowMessageBoards", DisplayMessageBoards);
                        ucMyAllSubscriptions.SetValue("ShowNewsletters", DisplayNewsletters);
                        ucMyAllSubscriptions.SetValue("ShowForums", DisplayForums);
                        ucMyAllSubscriptions.SetValue("ShowReports", DisplayReports);
                        ucMyAllSubscriptions.SetValue("sendconfirmationemail", SendConfirmationEmails);

                        ucMyAllSubscriptions.ID = "ucMyAllSubscriptions";
                        plcOther.Controls.Add(ucMyAllSubscriptions);

                        // Set new tab
                        tabName = subscriptionsTab;
                        activeTabs.Add(tabName);
                        tabMenu.Tabs[activeTabs.IndexOf(tabName), 0] = GetString("MyAccount.MyAllSubscriptions");
                        tabMenu.Tabs[activeTabs.IndexOf(tabName), 2] = HTMLHelper.HTMLEncode(URLHelper.AddParameterToUrl(absoluteUri, ParameterName, subscriptionsTab));

                        if (selectedPage == string.Empty)
                        {
                            selectedPage = tabName;
                        }
                    }
                }

                // My memberships
                if ((ucMyMemberships == null) && DisplayMyMemberships)
                {
                    // Try to load the control dynamically
                    ucMyMemberships = Page.LoadUserControl("~/CMSModules/Membership/Controls/MyMemberships.ascx") as CMSAdminControl;

                    if (ucMyMemberships != null)
                    {
                        ucMyMemberships.SetValue("UserID", currentUser.UserID);

                        if (!String.IsNullOrEmpty(MembershipsPagePath))
                        {
                            ucMyMemberships.SetValue("BuyMembershipURL", CMSContext.GetUrl(MembershipsPagePath));
                        }

                        plcOther.Controls.Add(ucMyMemberships);

                        // Set new tab
                        tabName = membershipsTab;
                        activeTabs.Add(tabName);
                        tabMenu.Tabs[activeTabs.IndexOf(tabName), 0] = GetString("myaccount.mymemberships");
                        tabMenu.Tabs[activeTabs.IndexOf(tabName), 2] = HTMLHelper.HTMLEncode(URLHelper.AddParameterToUrl(absoluteUri, ParameterName, membershipsTab));

                        if (selectedPage == String.Empty)
                        {
                            selectedPage = tabName;
                        }
                    }
                }

                if ((ucMyCategories == null) && DisplayMyCategories)
                {
                    // Try to load the control dynamically (if available)
                    ucMyCategories = Page.LoadUserControl("~/CMSModules/Categories/Controls/Categories.ascx") as CMSAdminControl;
                    if (ucMyCategories != null)
                    {
                        ucMyCategories.Visible = false;

                        ucMyCategories.SetValue("DisplaySiteCategories", false);
                        ucMyCategories.SetValue("DisplaySiteSelector", false);

                        ucMyCategories.ID = "ucMyCategories";
                        plcOther.Controls.Add(ucMyCategories);

                        // Set new tab
                        tabName = categoriesTab;
                        activeTabs.Add(tabName);
                        tabMenu.Tabs[activeTabs.IndexOf(tabName), 0] = GetString("MyAccount.MyCategories");
                        tabMenu.Tabs[activeTabs.IndexOf(tabName), 2] = HTMLHelper.HTMLEncode(URLHelper.AddParameterToUrl(absoluteUri, ParameterName, categoriesTab));

                        if (selectedPage == string.Empty)
                        {
                            selectedPage = tabName;
                        }
                    }
                }

                // Set CSS class
                pnlBody.CssClass = CssClass;

                // Get page URL
                page = QueryHelper.GetString(ParameterName, selectedPage);

                // Set controls visibility
                ucChangePassword.Visible        = false;
                ucChangePassword.StopProcessing = true;

                if (ucMyAddresses != null)
                {
                    ucMyAddresses.Visible        = false;
                    ucMyAddresses.StopProcessing = true;
                }

                if (ucMyOrders != null)
                {
                    ucMyOrders.Visible        = false;
                    ucMyOrders.StopProcessing = true;
                }

                if (ucMyDetails != null)
                {
                    ucMyDetails.Visible        = false;
                    ucMyDetails.StopProcessing = true;
                }

                if (ucMyCredit != null)
                {
                    ucMyCredit.Visible        = false;
                    ucMyCredit.StopProcessing = true;
                }

                if (ucMyAllSubscriptions != null)
                {
                    ucMyAllSubscriptions.Visible        = false;
                    ucMyAllSubscriptions.StopProcessing = true;
                    ucMyAllSubscriptions.SetValue("CacheMinutes", CacheMinutes);
                }

                if (ucMyNotifications != null)
                {
                    ucMyNotifications.Visible        = false;
                    ucMyNotifications.StopProcessing = true;
                }

                if (ucMyMessages != null)
                {
                    ucMyMessages.Visible        = false;
                    ucMyMessages.StopProcessing = true;
                }

                if (ucMyFriends != null)
                {
                    ucMyFriends.Visible        = false;
                    ucMyFriends.StopProcessing = true;
                }

                if (ucMyMemberships != null)
                {
                    ucMyMemberships.Visible        = false;
                    ucMyMemberships.StopProcessing = true;
                }

                if (ucMyCategories != null)
                {
                    ucMyCategories.Visible        = false;
                    ucMyCategories.StopProcessing = true;
                }

                tabMenu.SelectedTab = activeTabs.IndexOf(page);

                // Select current page
                switch (page)
                {
                case personalTab:
                    if (myProfile != null)
                    {
                        // Get alternative form info
                        AlternativeFormInfo afi = AlternativeFormInfoProvider.GetAlternativeFormInfo(AlternativeFormName);
                        if (afi != null)
                        {
                            myProfile.StopProcessing      = false;
                            myProfile.Visible             = true;
                            myProfile.AllowEditVisibility = AllowEditVisibility;
                            myProfile.AlternativeFormName = AlternativeFormName;
                        }
                        else
                        {
                            lblError.Text     = String.Format(GetString("altform.formdoesntexists"), AlternativeFormName);
                            lblError.Visible  = true;
                            myProfile.Visible = false;
                        }
                    }
                    break;

                // My details tab
                case detailsTab:
                    if (ucMyDetails != null)
                    {
                        ucMyDetails.Visible        = true;
                        ucMyDetails.StopProcessing = false;
                        ucMyDetails.SetValue("Customer", customer);
                    }
                    break;

                // My addresses tab
                case addressesTab:
                    if (ucMyAddresses != null)
                    {
                        ucMyAddresses.Visible        = true;
                        ucMyAddresses.StopProcessing = false;
                        ucMyAddresses.SetValue("CustomerId", customerId);
                    }
                    break;

                // My orders tab
                case ordersTab:
                    if (ucMyOrders != null)
                    {
                        ucMyOrders.Visible        = true;
                        ucMyOrders.StopProcessing = false;
                        ucMyOrders.SetValue("CustomerId", customerId);
                        ucMyOrders.SetValue("ShowOrderTrackingNumber", ShowOrderTrackingNumber);
                    }
                    break;

                // My credit tab
                case creditTab:
                    if (ucMyCredit != null)
                    {
                        ucMyCredit.Visible        = true;
                        ucMyCredit.StopProcessing = false;
                        ucMyCredit.SetValue("CustomerId", customerId);
                    }
                    break;

                // Password tab
                case passwordTab:
                    ucChangePassword.Visible            = true;
                    ucChangePassword.StopProcessing     = false;
                    ucChangePassword.AllowEmptyPassword = AllowEmptyPassword;
                    break;

                // Notification tab
                case notificationsTab:
                    if (ucMyNotifications != null)
                    {
                        ucMyNotifications.Visible        = true;
                        ucMyNotifications.StopProcessing = false;
                        ucMyNotifications.SetValue("UserId", currentUser.UserID);
                        ucMyNotifications.SetValue("UnigridImageDirectory", UnigridImageDirectory);
                    }
                    break;

                // My messages tab
                case messagesTab:
                    if (ucMyMessages != null)
                    {
                        ucMyMessages.Visible        = true;
                        ucMyMessages.StopProcessing = false;
                    }
                    break;

                // My friends tab
                case friendsTab:
                    if (ucMyFriends != null)
                    {
                        ucMyFriends.Visible        = true;
                        ucMyFriends.StopProcessing = false;
                        ucMyFriends.SetValue("UserID", currentUser.UserID);
                    }
                    break;

                // My subscriptions tab
                case subscriptionsTab:
                    if (ucMyAllSubscriptions != null)
                    {
                        ucMyAllSubscriptions.Visible        = true;
                        ucMyAllSubscriptions.StopProcessing = false;

                        ucMyAllSubscriptions.SetValue("userid", currentUser.UserID);
                        ucMyAllSubscriptions.SetValue("siteid", CMSContext.CurrentSiteID);
                    }
                    break;

                // My memberships tab
                case membershipsTab:
                    if (ucMyMemberships != null)
                    {
                        ucMyMemberships.Visible        = true;
                        ucMyMemberships.StopProcessing = false;
                    }
                    break;

                // My categories tab
                case categoriesTab:
                    if (ucMyCategories != null)
                    {
                        ucMyCategories.Visible        = true;
                        ucMyCategories.StopProcessing = false;
                    }
                    break;
                }
            }
            else
            {
                // Hide control if current user is not authenticated
                Visible = false;
            }
        }
    }
Пример #14
0
    /// <summary>
    /// OK click handler (Proceed registration).
    /// </summary>
    protected void btnOK_Click(object sender, EventArgs e)
    {
        if ((this.PageManager.ViewMode == ViewModeEnum.Design) || (this.HideOnCurrentPage) || (!this.IsVisible))
        {
            // Do not process
        }
        else
        {
            String siteName = CMSContext.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"

            // Check whether user with same email does not exist
            UserInfo ui     = UserInfoProvider.GetUserInfo(txtEmail.Text);
            SiteInfo si     = CMSContext.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 ((this.PasswordMinLength > 0) && (passStrength.Text.Length < this.PasswordMinLength))
            {
                lblError.Visible = true;
                lblError.Text    = String.Format(GetString("Webparts_Membership_RegistrationForm.PasswordMinLength"), this.PasswordMinLength.ToString());
                return;
            }

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

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

            #endregion


            #region "Captcha"

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

            #endregion


            #region "User properties"

            ui = new UserInfo();
            ui.PreferredCultureCode = "";
            ui.Email      = txtEmail.Text.Trim();
            ui.FirstName  = txtFirstName.Text.Trim();
            ui.FullName   = txtFirstName.Text.Trim() + " " + txtLastName.Text.Trim();
            ui.LastName   = txtLastName.Text.Trim();
            ui.MiddleName = "";

            // 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  = this.EnableUserAfterRegistration;
            ui.IsEditor = false;
            ui.IsGlobalAdministrator = false;
            ui.UserURLReferrer       = CMSContext.CurrentUser.URLReferrer;
            ui.UserCampaign          = CMSContext.Campaign;

            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 = SettingsKeyProvider.GetBoolValue(siteName + ".CMSRegistrationEmailConfirmation");
            bool requiresAdminApprove = false;

            if (!requiresConfirmation)
            {
                // If confirmation is not required check whether administration approval is reqiures
                if ((requiresAdminApprove = SettingsKeyProvider.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(this.StartingAliasPath))
            {
                ui.UserStartingAliasPath = CMSContext.ResolveCurrentPath(this.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"

            // Check limitations for Global administrator
            if (ui.IsGlobalAdministrator)
            {
                if (!UserInfoProvider.LicenseVersionCheck(URLHelper.GetCurrentDomain(), FeatureEnum.GlobalAdmininistrators, VersionActionEnum.Insert, false))
                {
                    lblError.Visible = true;
                    lblError.Text    = GetString("License.MaxItemsReachedGlobal");
                    return;
                }
            }

            // Check limitations for editors
            if (ui.IsEditor)
            {
                if (!UserInfoProvider.LicenseVersionCheck(URLHelper.GetCurrentDomain(), FeatureEnum.Editors, VersionActionEnum.Insert, false))
                {
                    lblError.Visible = true;
                    lblError.Text    = GetString("License.MaxItemsReachedEditor");
                    return;
                }
            }

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

            #endregion


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

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

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

            bool              error    = false;
            EventLogProvider  ev       = new EventLogProvider();
            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 (this.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)
            {
                // Rretrieve 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]     = (this.ApprovalPage != String.Empty) ? URLHelper.GetAbsoluteUrl(this.ApprovalPage) : URLHelper.GetAbsoluteUrl("~/CMSPages/Dialogs/UserRegistration.aspx");
                replacements[0, 1]    += "?userguid=" + ui.UserGUID + (contactId > 0?"&contactid=" + contactId.ToString():String.Empty);
                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
                ContextResolver resolver = CMSContext.CurrentResolver;
                resolver.SourceParameters     = replacements;
                resolver.EncodeResolvedValues = true;

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

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

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

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

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

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

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

            #endregion


            #region "Administrator notification email"

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

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

                if (mEmailTemplate == null)
                {
                    // Log missing e-mail template
                    ev.LogEvent("E", DateTime.Now, "RegistrationForm", "GetEmailTemplate", HTTPHelper.GetAbsoluteUri());
                }
                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;

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

                    EmailMessage message = new EmailMessage();

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

                    resolver.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
                        MetaFileInfoProvider.ResolveMetaFileImages(message, mEmailTemplate.TemplateID, EmailObjectType.EMAILTEMPLATE, MetaFileInfoProvider.OBJECT_CATEGORY_TEMPLATE);
                        EmailSender.SendEmail(siteName, message);
                    }
                    catch
                    {
                        ev.LogEvent("E", DateTime.Now, "Membership", "RegistrationEmail", CMSContext.CurrentSite.SiteID);
                    }
                }
            }

            #endregion


            #region "Web analytics"

            // Track successful registration conversion
            if (this.TrackConversionName != String.Empty)
            {
                if (AnalyticsHelper.AnalyticsEnabled(siteName) && AnalyticsHelper.TrackConversionsEnabled(siteName) && !AnalyticsHelper.IsIPExcluded(siteName, HTTPHelper.UserHostAddress))
                {
                    // Log conversion
                    HitLogProvider.LogConversions(siteName, CMSContext.PreferredCultureCode, this.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)
            {
                if (ActivitySettingsHelper.ActivitiesEnabledAndModuleLoaded(siteName))
                {
                    int contactId = 0;
                    // Log registration activity
                    if (ActivitySettingsHelper.UserRegistrationEnabled(siteName))
                    {
                        if (ActivitySettingsHelper.ActivitiesEnabledForThisUser(ui))
                        {
                            contactId = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui);
                            ActivityLogProvider.LogRegistrationActivity(contactId,
                                                                        ui, URLHelper.CurrentRelativePath, CMSContext.CurrentDocument.DocumentID, siteName, CMSContext.Campaign, CMSContext.CurrentDocument.DocumentCulture);
                        }
                    }

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

            #endregion

            #region "Roles & authentication"

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

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

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

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

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

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

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

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

                    // Check that url is relative path or hash is ok
                    if (url.StartsWith("~") || url.StartsWith("/") || 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;
        }
    }
    /// <summary>
    /// Setup media dialog from selected item.
    /// </summary>
    /// <param name="selectionTable">Hash table from selected item</param>
    /// <param name="anchorsList">List of anchors from document</param>
    /// <param name="idsList">List of ids from document</param>
    private void SelectMediaDialog(IDictionary selectionTable, ICollection anchorsList, ICollection idsList)
    {
        string insertHeaderLocation = BaseFilePath + "Header.aspx" + RequestContext.CurrentQueryString;

        if (selectionTable.Count > 0)
        {
            string siteName = null;
            string url      = null;
            // If link dialog use only link url
            if (RequestContext.CurrentQueryString.ToLowerCSafe().Contains("link=1"))
            {
                if (selectionTable[DialogParameters.LINK_URL] != null)
                {
                    url = selectionTable[DialogParameters.LINK_URL].ToString();
                    if ((selectionTable[DialogParameters.LINK_PROTOCOL] != null) && (selectionTable[DialogParameters.LINK_PROTOCOL].ToString() != "other"))
                    {
                        // Add protocol only if not already presents
                        if (!url.StartsWithCSafe(selectionTable[DialogParameters.LINK_PROTOCOL].ToString()))
                        {
                            url = selectionTable[DialogParameters.LINK_PROTOCOL] + url;
                        }
                    }
                }
                else if (selectionTable[DialogParameters.URL_URL] != null)
                {
                    url = selectionTable[DialogParameters.URL_URL].ToString();
                }
            }
            else
            {
                // Get url from selection table
                if (selectionTable[DialogParameters.IMG_URL] != null)
                {
                    url = selectionTable[DialogParameters.IMG_URL].ToString();
                }
                else if (selectionTable[DialogParameters.AV_URL] != null)
                {
                    url = selectionTable[DialogParameters.AV_URL].ToString();
                }
                else if (selectionTable[DialogParameters.LINK_URL] != null)
                {
                    url = selectionTable[DialogParameters.LINK_URL].ToString();
                }
                else if (selectionTable[DialogParameters.URL_URL] != null)
                {
                    url      = selectionTable[DialogParameters.URL_URL].ToString();
                    siteName = (selectionTable[DialogParameters.URL_SITENAME] != null ? selectionTable[DialogParameters.URL_SITENAME].ToString() : null);
                }
            }
            string query = URLHelper.RemoveUrlParameter(RequestContext.CurrentQueryString, "hash");

            // Get the data for media source
            MediaSource ms = CMSDialogHelper.GetMediaData(url, siteName);
            if (ms != null)
            {
                SessionHelper.SetValue("MediaSource", ms);

                // Preselect the tab
                if (!selectionTable.Contains(DialogParameters.EMAIL_TO) || !selectionTable.Contains(DialogParameters.ANCHOR_NAME))
                {
                    switch (ms.SourceType)
                    {
                    case MediaSourceEnum.DocumentAttachments:
                    case MediaSourceEnum.MetaFile:
                        query = URLHelper.AddUrlParameter(query, "tab", "attachments");
                        break;

                    case MediaSourceEnum.Content:
                        query = URLHelper.AddUrlParameter(query, "tab", "content");
                        break;

                    case MediaSourceEnum.MediaLibraries:
                        query = URLHelper.AddUrlParameter(query, "tab", "libraries");
                        break;

                    default:
                        query = URLHelper.AddUrlParameter(query, "tab", "web");
                        break;
                    }
                }

                // Update old format url
                if ((selectionTable.Contains(DialogParameters.URL_OLDFORMAT)) && (selectionTable.Contains(DialogParameters.URL_GUID)))
                {
                    if (String.IsNullOrEmpty(siteName))
                    {
                        siteName = SiteContext.CurrentSiteName;
                    }
                    string outUrl = ModuleCommands.MediaLibraryGetMediaFileUrl(selectionTable[DialogParameters.URL_GUID].ToString(), siteName);
                    if (!String.IsNullOrEmpty(outUrl))
                    {
                        selectionTable[DialogParameters.URL_URL] = outUrl;
                    }
                }

                // Set extension if not exist in selection table
                if ((selectionTable[DialogParameters.URL_EXT] == null) || ((selectionTable[DialogParameters.URL_EXT] != null) && (String.IsNullOrEmpty(selectionTable[DialogParameters.URL_EXT].ToString()))))
                {
                    selectionTable[DialogParameters.URL_EXT] = ms.Extension;
                }

                // Update selection table if only URL presents
                if (selectionTable.Contains(DialogParameters.URL_URL))
                {
                    switch (ms.MediaType)
                    {
                    case MediaTypeEnum.Image:
                        // Image
                        selectionTable[DialogParameters.IMG_URL]    = UrlResolver.ResolveUrl(selectionTable[DialogParameters.URL_URL].ToString());
                        selectionTable[DialogParameters.IMG_WIDTH]  = selectionTable[DialogParameters.URL_WIDTH];
                        selectionTable[DialogParameters.IMG_HEIGHT] = selectionTable[DialogParameters.URL_HEIGHT];
                        break;

                    case MediaTypeEnum.AudioVideo:
                        // Media
                        selectionTable[DialogParameters.AV_URL]    = UrlResolver.ResolveUrl(selectionTable[DialogParameters.URL_URL].ToString());
                        selectionTable[DialogParameters.AV_WIDTH]  = selectionTable[DialogParameters.URL_WIDTH];
                        selectionTable[DialogParameters.AV_HEIGHT] = selectionTable[DialogParameters.URL_HEIGHT];
                        selectionTable[DialogParameters.AV_EXT]    = ms.Extension;
                        break;
                    }

                    if ((ms.SourceType == MediaSourceEnum.Content) && (ms.FileName != null) && (OutputFormat == OutputFormatEnum.NodeGUID))
                    {
                        string fileUrl = AttachmentURLProvider.GetPermanentAttachmentUrl(ms.NodeGuid, ValidationHelper.GetSafeFileName(ms.FileName, siteName));
                        selectionTable[DialogParameters.URL_URL] = UrlResolver.ResolveUrl(fileUrl);
                    }
                    else if (OutputFormat != OutputFormatEnum.URL)
                    {
                        selectionTable[DialogParameters.URL_URL] = UrlResolver.ResolveUrl(selectionTable[DialogParameters.URL_URL].ToString());
                    }

                    selectionTable[DialogParameters.FILE_NAME] = ms.FileName;
                    selectionTable[DialogParameters.FILE_SIZE] = ms.FileSize;
                }

                // Add original size into table
                selectionTable[DialogParameters.IMG_ORIGINALWIDTH]  = ms.MediaWidth;
                selectionTable[DialogParameters.IMG_ORIGINALHEIGHT] = ms.MediaHeight;
            }
            else
            {
                if (selectionTable.Contains(DialogParameters.EMAIL_TO))
                {
                    query = URLHelper.AddUrlParameter(query, "tab", "email");
                }
                if (selectionTable.Contains(DialogParameters.ANCHOR_NAME))
                {
                    query = URLHelper.AddUrlParameter(query, "tab", "anchor");
                }
            }

            query = URLHelper.AddUrlParameter(query, "hash", QueryHelper.GetHash(query));
            insertHeaderLocation = BaseFilePath + "Header.aspx" + query;
        }


        // Set selected item into session
        SessionHelper.SetValue("DialogParameters", selectionTable);

        if ((anchorsList != null) && (anchorsList.Count > 0))
        {
            SessionHelper.SetValue("Anchors", anchorsList);
        }
        if ((idsList != null) && (idsList.Count > 0))
        {
            SessionHelper.SetValue("Ids", idsList);
        }

        if (((selectionTable[DialogParameters.LINK_TEXT] != null) &&
             (selectionTable[DialogParameters.LINK_TEXT].ToString() == "##LINKTEXT##")) ||
            ((selectionTable[DialogParameters.EMAIL_LINKTEXT] != null) &&
             (selectionTable[DialogParameters.EMAIL_LINKTEXT].ToString() == "##LINKTEXT##")) ||
            ((selectionTable[DialogParameters.ANCHOR_LINKTEXT] != null) &&
             (selectionTable[DialogParameters.ANCHOR_LINKTEXT].ToString() == "##LINKTEXT##")))
        {
            SessionHelper.SetValue("HideLinkText", true);
        }

        ltlScript.Text = ScriptHelper.GetScript("if (window.parent.frames['insertHeader']) { window.parent.frames['insertHeader'].location= \"" + ResolveUrl(insertHeaderLocation) + "\";} ");
    }
    /// <summary>
    /// Load event.
    /// </summary>
    protected void Page_Load(object sender, EventArgs e)
    {
        InitializeForm();

        // Score selector is not null only if DisplayScore is true
        if (mScoreSelector != null)
        {
            if (IsOnlineUsersUI() && DisplayContacts)
            {
                plcScore.Visible = true;

                int siteId = QueryHelper.GetInteger("siteid", 0);
                mScoreSelector.Enabled = (siteId > 0) || ((siteId == 0) && (siteSelector.SiteID > 0));

                if (siteId == 0)
                {
                    mScoreSelector.SetValue("SiteID", siteSelector.SiteID);
                }
            }
            else
            {
                // Disable loading not visible control
                mScoreSelector.StopProcessing = true;
            }
        }

        // Show correct filter panel
        SetCorrectFilterMode();

        // Set reset link button
        UniGrid grid = FilteredControl as UniGrid;

        if (grid != null && grid.RememberState)
        {
            if (mIsAdvancedMode)
            {
                btnAdvancedReset.Click += btnReset_Click;
            }
            else
            {
                btnReset.Click += btnReset_Click;
            }
        }
        else
        {
            if (mIsAdvancedMode)
            {
                btnAdvancedReset.Visible = false;
            }
            else
            {
                btnReset.Visible = false;
            }
        }

        // Set privilege level filter
        if (ShowPrivilegeLevelFilter(grid))
        {
            plcPrivilegeLevel.Visible = true;
            mShowPrivilegeFilter      = true;
        }
        else
        {
            mShowPrivilegeFilter = false;
        }

        // Show group filter only if enabled
        if (SiteID > 0)
        {
            SiteInfo si = SiteInfoProvider.GetSiteInfo(SiteID);
            if ((si != null) && mIsAdvancedMode)
            {
                mShowGroups = ModuleCommands.CommunitySiteHasGroup(si.SiteID);
            }
        }

        // Setup role selector
        selectNotInRole.SiteID = SiteID;
        selectRoleElem.SiteID  = SiteID;
        selectRoleElem.CurrentSelector.ResourcePrefix  = "addroles";
        selectNotInRole.CurrentSelector.ResourcePrefix = "addroles";
        selectRoleElem.UseFriendlyMode  = true;
        selectNotInRole.UseFriendlyMode = true;

        // Setup groups selectors
        plcGroups.Visible = mShowGroups;
        if (mSelectInGroups != null)
        {
            mSelectInGroups.StopProcessing       = !mShowGroups;
            mSelectInGroups.FormControlParameter = SiteID;
        }

        if (mSelectNotInGroups != null)
        {
            mSelectNotInGroups.StopProcessing       = !mShowGroups;
            mSelectNotInGroups.FormControlParameter = SiteID;
        }

        if (SessionInsteadOfUser && DisplayGuestsByDefault)
        {
            plcNickName.Visible = false;
            plcUserName.Visible = false;
        }

        if (QueryHelper.GetBoolean("isonlinemarketing", false))
        {
            // Set disabled modules info (only on On-line marketing tab)
            ucDisabledModule.TestSettingKeys = "CMSSessionUseDBRepository;CMSEnableOnlineMarketing";
            ucDisabledModule.Visible         = true;
        }
    }
    /// <summary>
    /// OnLoad override - check wheter filter is set.
    /// </summary>
    protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);

        // Hide default site filter label
        siteFilter.ShowLabel = false;
        siteFilter.Selector.OnSelectionChanged += Filter_Changed;

        // Check if site filter should be displayed
        if (ShowSiteFilter)
        {
            lblSite.ResourceString = "general.site";
            lblSite.DisplayColon   = true;
        }
        else
        {
            plcSite.Visible = false;
        }

        // Check if group filter should be displayed
        if (GroupID > 0)
        {
            // Initialize DDL
            if (!RequestHelper.IsPostBack())
            {
                string          groupName = String.Empty;
                GeneralizedInfo gi        = ModuleCommands.CommunityGetGroupInfo(GroupID);
                if (gi != null)
                {
                    groupName = ValidationHelper.GetString(gi.GetValue("GroupDisplayName"), "");
                }

                // Initialize DDL using obtained group name
                switch (siteFilter.FilterMode)
                {
                case "user":
                    drpGroup.Items.Add(new ListItem(ResHelper.GetString("sitegroupselector.generalusers"), "0"));
                    if (!String.IsNullOrEmpty(groupName))
                    {
                        drpGroup.Items.Add(new ListItem(groupName, GroupID.ToString()));
                    }
                    break;

                case "role":
                    drpGroup.Items.Add(new ListItem(ResHelper.GetString("sitegroupselector.generalroles"), "0"));
                    if (!String.IsNullOrEmpty(groupName))
                    {
                        drpGroup.Items.Add(new ListItem(groupName, GroupID.ToString()));
                    }
                    break;
                }
            }

            // Initialize group label
            lblGroup.Visible        = true;
            lblGroup.ResourceString = "general.group";
            lblGroup.DisplayColon   = true;
        }
        else
        {
            plcGroup.Visible = false;
        }

        // Generate current where condition
        if (ShowSiteFilter)
        {
            WhereCondition = SqlHelper.AddWhereCondition(siteFilter.WhereCondition, GenerateWhereCondition(SelectedGroupID));
        }
        else
        {
            WhereCondition = GenerateWhereCondition(SelectedGroupID);
        }
    }
    /// <summary>
    /// Initializes the control properties.
    /// </summary>
    protected void SetupControl()
    {
        if (StopProcessing)
        {
            // Do nothing
        }
        else
        {
            if (!String.IsNullOrEmpty(TransformationName))
            {
                repMostActiveThread.ItemTemplate           = TransformationHelper.LoadTransformation(this, TransformationName);
                repMostActiveThread.HideControlForZeroRows = HideControlForZeroRows;
                repMostActiveThread.ZeroRowsText           = ZeroRowsText;

                // Set data source groupid according to group name
                if (!String.IsNullOrEmpty(GroupName))
                {
                    if (GroupName == PredefinedObjectType.COMMUNITY_CURRENT_GROUP)
                    {
                        forumDataSource.GroupID = ModuleCommands.CommunityGetCurrentGroupID();
                    }
                    else
                    {
                        GeneralizedInfo gi = ModuleCommands.CommunityGetGroupInfoByName(GroupName, SiteName);
                        if (gi != null)
                        {
                            forumDataSource.GroupID = ValidationHelper.GetInteger(gi.GetValue("GroupID"), 0);
                        }
                        else
                        {
                            forumDataSource.StopProcessing = true;
                        }
                    }
                }

                if (!forumDataSource.StopProcessing)
                {
                    forumDataSource.TopN               = SelectTopN;
                    forumDataSource.OrderBy            = "PostThreadPosts DESC";
                    forumDataSource.CacheItemName      = CacheItemName;
                    forumDataSource.CacheDependencies  = CacheDependencies;
                    forumDataSource.CacheMinutes       = CacheMinutes;
                    forumDataSource.SelectOnlyApproved = false;
                    forumDataSource.SiteName           = SiteName;
                    forumDataSource.ShowGroupPosts     = ShowGroupPosts && String.IsNullOrEmpty(ForumGroups);
                    forumDataSource.SelectedColumns    = Columns;

                    #region "Complete where condition"

                    string where = "";

                    // Get groups part of where condition
                    string[] groups = ForumGroups.Split(';');
                    foreach (string group in groups)
                    {
                        if (group != "")
                        {
                            if (where != "")
                            {
                                where += " OR ";
                            }
                            where += "(GroupName = N'" + SqlHelper.GetSafeQueryString(group, false) + "')";
                        }
                    }
                    where = "(" + (where == "" ? "(GroupName NOT LIKE 'AdHoc%')" : "(" + where + ")") + " AND (PostLevel = 0))";

                    // Append where condition and set PostLevel to 0 (only threads are needed)
                    // and filter out AdHoc forums
                    if (!String.IsNullOrEmpty(WhereCondition))
                    {
                        where += " AND (" + WhereCondition + ")";
                    }

                    #endregion


                    forumDataSource.WhereCondition        = where;
                    forumDataSource.CheckPermissions      = true;
                    repMostActiveThread.DataSourceControl = forumDataSource;
                    repMostActiveThread.DataBind();
                }
            }
        }
    }
Пример #19
0
    /// <summary>
    /// Init event handler.
    /// </summary>
    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);

        // Load settings
        if (!string.IsNullOrEmpty(Request.Form[hdnIsNewWebPart.UniqueID]))
        {
            IsNewWebPart = ValidationHelper.GetBoolean(Request.Form[hdnIsNewWebPart.UniqueID], false);
        }
        if (!string.IsNullOrEmpty(Request.Form[hdnInstanceGUID.UniqueID]))
        {
            InstanceGUID = ValidationHelper.GetGuid(Request.Form[hdnInstanceGUID.UniqueID], Guid.Empty);
        }

        // Try to find the web part variant in the database and set its VariantID
        if (IsNewVariant)
        {
            Hashtable properties = WindowHelper.GetItem("variantProperties") as Hashtable;
            if (properties != null)
            {
                // Get the variant code name from the WindowHelper
                string variantName = ValidationHelper.GetString(properties["codename"], string.Empty);

                // Check if the variant exists in the database
                int variantIdFromDB = 0;
                if (VariantMode == VariantModeEnum.MVT)
                {
                    variantIdFromDB = ModuleCommands.OnlineMarketingGetMVTVariantId(PageTemplateId, variantName);
                }
                else if (VariantMode == VariantModeEnum.ContentPersonalization)
                {
                    variantIdFromDB = ModuleCommands.OnlineMarketingGetContentPersonalizationVariantId(PageTemplateId, variantName);
                }

                // Set the variant id from the database
                if (variantIdFromDB > 0)
                {
                    VariantID    = variantIdFromDB;
                    IsNewVariant = false;
                }
            }
        }

        if (!String.IsNullOrEmpty(WebpartId))
        {
            // Get the page info
            pi = CMSWebPartPropertiesPage.GetPageInfo(this.AliasPath, this.PageTemplateId);
            if (pi != null)
            {
                // Get template
                pti = pi.PageTemplateInfo;

                // Get template instance
                templateInstance = pti.TemplateInstance;

                // Parent webpart
                WebPartInfo parentWpi = null;

                //Before FormInfo
                FormInfo beforeFI = null;

                //After FormInfo
                FormInfo afterFI = null;

                // Webpart form info
                FormInfo fi = null;

                if (!IsNewWebPart)
                {
                    // Standard zone
                    webPartInstance = pti.GetWebPart(InstanceGUID, WebpartId);

                    // If the web part not found, try to find it among the MVT/CP variants
                    if (webPartInstance == null)
                    {
                        // MVT/CP variant
                        templateInstance.LoadVariants(false, VariantModeEnum.None);
                        webPartInstance = templateInstance.GetWebPart(InstanceGUID, true);

                        // Set the VariantMode according to the selected web part/zone variant
                        if ((webPartInstance != null) && (webPartInstance.ParentZone != null))
                        {
                            VariantMode = (webPartInstance.VariantMode != VariantModeEnum.None) ? webPartInstance.VariantMode : webPartInstance.ParentZone.VariantMode;
                        }
                        else
                        {
                            VariantMode = VariantModeEnum.None;
                        }
                    }
                    else
                    {
                        // Ensure that the ZoneVarianID is not set when the web part was found in a regural zone.
                        ZoneVariantID = 0;
                    }

                    if ((VariantID > 0) && (webPartInstance != null) && (webPartInstance.PartInstanceVariants != null))
                    {
                        // Check OnlineMarketing permissions.
                        if (CheckPermissions("Read"))
                        {
                            webPartInstance = webPartInstance.FindVariant(VariantID);
                        }
                        else
                        {
                            // Not authorised for OnlineMarketing - Manage.
                            RedirectToInformation(String.Format(GetString("general.permissionresource"), "Read", (VariantMode == VariantModeEnum.ContentPersonalization) ? "CMS.ContentPersonalization" : "CMS.MVTest"));
                        }
                    }

                    if (webPartInstance == null)
                    {
                        lblInfo.Text        = GetString("WebPartProperties.WebPartNotFound");
                        pnlFormArea.Visible = false;
                        return;
                    }

                    wpi       = WebPartInfoProvider.GetWebPartInfo(webPartInstance.WebPartType);
                    form.Mode = FormModeEnum.Update;
                }
                // Webpart instance hasn't created yet
                else
                {
                    wpi       = WebPartInfoProvider.GetWebPartInfo(ValidationHelper.GetInteger(WebpartId, 0));
                    form.Mode = FormModeEnum.Insert;
                }

                // Load parent
                if (wpi != null)
                {
                    if (wpi.WebPartParentID > 0)
                    {
                        parentWpi = WebPartInfoProvider.GetWebPartInfo(wpi.WebPartParentID);
                    }
                }

                // Get the form definition
                string wpProperties = "<form></form>";
                if (wpi != null)
                {
                    wpProperties = wpi.WebPartProperties;

                    // Use parent webpart if is defined
                    if (parentWpi != null)
                    {
                        wpProperties = parentWpi.WebPartProperties;
                    }

                    // Get before FormInfo
                    if (BeforeFormDefinition == null)
                    {
                        beforeFI = PortalHelper.GetPositionFormInfo((WebPartTypeEnum)wpi.WebPartType, PropertiesPosition.Before);
                    }
                    else
                    {
                        beforeFI = new FormInfo(BeforeFormDefinition);
                    }

                    // Get after FormInfo
                    if (AfterFormDefinition == null)
                    {
                        afterFI = PortalHelper.GetPositionFormInfo((WebPartTypeEnum)wpi.WebPartType, PropertiesPosition.After);
                    }
                    else
                    {
                        afterFI = new FormInfo(AfterFormDefinition);
                    }
                }

                // Add 'General' category at the beginning if no one is specified
                if (!string.IsNullOrEmpty(wpProperties) && (!wpProperties.StartsWith("<form><category", StringComparison.InvariantCultureIgnoreCase)))
                {
                    wpProperties = wpProperties.Insert(6, "<category name=\"" + GetString("general.general") + "\" />");
                }

                // Get merged web part FormInfo
                fi = FormHelper.GetWebPartFormInfo(wpi.WebPartName, wpProperties, beforeFI, afterFI, true);

                // Get datarow with required columns
                DataRow dr = fi.GetDataRow();

                if (IsNewWebPart)
                {
                    // Load default properties values
                    fi.LoadDefaultValues(dr);

                    // Load overriden system values
                    fi.LoadDefaultValues(dr, wpi.WebPartDefaultValues);

                    // Set control ID
                    FormFieldInfo ffi = fi.GetFormField("WebPartControlID");
                    if (ffi != null)
                    {
                        ffi.DefaultValue = WebPartZoneInstance.GetUniqueWebPartId(wpi.WebPartName, templateInstance);
                        fi.UpdateFormField("WebPartControlID", ffi);
                    }
                }

                // Load values from existing webpart
                LoadDataRowFromWebPart(dr, webPartInstance);

                // Set a unique WebPartControlID for athe new variant
                if (IsNewVariant)
                {
                    // Set control ID
                    dr["WebPartControlID"] = WebPartZoneInstance.GetUniqueWebPartId(wpi.WebPartName, templateInstance);
                }

                // Init the form
                InitForm(form, dr, fi);

                AddExportLink();
            }
        }
    }
    /// <summary>
    /// Sends confirmation or welcome email.
    /// </summary>
    private void SendRegistrationEmail(UserInfo ui)
    {
        bool error = false;
        EmailTemplateInfo template = null;

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

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

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

        if (template != null)
        {
            // Create relation between contact and user. This ensures that contact will be correctly recognized when user approves registration (if approval is required)
            int contactId = ModuleCommands.OnlineMarketingGetCurrentContactID();
            if (contactId > 0)
            {
                var checker = new UserContactDataPropagationChecker();
                Service.Resolve <IContactRelationAssigner>().Assign(ui.UserID, MembershipType.CMS_USER, contactId, checker);
            }

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

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

            // Email was not send, user can't be approved - delete it
            UserInfoProvider.DeleteUser(ui);
        }
    }
    /// <summary>
    /// Initializes the control properties.
    /// </summary>
    protected void SetupControl()
    {
        repLatestPosts.DataBindByDefault = false;
        pagerElem.PageControl            = repLatestPosts.ID;

        if (StopProcessing)
        {
            // Do nothing
        }
        else
        {
            if (!String.IsNullOrEmpty(TransformationName))
            {
                // Basic control properties
                repLatestPosts.HideControlForZeroRows = HideControlForZeroRows;
                repLatestPosts.ZeroRowsText           = ZeroRowsText;

                // Set data source groupID according to group name
                if (!String.IsNullOrEmpty(GroupName))
                {
                    GeneralizedInfo gi = ModuleCommands.CommunityGetGroupInfoByName(GroupName, SiteName);
                    if (gi != null)
                    {
                        forumDataSource.GroupID = ValidationHelper.GetInteger(gi.GetValue("GroupID"), 0);
                    }
                    else
                    {
                        // Do nothing if no group is set
                        forumDataSource.StopProcessing = true;
                    }
                }

                if (!forumDataSource.StopProcessing)
                {
                    // Data source properties
                    forumDataSource.TopN               = SelectTopN;
                    forumDataSource.OrderBy            = OrderBy;
                    forumDataSource.CacheItemName      = CacheItemName;
                    forumDataSource.CacheDependencies  = CacheDependencies;
                    forumDataSource.CacheMinutes       = CacheMinutes;
                    forumDataSource.SourceFilterName   = FilterName;
                    forumDataSource.SelectOnlyApproved = SelectOnlyApproved;
                    forumDataSource.SiteName           = SiteName;
                    forumDataSource.SelectedColumns    = Columns;
                    forumDataSource.ShowGroupPosts     = ShowGroupPosts && String.IsNullOrEmpty(ForumGroups);


                    #region "Repeater template properties"

                    // Apply transformations if they exist
                    repLatestPosts.ItemTemplate = CMSDataProperties.LoadTransformation(this, TransformationName);

                    // Alternating item
                    if (!String.IsNullOrEmpty(AlternatingItemTransformationName))
                    {
                        repLatestPosts.AlternatingItemTemplate = CMSDataProperties.LoadTransformation(this, AlternatingItemTransformationName);
                    }

                    // Footer
                    if (!String.IsNullOrEmpty(FooterTransformationName))
                    {
                        repLatestPosts.FooterTemplate = CMSDataProperties.LoadTransformation(this, FooterTransformationName);
                    }

                    // Header
                    if (!String.IsNullOrEmpty(HeaderTransformationName))
                    {
                        repLatestPosts.HeaderTemplate = CMSDataProperties.LoadTransformation(this, HeaderTransformationName);
                    }

                    // Separator
                    if (!String.IsNullOrEmpty(SeparatorTransformationName))
                    {
                        repLatestPosts.SeparatorTemplate = CMSDataProperties.LoadTransformation(this, SeparatorTransformationName);
                    }

                    #endregion


                    // UniPager properties
                    pagerElem.PageSize       = PageSize;
                    pagerElem.GroupSize      = GroupSize;
                    pagerElem.QueryStringKey = QueryStringKey;
                    pagerElem.DisplayFirstLastAutomatically    = DisplayFirstLastAutomatically;
                    pagerElem.DisplayPreviousNextAutomatically = DisplayPreviousNextAutomatically;
                    pagerElem.HidePagerForSinglePage           = HidePagerForSinglePage;

                    // Set pager mode
                    switch (PagingMode.ToLowerCSafe())
                    {
                    case "postback":
                        pagerElem.PagerMode = UniPagerMode.PostBack;
                        break;

                    default:
                        pagerElem.PagerMode = UniPagerMode.Querystring;
                        break;
                    }


                    #region "UniPager template properties"

                    // UniPager template properties
                    if (!String.IsNullOrEmpty(PagesTemplate))
                    {
                        pagerElem.PageNumbersTemplate = CMSDataProperties.LoadTransformation(pagerElem, PagesTemplate);
                    }

                    // Current page
                    if (!String.IsNullOrEmpty(CurrentPageTemplate))
                    {
                        pagerElem.CurrentPageTemplate = CMSDataProperties.LoadTransformation(pagerElem, CurrentPageTemplate);
                    }

                    // Separator
                    if (!String.IsNullOrEmpty(SeparatorTemplate))
                    {
                        pagerElem.PageNumbersSeparatorTemplate = CMSDataProperties.LoadTransformation(pagerElem, SeparatorTemplate);
                    }

                    // First page
                    if (!String.IsNullOrEmpty(FirstPageTemplate))
                    {
                        pagerElem.FirstPageTemplate = CMSDataProperties.LoadTransformation(pagerElem, FirstPageTemplate);
                    }

                    // Last page
                    if (!String.IsNullOrEmpty(LastPageTemplate))
                    {
                        pagerElem.LastPageTemplate = CMSDataProperties.LoadTransformation(pagerElem, LastPageTemplate);
                    }

                    // Previous page
                    if (!String.IsNullOrEmpty(PreviousPageTemplate))
                    {
                        pagerElem.PreviousPageTemplate = CMSDataProperties.LoadTransformation(pagerElem, PreviousPageTemplate);
                    }

                    // Next page
                    if (!String.IsNullOrEmpty(NextPageTemplate))
                    {
                        pagerElem.NextPageTemplate = CMSDataProperties.LoadTransformation(pagerElem, NextPageTemplate);
                    }

                    // Previous group
                    if (!String.IsNullOrEmpty(PreviousGroupTemplate))
                    {
                        pagerElem.PreviousGroupTemplate = CMSDataProperties.LoadTransformation(pagerElem, PreviousGroupTemplate);
                    }

                    // Next group
                    if (!String.IsNullOrEmpty(NextGroupTemplate))
                    {
                        pagerElem.NextGroupTemplate = CMSDataProperties.LoadTransformation(pagerElem, NextGroupTemplate);
                    }

                    // Direct page
                    if (!String.IsNullOrEmpty(DirectPageTemplate))
                    {
                        pagerElem.DirectPageTemplate = CMSDataProperties.LoadTransformation(pagerElem, DirectPageTemplate);
                    }

                    // Layout
                    if (!String.IsNullOrEmpty(LayoutTemplate))
                    {
                        pagerElem.LayoutTemplate = CMSDataProperties.LoadTransformation(pagerElem, LayoutTemplate);
                    }

                    #endregion


                    #region "Complete where condition"

                    string where = "";
                    string[] groups = ForumGroups.Split(';');

                    // Create where condition for all forum groups
                    foreach (string group in groups)
                    {
                        if (group != "")
                        {
                            if (where != "")
                            {
                                where += "OR";
                            }
                            where += "(GroupName = N'" + SqlHelper.GetSafeQueryString(group, false) + "')";
                        }
                    }

                    // Add custom where condition
                    if (!string.IsNullOrEmpty(WhereCondition))
                    {
                        if (string.IsNullOrEmpty(where))
                        {
                            where = WhereCondition;
                        }
                        else
                        {
                            where = "(" + WhereCondition + ") AND (" + where + ")";
                        }
                    }

                    #endregion

                    // Set forum data source
                    forumDataSource.WhereCondition   = where;
                    forumDataSource.CheckPermissions = true;
                    repLatestPosts.DataSourceControl = forumDataSource;
                }
            }

            pagerElem.RebindPager();
            repLatestPosts.DataBind();
        }
    }
Пример #22
0
    /// <summary>
    /// On page load.
    /// </summary>
    /// <param name="sender">Sender</param>
    /// <param name="e">Event arguments</param>
    protected void Page_Load(object sender, EventArgs e)
    {
        // Check the license
        if (DataHelper.GetNotEmpty(URLHelper.GetCurrentDomain(), "") != "")
        {
            LicenseHelper.CheckFeatureAndRedirect(URLHelper.GetCurrentDomain(), FeatureEnum.Newsletters);
        }

        // Check site availability
        if (!ResourceSiteInfoProvider.IsResourceOnSite("CMS.Newsletter", CMSContext.CurrentSiteName))
        {
            RedirectToResourceNotAvailableOnSite("CMS.Newsletter");
        }

        // Check site availability
        if (!ResourceSiteInfoProvider.IsResourceOnSite("CMS.Ecommerce", CMSContext.CurrentSiteName))
        {
            RedirectToResourceNotAvailableOnSite("CMS.Ecommerce");
        }

        siteSelector.UniSelector.OnSelectionChanged   += new EventHandler(UniSelector_OnSelectionChanged);
        siteSelector.DropDownSingleSelect.AutoPostBack = true;
        if (!URLHelper.IsPostback())
        {
            siteSelector.SiteID = CMSContext.CurrentSiteID;
        }

        CurrentUserInfo user = CMSContext.CurrentUser;

        // Check 'NewsletterRead' permission
        if (!user.IsAuthorizedPerResource("CMS.Newsletter", "Read"))
        {
            RedirectToCMSDeskAccessDenied("CMS.Newsletter", "Read");
        }

        lblTitle.Text = GetString("Customer_Edit_Newsletters.Title");

        // Load customer data
        GeneralizedInfo customerObj = ModuleCommands.ECommerceGetCustomerInfo(QueryHelper.GetInteger("customerId", 0));

        if (customerObj != null)
        {
            email          = Convert.ToString(customerObj.GetValue("CustomerEmail"));
            firstName      = Convert.ToString(customerObj.GetValue("CustomerFirstName"));
            lastName       = Convert.ToString(customerObj.GetValue("CustomerLastName"));
            customerUserId = ValidationHelper.GetInteger(customerObj.GetValue("CustomerUserID"), -1);

            object customerSiteIdObj = customerObj.GetValue("CustomerSiteID");
            customerSiteId = ValidationHelper.GetInteger((customerSiteIdObj == null) ? 0 : customerSiteIdObj, CMSContext.CurrentSiteID);
        }

        if ((email == null) || (email.Trim() == string.Empty) || (!ValidationHelper.IsEmail(email)))
        {
            lblTitle.Visible      = false;
            lblInfo.Visible       = true;
            lblInfo.Text          = GetString("ecommerce.customer.invalidemail");
            usNewsletters.Visible = false;
        }

        usNewsletters.ButtonRemoveSelected.CssClass = "XLongButton";
        usNewsletters.ButtonAddItems.CssClass       = "XLongButton";
        usNewsletters.OnSelectionChanged           += new EventHandler(usNewsletters_OnSelectionChanged);

        SetWhereCondition();

        LoadSelection(false);
    }
Пример #23
0
    protected void Page_Load(object sender, EventArgs e)
    {
        SetPropertyTab(TAB_GENERAL);

        // Register the scripts
        ScriptHelper.RegisterLoader(Page);
        ScriptHelper.RegisterTooltip(Page);
        ScriptHelper.RegisterDialogScript(this);

        btnEditableContent.OnClientClick = "ShowEditableContent(); return false;";
        btnMessageBoards.OnClientClick   = "ShowMessageBoards(); return false;";
        btnForums.OnClientClick          = "ShowForums(); return false;";

        // Get strings for radio buttons
        lblCacheMinutes.Text = GetString("GeneralProperties.cacheMinutes");

        // Get strings for labels
        lblNameTitle.Text           = GetString("GeneralProperties.Name");
        lblNamePathTitle.Text       = GetString("GeneralProperties.NamePath");
        lblAliasPathTitle.Text      = GetString("GeneralProperties.AliasPath");
        lblTypeTitle.Text           = GetString("GeneralProperties.Type");
        lblNodeIDTitle.Text         = GetString("GeneralProperties.NodeID");
        lblLastModifiedByTitle.Text = GetString("GeneralProperties.LastModifiedBy");
        lblLastModifiedTitle.Text   = GetString("GeneralProperties.LastModified");
        lblLiveURLTitle.Text        = GetString("GeneralProperties.LiveURL");
        lblPreviewURLTitle.Text     = GetString("GeneralProperties.PreviewURL");
        lblGUIDTitle.Text           = GetString("GeneralProperties.GUID");
        lblDocGUIDTitle.Text        = GetString("GeneralProperties.DocumentGUID");
        lblDocIDTitle.Text          = GetString("GeneralProperties.DocumentID");
        lblCultureTitle.Text        = GetString("GeneralProperties.Culture");
        lblCreatedByTitle.Text      = GetString("GeneralProperties.CreatedBy");
        lblCreatedTitle.Text        = GetString("GeneralProperties.Created");
        lblOwnerTitle.Text          = GetString("GeneralProperties.Owner");
        lblCssStyle.Text            = GetString("PageProperties.CssStyle");
        lblPublishedTitle.Text      = GetString("PageProperties.Published");

        // Set default item value
        ctrlSiteSelectStyleSheet.AddDefaultRecord = false;
        ctrlSiteSelectStyleSheet.CurrentSelector.SpecialFields.AllowDuplicates = true;

        if (PortalContext.CurrentSiteStylesheet != null)
        {
            ctrlSiteSelectStyleSheet.CurrentSelector.SpecialFields.Add(new SpecialField {
                Text = GetString("general.defaultchoice"), Value = GetDefaultStylesheet()
            });
        }
        else
        {
            ctrlSiteSelectStyleSheet.CurrentSelector.AllowEmpty = true;
        }

        ctrlSiteSelectStyleSheet.ReturnColumnName = "StyleSheetID";
        ctrlSiteSelectStyleSheet.SiteId           = SiteContext.CurrentSiteID;

        if ((SiteContext.CurrentSite != null) && (usrOwner != null))
        {
            usrOwner.SetValue("SiteID", SiteContext.CurrentSite.SiteID);
        }

        int documentId = 0;

        StringBuilder script = new StringBuilder();

        TreeNode node = Node;

        if (node != null)
        {
            // Redirect to information page when no UI elements displayed
            if (((pnlUIAdvanced.IsHidden && pnlUICache.IsHidden && pnlUIDesign.IsHidden) || ShowContentOnlyProperties) && pnlUIOther.IsHidden && pnlUIOwner.IsHidden)
            {
                RedirectToUINotAvailable();
            }

            // Get strings for headings
            headOtherProperties.Text = ShowContentOnlyProperties ? GetString("content.ui.properties") : GetString("GeneralProperties.OtherGroup");

            if (PortalContext.CurrentSiteStylesheet != null)
            {
                script.Append(@"
var currentStyleSheetId;
// Function raised before opening the Edit dialog of the CSS style sheet control. When 'default' style sheet is chosen, translate this value to the default site style sheet id.
function US_GetEditedItemId_", ctrlSiteSelectStyleSheet.ValueElementID, @"(selectedValue) {
    currentStyleSheetId = selectedValue;
    if (selectedValue == ""default"") {
        return ", PortalContext.CurrentSiteStylesheet.StylesheetID, @";
    }

    return selectedValue;
}

// Function raised from New/Edit dialog after save action. When 'default' style is used, the new/edit dialog will try to choose a real style sheet id (which was edited), but it is necessary keep the selected value to be 'default'.
function US_GetNewItemId_", ctrlSiteSelectStyleSheet.ValueElementID, @"(newStyleSheetId) {
    if ((currentStyleSheetId == ""default"") && (newStyleSheetId == ", PortalContext.CurrentSiteStylesheet.StylesheetID, @")) {
        return currentStyleSheetId;
    }

    return newStyleSheetId;
}
"
                              );
            }

            documentId   = node.DocumentID;
            canEditOwner = (MembershipContext.AuthenticatedUser.IsAuthorizedPerDocument(Node, NodePermissionsEnum.ModifyPermissions) == AuthorizationResultEnum.Allowed);
            ctrlSiteSelectStyleSheet.AliasPath = node.NodeAliasPath;

            ReloadData();

            // Check ad-hoc forum counts
            hasAdHocForum = (ModuleCommands.ForumsGetDocumentForumsCount(node.DocumentID) > 0);

            // Ad-Hoc message boards check
            hasAdHocBoard = (ModuleCommands.MessageBoardGetDocumentBoardsCount(node.DocumentID) > 0);

            script.Append("function ShowEditableContent() { modalDialog('", ResolveUrl("Advanced/EditableContent/default.aspx"), "?nodeid=", node.NodeID, "', 'EditableContent', '95%', '95%'); } \n");
        }

        // Generate executive script
        if (hasAdHocBoard)
        {
            plcAdHocBoards.Visible = true;
            script.Append("function ShowMessageBoards() { modalDialog('", ResolveUrl("~/CMSModules/MessageBoards/Content/Properties/default.aspx"), "?documentid=", documentId, "', 'MessageBoards', '95%', '95%'); } \n");
        }

        if (hasAdHocForum)
        {
            plcAdHocForums.Visible = true;
            script.Append("function ShowForums() { modalDialog('", ResolveUrl("~/CMSModules/Forums/Content/Properties/default.aspx"), "?documentid=", documentId, "', 'Forums', '95%', '95%'); } \n");
        }

        ScriptHelper.RegisterClientScriptBlock(this, typeof(string), "ModalDialogsToAdvancedSection", script.ToString(), true);

        // Reflect processing action
        pnlContent.Enabled = DocumentManager.AllowSave;

        if (chkCssStyle.Checked && (PortalContext.CurrentSiteStylesheet != null))
        {
            // Enable the edit button
            ctrlSiteSelectStyleSheet.ButtonEditEnabled = true;
        }
    }
    /// <summary>
    /// Handles the OnReloadData event of the menuWebPartCPVariants control.
    /// </summary>
    protected void menuWebPartCPVariants_OnReloadData(object sender, EventArgs e)
    {
        // Check permissions
        if ((CMSContext.CurrentUser == null) ||
            (!CMSContext.CurrentUser.IsAuthorizedPerResource("CMS.ContentPersonalization", "Read")))
        {
            return;
        }

        string parameters = ValidationHelper.GetString(menuWebPartCPVariants.Parameter, string.Empty);

        string[] items = parameters.Split(new char[] { ',' }, 7);

        isZone = (items.Length == 4);
        if ((items == null))
        {
            return;
        }

        string zoneId       = string.Empty;
        string webpartName  = string.Empty;
        string aliasPath    = string.Empty;
        Guid   instanceGuid = Guid.Empty;

        if (isZone)
        {
            zoneId    = ValidationHelper.GetString(items[0], string.Empty);
            aliasPath = ValidationHelper.GetString(items[1], string.Empty);
        }
        else
        {
            zoneId       = ValidationHelper.GetString(items[0], string.Empty);
            webpartName  = ValidationHelper.GetString(items[1], string.Empty);
            aliasPath    = ValidationHelper.GetString(items[2], string.Empty);
            instanceGuid = ValidationHelper.GetGuid(items[3], Guid.Empty);
        }

        if ((CMSContext.CurrentPageInfo != null) &&
            (CMSContext.CurrentPageInfo.TemplateInstance != null))
        {
            int templateId = CMSContext.CurrentPageInfo.UsedPageTemplateInfo.PageTemplateId;

            DataSet   ds          = ModuleCommands.OnlineMarketingGetContentPersonalizationVariants(templateId, zoneId, instanceGuid, 0);
            DataTable resultTable = null;

            if (!DataHelper.DataSourceIsEmpty(ds))
            {
                DataTable table = ds.Tables[0].Copy();
                table.DefaultView.Sort = columnVariantID;

                // Add the original web part as the first item in the variant list
                DataRow originalVariant = table.NewRow();
                originalVariant[columnVariantID]             = 0;
                originalVariant[columnVariantDisplayName]    = ResHelper.GetString(isZone ? "ZoneMenu.OriginalZone" : "WebPartMenu.OriginalWebPart");
                originalVariant[columnVariantZoneID]         = zoneId;
                originalVariant[columnVariantPageTemplateID] = templateId;
                originalVariant[columnVariantInstanceGUID]   = instanceGuid;
                table.Rows.InsertAt(originalVariant, 0);

                resultTable = table.DefaultView.ToTable();
            }

            repWebPartCPVariants.DataSource = resultTable;
            repWebPartCPVariants.DataBind();
        }
    }
Пример #25
0
    /// <summary>
    /// Load event.
    /// </summary>
    protected void Page_Load(object sender, EventArgs e)
    {
        InitializeForm();

        drpLockReason.Enabled = chkEnabled.Checked;

        // Score selector is not null only if DisplayScore is true
        if (scoreSelector != null)
        {
            if ((CurrentMode == "online") && DisplayContacts)
            {
                plcScore.Visible = true;
            }

            int siteId = QueryHelper.GetInteger("siteid", 0);
            scoreSelector.Enabled = (siteId > 0) || ((siteId == 0) && (siteSelector.SiteID > 0));

            if (siteId == 0)
            {
                scoreSelector.SetValue("SiteID", siteSelector.SiteID);
            }
        }

        // Show correct filter panel
        EnsureFilterMode();

        // Set reset link button
        UniGrid grid = FilteredControl as UniGrid;

        if (grid != null && grid.RememberState)
        {
            if (isAdvancedMode)
            {
                btnAdvancedReset.Text   = GetString("general.reset");
                btnAdvancedReset.Click += btnReset_Click;
            }
            else
            {
                btnReset.Text   = GetString("general.reset");
                btnReset.Click += btnReset_Click;
            }
        }
        else
        {
            if (isAdvancedMode)
            {
                btnAdvancedReset.Visible = false;
            }
            else
            {
                btnReset.Visible = false;
            }
        }

        // Show group filter only if enabled
        if (SiteID > 0)
        {
            SiteInfo si = SiteInfoProvider.GetSiteInfo(SiteID);
            if ((si != null) && isAdvancedMode)
            {
                showGroups = ModuleCommands.CommunitySiteHasGroup(si.SiteID);
            }
        }

        // Setup role selector
        selectNotInRole.SiteID = SiteID;
        selectRoleElem.SiteID  = SiteID;
        selectRoleElem.CurrentSelector.ResourcePrefix  = "addroles";
        selectNotInRole.CurrentSelector.ResourcePrefix = "addroles";
        selectRoleElem.UseFriendlyMode  = true;
        selectNotInRole.UseFriendlyMode = true;

        // Setup groups selectors
        plcGroups.Visible = showGroups;
        if (selectInGroups != null)
        {
            selectInGroups.StopProcessing       = !showGroups;
            selectInGroups.FormControlParameter = SiteID;
        }

        if (selectNotInGroups != null)
        {
            selectNotInGroups.StopProcessing       = !showGroups;
            selectNotInGroups.FormControlParameter = SiteID;
        }

        if (SessionInsteadOfUser && DisplayGuestsByDefault)
        {
            plcNickName.Visible = false;
            plcUserName.Visible = false;
        }

        if (QueryHelper.GetBoolean("isonlinemarketing", false))
        {
            // Set disabled modules info (only on On-line marketing tab)
            ucDisabledModule.SettingsKeys = "CMSSessionUseDBRepository;CMSEnableOnlineMarketing";
            ucDisabledModule.Visible      = true;
        }
    }
Пример #26
0
    /// <summary>
    /// Handles the OnReloadData event of the menuWebPartVariants control.
    /// </summary>
    protected void menuZoneCPVariants_OnReloadData(object sender, EventArgs e)
    {
        // Check permissions
        if ((currentUser == null) ||
            (!currentUser.IsAuthorizedPerResource("CMS.ContentPersonalization", "Read")))
        {
            return;
        }

        SetColumnNames(VariantModeEnum.ContentPersonalization);

        string parameters = ValidationHelper.GetString(menuZoneCPVariants.Parameter, string.Empty);

        string[] items = parameters.Split(new char[] { ',' }, 3);
        if ((items == null) || (items.Length != 3))
        {
            return;
        }

        string zoneId    = ValidationHelper.GetString(items[0], string.Empty);
        string aliasPath = ValidationHelper.GetString(items[1], string.Empty);

        if ((CMSContext.CurrentPageInfo != null) &&
            (CMSContext.CurrentPageInfo.TemplateInstance != null))
        {
            int templateId = CMSContext.CurrentPageInfo.PageTemplateInfo.PageTemplateId;

            DataSet   ds          = ModuleCommands.OnlineMarketingGetContentPersonalizationVariants(templateId, zoneId, Guid.Empty, 0);
            DataTable resultTable = null;

            if (!DataHelper.DataSourceIsEmpty(ds))
            {
                DataTable table = ds.Tables[0].Copy();
                table.DefaultView.Sort = columnVariantID;

                // Add the original web part as the first item in the variant list
                DataRow originalVariant = table.NewRow();
                originalVariant[columnVariantID]             = 0;
                originalVariant[columnVariantDisplayName]    = ResHelper.GetString("WebPartMenu.OriginalWebPart");
                originalVariant[columnVariantZoneID]         = zoneId;
                originalVariant[columnVariantPageTemplateID] = templateId;
                originalVariant[columnVariantInstanceGUID]   = Guid.Empty;
                table.Rows.InsertAt(originalVariant, 0);

                resultTable = table.DefaultView.ToTable();

                if (DataHelper.DataSourceIsEmpty(resultTable))
                {
                    pnlNoZoneCPVariants.Visible = true;
                    lblNoZoneCPVariants.Text    = ResHelper.GetString("Content.NoPermissions");
                }
            }
            else
            {
                pnlNoZoneCPVariants.Visible = true;
            }

            repZoneCPVariants.DataSource = resultTable;
            repZoneCPVariants.DataBind();
        }
    }
Пример #27
0
    /// <summary>
    /// Initializes the control properties.
    /// </summary>
    protected void SetupControl()
    {
        if (StopProcessing)
        {
            // Do nothing
        }
        else
        {
            // Initialize properties
            string script = "";

            // Set current user
            currentUser = MembershipContext.AuthenticatedUser;

            // Get Enable Friends setting
            bool friendsEnabled = UIHelper.IsFriendsModuleEnabled(SiteContext.CurrentSiteName);

            // Initialize strings
            lnkSignIn.Text                 = SignInText;
            lnkJoinCommunity.Text          = JoinCommunityText;
            lnkMyProfile.Text              = MyProfileText;
            lnkEditMyProfile.Text          = EditMyProfileText;
            btnSignOut.Text                = SignOutText;
            lnkCreateNewGroup.Text         = CreateNewGroupText;
            lnkCreateNewBlog.Text          = CreateNewBlogText;
            lnkJoinGroup.Text              = JoinGroupText;
            lnkLeaveGroup.Text             = LeaveGroupText;
            lnkRejectFriendship.Text       = RejectFriendshipText;
            requestFriendshipElem.LinkText = RequestFriendshipText;
            lnkSendMessage.Text            = SendMessageText;
            lnkAddToContactList.Text       = AddToContactListText;
            lnkAddToIgnoreList.Text        = AddToIgnoreListText;
            lnkInviteToGroup.Text          = InviteGroupText;
            lnkManageGroup.Text            = ManageGroupText;
            lnkMyMessages.Text             = MyMessagesText;
            lnkMyFriends.Text              = MyFriendsText;
            lnkMyInvitations.Text          = MyInvitationsText;

            // If current user is public...
            if (currentUser.IsPublic())
            {
                // Display Sign In link if set so
                if (DisplaySignIn)
                {
                    // SignInPath returns URL - because of settings value
                    lnkSignIn.NavigateUrl = MacroResolver.ResolveCurrentPath(SignInPath);
                    pnlSignIn.Visible     = true;
                    pnlSignInOut.Visible  = true;
                }

                // Display Join the community link if set so
                if (DisplayJoinCommunity)
                {
                    lnkJoinCommunity.NavigateUrl = GetUrl(JoinCommunityPath);
                    pnlJoinCommunity.Visible     = true;
                    pnlPersonalLinks.Visible     = true;
                }
            }
            // If user is logged in
            else
            {
                // Display Sign out link if set so
                if (DisplaySignOut && !RequestHelper.IsWindowsAuthentication())
                {
                    pnlSignOut.Visible   = true;
                    pnlSignInOut.Visible = true;
                }

                // Display Edit my profile link if set so
                if (DisplayEditMyProfileLink)
                {
                    lnkEditMyProfile.NavigateUrl = UrlResolver.ResolveUrl(DocumentURLProvider.GetUrl(GroupMemberInfoProvider.GetMemberManagementPath(currentUser.UserName, SiteContext.CurrentSiteName)));
                    pnlEditMyProfile.Visible     = true;
                    pnlProfileLinks.Visible      = true;
                }

                // Display My profile link if set so
                if (DisplayMyProfileLink)
                {
                    lnkMyProfile.NavigateUrl = UrlResolver.ResolveUrl(DocumentURLProvider.GetUrl(GroupMemberInfoProvider.GetMemberProfilePath(currentUser.UserName, SiteContext.CurrentSiteName)));
                    pnlMyProfile.Visible     = true;
                    pnlProfileLinks.Visible  = true;
                }

                // Display Create new group link if set so
                if (DisplayCreateNewGroup)
                {
                    lnkCreateNewGroup.NavigateUrl = GetUrl(CreateNewGroupPath);
                    pnlCreateNewGroup.Visible     = true;
                    pnlGroupLinks.Visible         = true;
                }

                // Display Create new blog link if set so
                if (DisplayCreateNewBlog)
                {
                    // Check that Community Module is present
                    var entry = ModuleManager.GetModule(ModuleName.BLOGS);
                    if (entry != null)
                    {
                        lnkCreateNewBlog.NavigateUrl = GetUrl(CreateNewBlogPath);
                        pnlCreateNewBlog.Visible     = true;
                        pnlBlogLinks.Visible         = true;
                    }
                }

                // Display My messages link
                if (DisplayMyMessages)
                {
                    lnkMyMessages.NavigateUrl = GetUrl(MyMessagesPath);
                    pnlMyMessages.Visible     = true;
                    pnlPersonalLinks.Visible  = true;
                }

                // Display My friends link
                if (DisplayMyFriends && friendsEnabled)
                {
                    lnkMyFriends.NavigateUrl = GetUrl(MyFriendsPath);
                    pnlMyFriends.Visible     = true;
                    pnlPersonalLinks.Visible = true;
                }

                // Display My invitations link
                if (DisplayMyInvitations)
                {
                    lnkMyInvitations.NavigateUrl = GetUrl(MyInvitationsPath);
                    pnlMyInvitations.Visible     = true;
                    pnlPersonalLinks.Visible     = true;
                }

                GroupMemberInfo gmi = null;

                if (CommunityContext.CurrentGroup != null)
                {
                    // Get group info from community context
                    GroupInfo currentGroup = CommunityContext.CurrentGroup;

                    if (DisplayGroupLinks)
                    {
                        script += "function ReloadPage(){" + ControlsHelper.GetPostBackEventReference(this, "") + "}";

                        // Display Join group link if set so and user is visiting a group page
                        gmi = GetGroupMember(MembershipContext.AuthenticatedUser.UserID, currentGroup.GroupID);
                        if (gmi == null)
                        {
                            if (String.IsNullOrEmpty(JoinGroupPath))
                            {
                                script += "function JoinToGroupRequest() {\n" +
                                          "modalDialog('" + ApplicationUrlHelper.ResolveDialogUrl("~/CMSModules/Groups/CMSPages/JoinTheGroup.aspx") + "?groupid=" + currentGroup.GroupID + "','requestJoinToGroup', 500, 180); \n" +
                                          " } \n";

                                lnkJoinGroup.Attributes.Add("onclick", "JoinToGroupRequest();return false;");
                                lnkJoinGroup.NavigateUrl = RequestContext.CurrentURL;
                            }
                            else
                            {
                                lnkJoinGroup.NavigateUrl = GetUrl(JoinGroupPath);
                            }
                            pnlJoinGroup.Visible  = true;
                            pnlGroupLinks.Visible = true;
                        }
                        else if ((gmi.MemberStatus == GroupMemberStatus.Approved) || (MembershipContext.AuthenticatedUser.CheckPrivilegeLevel(UserPrivilegeLevelEnum.Admin)))
                        // Display Leave the group link if user is the group member
                        {
                            if (String.IsNullOrEmpty(LeaveGroupPath))
                            {
                                script += "function LeaveTheGroupRequest() {\n" +
                                          "modalDialog('" + ApplicationUrlHelper.ResolveDialogUrl("~/CMSModules/Groups/CMSPages/LeaveTheGroup.aspx") + "?groupid=" + currentGroup.GroupID + "','requestLeaveThGroup', 500, 180); \n" +
                                          " } \n";

                                lnkLeaveGroup.Attributes.Add("onclick", "LeaveTheGroupRequest();return false;");
                                lnkLeaveGroup.NavigateUrl = RequestContext.CurrentURL;
                            }
                            else
                            {
                                lnkLeaveGroup.NavigateUrl = GetUrl(LeaveGroupPath);
                            }

                            pnlLeaveGroup.Visible = true;
                            pnlGroupLinks.Visible = true;
                        }
                    }

                    // Display Manage the group link if set so and user is logged as group administrator and user is visiting a group page
                    if (DisplayManageGroup && (currentUser.IsGroupAdministrator(currentGroup.GroupID) || (currentUser.CheckPrivilegeLevel(UserPrivilegeLevelEnum.Admin))))
                    {
                        lnkManageGroup.NavigateUrl = ResolveUrl(DocumentURLProvider.GetUrl(GroupInfoProvider.GetGroupManagementPath(currentGroup.GroupName, SiteContext.CurrentSiteName)));
                        pnlManageGroup.Visible     = true;
                        pnlGroupLinks.Visible      = true;
                    }
                }

                // Get user info from site context
                UserInfo siteContextUser = MembershipContext.CurrentUserProfile;

                if (DisplayInviteToGroup)
                {
                    // Get group info from community context
                    GroupInfo currentGroup = CommunityContext.CurrentGroup;

                    // Display invite to group link for user who is visiting a group page
                    if (currentGroup != null)
                    {
                        // Get group user
                        if (gmi == null)
                        {
                            gmi = GetGroupMember(MembershipContext.AuthenticatedUser.UserID, currentGroup.GroupID);
                        }

                        if (((gmi != null) && (gmi.MemberStatus == GroupMemberStatus.Approved)) || (MembershipContext.AuthenticatedUser.CheckPrivilegeLevel(UserPrivilegeLevelEnum.Admin)))
                        {
                            pnlInviteToGroup.Visible = true;

                            if (String.IsNullOrEmpty(InviteGroupPath))
                            {
                                script += "function InviteToGroup() {\n modalDialog('" + ApplicationUrlHelper.ResolveDialogUrl("~/CMSModules/Groups/CMSPages/InviteToGroup.aspx") + "?groupid=" + currentGroup.GroupID + "','inviteToGroup', 800, 450); \n } \n";
                                lnkInviteToGroup.Attributes.Add("onclick", "InviteToGroup();return false;");
                                lnkInviteToGroup.NavigateUrl = RequestContext.CurrentURL;
                            }
                            else
                            {
                                lnkInviteToGroup.NavigateUrl = GetUrl(InviteGroupPath);
                            }
                        }
                    }
                    // Display invite to group link for user who is visiting another user's page
                    else if ((siteContextUser != null) && (siteContextUser.UserName != currentUser.UserName) && (GroupInfoProvider.GetUserGroupsCount(currentUser, SiteContext.CurrentSite) != 0))
                    {
                        pnlInviteToGroup.Visible = true;

                        if (String.IsNullOrEmpty(InviteGroupPath))
                        {
                            script += "function InviteToGroup() {\n modalDialog('" + ApplicationUrlHelper.ResolveDialogUrl("~/CMSModules/Groups/CMSPages/InviteToGroup.aspx") + "?invitedid=" + siteContextUser.UserID + "','inviteToGroup', 700, 400); \n } \n";
                            lnkInviteToGroup.Attributes.Add("onclick", "InviteToGroup();return false;");
                            lnkInviteToGroup.NavigateUrl = RequestContext.CurrentURL;
                        }
                        else
                        {
                            lnkInviteToGroup.NavigateUrl = GetUrl(InviteGroupPath);
                        }
                    }
                }

                if (siteContextUser != null)
                {
                    // Display Friendship link if set so and user is visiting an user's page
                    if (DisplayFriendshipLinks && (currentUser.UserID != siteContextUser.UserID) && friendsEnabled)
                    {
                        FriendshipStatusEnum status = MembershipContext.AuthenticatedUser.HasFriend(siteContextUser.UserID);
                        switch (status)
                        {
                        case FriendshipStatusEnum.Approved:
                            // Friendship rejection
                            script += "function ShortcutFriendshipReject(id) { \n" +
                                      "modalDialog('" + ApplicationUrlHelper.ResolveDialogUrl("~/CMSModules/Friends/CMSPages/Friends_Reject.aspx") + "?userid=" + currentUser.UserID + "&requestid=' + id , 'rejectFriend', 410, 270); \n" +
                                      " } \n";

                            lnkRejectFriendship.Attributes.Add("onclick", "ShortcutFriendshipReject('" + siteContextUser.UserID + "');return false;");
                            lnkRejectFriendship.NavigateUrl = RequestContext.CurrentURL;
                            pnlRejectFriendship.Visible     = true;
                            pnlFriendshipLinks.Visible      = true;
                            break;

                        case FriendshipStatusEnum.None:
                            requestFriendshipElem.UserID          = currentUser.UserID;
                            requestFriendshipElem.RequestedUserID = siteContextUser.UserID;
                            pnlFriendshipLink.Visible             = true;
                            pnlFriendshipLinks.Visible            = true;
                            break;
                        }
                    }

                    // Show messaging links if enabled
                    if (MessagingPresent && (currentUser.UserID != siteContextUser.UserID))
                    {
                        // Display Send message link if user is visiting an user's page
                        if (DisplaySendMessage)
                        {
                            // Send private message
                            script += "function ShortcutPrivateMessage(id) { \n" +
                                      "modalDialog('" + ApplicationUrlHelper.ResolveDialogUrl("~/CMSModules/Messaging/CMSPages/SendMessage.aspx") + "?userid=" + currentUser.UserID + "&requestid=' + id , 'sendMessage', 390, 390); \n" +
                                      " } \n";

                            lnkSendMessage.Attributes.Add("onclick", "ShortcutPrivateMessage('" + siteContextUser.UserID + "');return false;");
                            lnkSendMessage.NavigateUrl = RequestContext.CurrentURL;
                            pnlSendMessage.Visible     = true;
                            pnlMessageLinks.Visible    = true;
                        }

                        // Display Add to contact list link if user is visiting an user's page
                        if (DisplayAddToContactList)
                        {
                            // Check if user is in contact list
                            bool isInContactList = ModuleCommands.MessagingIsInContactList(currentUser.UserID, siteContextUser.UserID);

                            // Add to actions
                            if (!isInContactList)
                            {
                                lnkAddToContactList.Attributes.Add("onclick", "return ShortcutAddToContactList('" + siteContextUser.UserID + "')");
                                lnkAddToContactList.NavigateUrl = RequestContext.CurrentURL;
                                pnlAddToContactList.Visible     = true;
                                pnlMessageLinks.Visible         = true;

                                // Add to contact list
                                script += "function ShortcutAddToContactList(usertoadd) { \n" +
                                          "var confirmation = confirm(" + ScriptHelper.GetString(GetString("messaging.contactlist.addconfirmation")) + ");" +
                                          "if(confirmation)" +
                                          "{" +
                                          "selectedIdElem = document.getElementById('" + hdnSelectedId.ClientID + "'); \n" +
                                          "if (selectedIdElem != null) { selectedIdElem.value = usertoadd;}" +
                                          ControlsHelper.GetPostBackEventReference(this, "addtocontactlist", false) +
                                          "} return false;}\n";
                            }
                        }

                        // Display Add to ignore list link if user is visiting an user's page
                        if (DisplayAddToIgnoreList)
                        {
                            // Check if user is in ignore list
                            bool isInIgnoreList = ModuleCommands.MessagingIsInIgnoreList(currentUser.UserID, siteContextUser.UserID);

                            // Add to ignore list
                            if (!isInIgnoreList)
                            {
                                lnkAddToIgnoreList.Attributes.Add("onclick", "return ShortcutAddToIgnoretList('" + siteContextUser.UserID + "')");
                                lnkAddToIgnoreList.NavigateUrl = RequestContext.CurrentURL;
                                pnlAddToIgnoreList.Visible     = true;
                                pnlMessageLinks.Visible        = true;

                                // Add to ignore list
                                script += "function ShortcutAddToIgnoretList(usertoadd) { \n" +
                                          "var confirmation = confirm(" + ScriptHelper.GetString(GetString("messaging.ignorelist.addconfirmation")) + ");" +
                                          "if(confirmation)" +
                                          "{" +
                                          "selectedIdElem = document.getElementById('" + hdnSelectedId.ClientID + "'); \n" +
                                          "if (selectedIdElem != null) { selectedIdElem.value = usertoadd;}" +
                                          ControlsHelper.GetPostBackEventReference(this, "addtoignorelist", false) +
                                          "} return false; } \n";
                            }
                        }
                    }
                }
            }

            // Register menu management scripts
            ScriptHelper.RegisterClientScriptBlock(this, typeof(string), "Shortcuts_" + ClientID, ScriptHelper.GetScript(script));

            // Register the dialog script
            ScriptHelper.RegisterDialogScript(Page);
        }
    }
Пример #28
0
    /// <summary>
    /// Handles the OnReloadData event of the menuZoneVariants control.
    /// </summary>
    protected void menuMoveToZoneVariants_OnReloadData(object sender, EventArgs e)
    {
        // Check permissions
        if (currentUser == null)
        {
            return;
        }

        if ((CMSContext.CurrentPageInfo != null) &&
            (CMSContext.CurrentPageInfo.TemplateInstance != null))
        {
            VariantModeEnum currentVariantMode = VariantModeEnum.None;
            string          targetZoneId       = ValidationHelper.GetString(menuMoveToZoneVariants.Parameter, string.Empty);
            int             pageTemplateId     = CMSContext.CurrentPageInfo.PageTemplateInfo.PageTemplateId;

            // Get selected zone variant mode
            if ((CMSContext.CurrentPageInfo != null) &&
                (CMSContext.CurrentPageInfo.TemplateInstance != null))
            {
                WebPartZoneInstance targetZone = CMSContext.CurrentPageInfo.TemplateInstance.GetZone(targetZoneId);
                if (targetZone != null)
                {
                    currentVariantMode = targetZone.VariantMode;
                }
            }

            SetColumnNames(currentVariantMode);

            // Get all zone variants of the current web part
            DataSet   ds          = null;
            DataTable resultTable = null;

            if (currentVariantMode == VariantModeEnum.MVT)
            {
                if (currentUser.IsAuthorizedPerResource("CMS.mvtest", "Read"))
                {
                    // MVT variants
                    ds = ModuleCommands.OnlineMarketingGetMVTVariants(pageTemplateId, targetZoneId, Guid.Empty, 0);
                }
            }
            else if (currentVariantMode == VariantModeEnum.ContentPersonalization)
            {
                if (currentUser.IsAuthorizedPerResource("CMS.ContentPersonalization", "Read"))
                {
                    // Content personalization variants
                    ds = ModuleCommands.OnlineMarketingGetContentPersonalizationVariants(pageTemplateId, targetZoneId, Guid.Empty, 0);
                }
            }

            if (!DataHelper.DataSourceIsEmpty(ds))
            {
                DataTable table = ds.Tables[0].Copy();
                table.DefaultView.Sort = columnVariantID;

                // Add the original web part as the first item in the variant list
                DataRow originalVariant = table.NewRow();
                originalVariant[columnVariantID]             = 0;
                originalVariant[columnVariantDisplayName]    = ResHelper.GetString("ZoneMenu.OriginalZone");
                originalVariant[columnVariantZoneID]         = targetZoneId;
                originalVariant[columnVariantPageTemplateID] = pageTemplateId;
                originalVariant[columnVariantInstanceGUID]   = Guid.Empty;
                table.Rows.InsertAt(originalVariant, 0);

                resultTable = table.DefaultView.ToTable();

                if (DataHelper.DataSourceIsEmpty(resultTable))
                {
                    pnlNoZoneVariants.Visible = true;
                    ltlNoZoneVariants.Text    = ResHelper.GetString("Content.NoPermissions");
                }
            }

            this.repMoveToZoneVariants.DataSource = resultTable;
            this.repMoveToZoneVariants.DataBind();
        }
    }
Пример #29
0
    /// <summary>
    /// Sets data to database.
    /// </summary>
    protected void btnOK_Click(object sender, EventArgs e)
    {
        string errorMessage = "";
        string siteName     = CMSContext.CurrentSiteName;

        if ((txtCustomerCompany.Text.Trim() == "" || !chkCompanyAccount.Checked) &&
            ((txtCustomerFirstName.Text.Trim() == "") || (txtCustomerLastName.Text.Trim() == "")))
        {
            errorMessage = GetString("Customers_Edit.errorInsert");
        }
        // Check the following items if complete company info is required for company account
        if (errorMessage == "" && ECommerceSettings.RequireCompanyInfo(siteName) && chkCompanyAccount.Checked)
        {
            errorMessage = new Validator().NotEmpty(txtCustomerCompany.Text, GetString("customers_edit.errorCompany"))
                           .NotEmpty(txtOraganizationID.Text, GetString("customers_edit.errorOrganizationID"))
                           .NotEmpty(txtTaxRegistrationID.Text, GetString("customers_edit.errorTaxRegID")).Result;
        }

        if (errorMessage == "")
        {
            errorMessage = new Validator().IsEmail(txtCustomerEmail.Text.Trim(), GetString("customers_edit.erroremailformat")).Result;
        }

        plcCompanyInfo.Visible = chkCompanyAccount.Checked;

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

            int currencyId = selectCurrency.CurrencyID;

            if (ECommerceContext.CurrentShoppingCart != null)
            {
                ECommerceContext.CurrentShoppingCart.ShoppingCartCurrencyID = currencyId;
            }

            mCustomer.CustomerEmail     = txtCustomerEmail.Text.Trim();
            mCustomer.CustomerFax       = txtCustomerFax.Text.Trim();
            mCustomer.CustomerLastName  = txtCustomerLastName.Text.Trim();
            mCustomer.CustomerPhone     = txtCustomerPhone.Text.Trim();
            mCustomer.CustomerFirstName = txtCustomerFirstName.Text.Trim();
            mCustomer.CustomerCountryID = drpCountry.CountryID;
            mCustomer.CustomerStateID   = drpCountry.StateID;
            mCustomer.CustomerCreated   = DateTime.Now;

            // Set customers's preferences
            mCustomer.CustomerPreferredCurrencyID       = (currencyId > 0) ? currencyId : 0;
            mCustomer.CustomerPreferredPaymentOptionID  = drpPayment.PaymentID;
            mCustomer.CustomerPreferredShippingOptionID = drpShipping.ShippingID;

            // Check if customer is registered
            if (mCustomer.CustomerIsRegistered)
            {
                // Find user-site binding
                UserSiteInfo userSite = UserSiteInfoProvider.GetUserSiteInfo(Customer.CustomerUserID, CMSContext.CurrentSiteID);
                if (userSite != null)
                {
                    // Set user's preferences
                    userSite.UserPreferredCurrencyID       = mCustomer.CustomerPreferredCurrencyID;
                    userSite.UserPreferredPaymentOptionID  = mCustomer.CustomerPreferredPaymentOptionID;
                    userSite.UserPreferredShippingOptionID = mCustomer.CustomerPreferredShippingOptionID;

                    UserSiteInfoProvider.SetUserSiteInfo(userSite);
                }
            }

            if (chkCompanyAccount.Checked)
            {
                mCustomer.CustomerCompany = txtCustomerCompany.Text.Trim();
                if (ECommerceSettings.ShowOrganizationID(siteName))
                {
                    mCustomer.CustomerOrganizationID = txtOraganizationID.Text.Trim();
                }
                if (ECommerceSettings.ShowTaxRegistrationID(siteName))
                {
                    mCustomer.CustomerTaxRegistrationID = txtTaxRegistrationID.Text.Trim();
                }
            }
            else
            {
                mCustomer.CustomerCompany           = "";
                mCustomer.CustomerOrganizationID    = "";
                mCustomer.CustomerTaxRegistrationID = "";
            }

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

            // Update corresponding user email
            UserInfo user = mCustomer.CustomerUser;
            if (user != null)
            {
                user.Email = mCustomer.CustomerEmail;
                UserInfoProvider.SetUserInfo(user);
            }

            // Update corresponding contact data
            ModuleCommands.OnlineMarketingUpdateContactFromExternalData(mCustomer, DataClassInfoProvider.GetDataClass(CustomerInfo.TYPEINFO.ObjectClassName).ClassContactOverwriteEnabled,
                                                                        ModuleCommands.OnlineMarketingGetCurrentContactID());

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

                ShowChangesSaved();
            }
            else
            {
                URLHelper.Redirect(URLHelper.AddParameterToUrl(URLRewriter.CurrentURL, "saved", "1"));
            }
        }
        else
        {
            //Show error
            ShowError(errorMessage);
        }
    }
Пример #30
0
    /// <summary>
    /// Sets image  url, width and height.
    /// </summary>
    protected void SetImage()
    {
        Visible = false;

        // Only if display picture is allowed
        if (DisplayPicture)
        {
            string imageUrl = ResolveUrl("~/CMSModules/Avatars/CMSPages/GetAvatar.aspx?avatarguid=");

            bool isGravatar = false;

            // Is user id set? => Get user info
            if (mUserId > 0)
            {
                // Get user info
                UserInfo ui = UserInfoProvider.GetUserInfo(mUserId);
                if (ui != null)
                {
                    switch (UserAvatarType)
                    {
                    case AvatarInfoProvider.AVATAR:
                        AvatarID = ui.UserAvatarID;
                        if (AvatarID <= 0)     // Backward compatibility
                        {
                            if (ui.UserPicture != "")
                            {
                                // Get picture filename
                                string filename = ui.UserPicture.Remove(ui.UserPicture.IndexOfCSafe('/'));
                                string ext      = Path.GetExtension(filename);
                                imageUrl += filename.Substring(0, (filename.Length - ext.Length));
                                imageUrl += "&extension=" + ext;
                                Visible   = true;
                            }
                            else if (UseDefaultAvatar)
                            {
                                UserGenderEnum gender = (UserGenderEnum)ValidationHelper.GetInteger(ui.UserSettings.UserGender, 0);
                                AvatarInfo     ai     = AvatarInfoProvider.GetDefaultAvatar(gender);

                                if (ai != null)
                                {
                                    AvatarID = ai.AvatarID;
                                }
                            }
                        }
                        break;

                    case AvatarInfoProvider.GRAVATAR:
                        int sideSize = mWidth > 0 ? mWidth : SettingsKeyInfoProvider.GetIntValue(SiteContext.CurrentSiteName + ".CMSAvatarMaxSideSize");
                        imageUrl   = AvatarInfoProvider.CreateGravatarLink(ui.Email, ui.UserSettings.UserGender, sideSize, SiteContext.CurrentSiteName);
                        isGravatar = true;
                        Visible    = true;
                        AvatarID   = 0;
                        break;
                    }
                }
            }
            else
            {
                // If user is public try get his gravatar
                if (UserAvatarType == AvatarInfoProvider.GRAVATAR)
                {
                    int sideSize = mWidth > 0 ? mWidth : SettingsKeyInfoProvider.GetIntValue(SiteContext.CurrentSiteName + ".CMSAvatarMaxSideSize");
                    imageUrl   = AvatarInfoProvider.CreateGravatarLink(UserEmail, (int)UserGenderEnum.Unknown, sideSize, SiteContext.CurrentSiteName);
                    isGravatar = true;
                    Visible    = true;
                    AvatarID   = 0;
                }
            }

            // Is group id set? => Get group info
            if (mGroupId > 0)
            {
                // Get group info trough module commands
                GeneralizedInfo gi = ModuleCommands.CommunityGetGroupInfo(mGroupId);
                if (gi != null)
                {
                    AvatarID = ValidationHelper.GetInteger(gi.GetValue("GroupAvatarID"), 0);
                }

                if ((AvatarID <= 0) && UseDefaultAvatar)
                {
                    AvatarInfo ai = AvatarInfoProvider.GetDefaultAvatar(DefaultAvatarTypeEnum.Group);
                    if (ai != null)
                    {
                        AvatarID = ai.AvatarID;
                    }
                }
            }

            if (AvatarID > 0)
            {
                AvatarInfo ai = AvatarInfoProvider.GetAvatarInfoWithoutBinary(AvatarID);
                if (ai != null)
                {
                    imageUrl += ai.AvatarGUID.ToString();
                    Visible   = true;
                }
            }


            // If item was found
            if (Visible)
            {
                if (!isGravatar)
                {
                    if (KeepAspectRatio)
                    {
                        imageUrl += "&maxsidesize=" + (Width > Height ? Width : Height);
                    }
                    else
                    {
                        imageUrl += "&width=" + Width + "&height=" + Height;
                    }
                }

                imageUrl      = HTMLHelper.EncodeForHtmlAttribute(imageUrl);
                ltlImage.Text = "<img alt=\"" + GetString("general.avatar") + "\" src=\"" + imageUrl + "\" />";

                // Render outer div with specific CSS class
                if (RenderOuterDiv)
                {
                    ltlImage.Text = "<div class=\"" + OuterDivCSSClass + "\">" + ltlImage.Text + "</div>";
                }
            }
        }
    }