Esempio n. 1
0
    /// <summary>
    /// Updates the current Group or creates new if no GroupID is present.
    /// </summary>
    public void SaveData()
    {
        if (!CheckPermissions("cms.groups", PERMISSION_MANAGE, GroupID))
        {
            return;
        }

        // Trim display name and code name
        string displayName = txtDisplayName.Text.Trim();
        string codeName    = txtCodeName.Text.Trim();

        // Validate form entries
        string errorMessage = ValidateForm(displayName, codeName);

        if (errorMessage == "")
        {
            GroupInfo group = null;

            try
            {
                bool newGroup = false;

                // Update existing item
                if ((GroupID > 0) && (gi != null))
                {
                    group = gi;
                }
                else
                {
                    group    = new GroupInfo();
                    newGroup = true;
                }

                if (group != null)
                {
                    if (displayName != group.GroupDisplayName)
                    {
                        // Refresh a breadcrumb if used in the tabs layout
                        ScriptHelper.RefreshTabHeader(Page, displayName);
                    }

                    if (DisplayAdvanceOptions)
                    {
                        // Update Group fields
                        group.GroupDisplayName = displayName;
                        group.GroupName        = codeName;
                        group.GroupNodeGUID    = ValidationHelper.GetGuid(groupPageURLElem.Value, Guid.Empty);
                    }

                    if (AllowChangeGroupDisplayName && IsLiveSite)
                    {
                        group.GroupDisplayName = displayName;
                    }

                    group.GroupDescription                        = txtDescription.Text;
                    group.GroupAccess                             = GetGroupAccess();
                    group.GroupSiteID                             = SiteID;
                    group.GroupApproveMembers                     = GetGroupApproveMembers();
                    group.GroupSendJoinLeaveNotification          = chkJoinLeave.Checked;
                    group.GroupSendWaitingForApprovalNotification = chkWaitingForApproval.Checked;
                    groupPictureEdit.UpdateGroupPicture(group);

                    // If new group was created
                    if (newGroup)
                    {
                        // Set columns GroupCreatedByUserID and GroupApprovedByUserID to current user
                        var user = MembershipContext.AuthenticatedUser;
                        if (user != null)
                        {
                            group.GroupCreatedByUserID  = user.UserID;
                            group.GroupApprovedByUserID = user.UserID;
                            group.GroupApproved         = true;
                        }
                    }

                    if (!IsLiveSite && (group.GroupNodeGUID == Guid.Empty))
                    {
                        plcStyleSheetSelector.Visible = false;
                    }

                    // Save theme
                    int selectedSheetID = ValidationHelper.GetInteger(ctrlSiteSelectStyleSheet.Value, 0);
                    if (plcStyleSheetSelector.Visible)
                    {
                        if (group.GroupNodeGUID != Guid.Empty)
                        {
                            // Save theme for every site culture
                            var cultures = CultureSiteInfoProvider.GetSiteCultureCodes(SiteContext.CurrentSiteName);
                            if (cultures != null)
                            {
                                TreeProvider tree = new TreeProvider(MembershipContext.AuthenticatedUser);

                                // Return class name of selected tree node
                                TreeNode treeNode = tree.SelectSingleNode(group.GroupNodeGUID, TreeProvider.ALL_CULTURES, SiteContext.CurrentSiteName);
                                if (treeNode != null)
                                {
                                    // Return all culture version of node
                                    DataSet ds = tree.SelectNodes(SiteContext.CurrentSiteName, null, TreeProvider.ALL_CULTURES, false, treeNode.NodeClassName, "NodeGUID ='" + group.GroupNodeGUID + "'", String.Empty, -1, false);
                                    if (!DataHelper.DataSourceIsEmpty(ds))
                                    {
                                        // Loop through all nodes
                                        foreach (DataRow dr in ds.Tables[0].Rows)
                                        {
                                            // Create node and set tree provider for user validation
                                            TreeNode node = TreeNode.New(ValidationHelper.GetString(dr["className"], String.Empty), dr);
                                            node.TreeProvider = tree;

                                            // Update stylesheet id if set
                                            if (selectedSheetID == 0)
                                            {
                                                node.SetValue("DocumentStylesheetID", -1);
                                            }
                                            else
                                            {
                                                node.DocumentStylesheetID = selectedSheetID;
                                            }

                                            node.Update();
                                        }
                                    }
                                }
                            }
                        }
                    }

                    if (!IsLiveSite && (group.GroupNodeGUID != Guid.Empty))
                    {
                        plcStyleSheetSelector.Visible = true;
                    }

                    if (plcOnline.Visible)
                    {
                        // On-line marketing setting is visible => set flag according to checkbox
                        group.GroupLogActivity = chkLogActivity.Checked;
                    }
                    else
                    {
                        // On-line marketing setting is not visible => set flag to TRUE as default value
                        group.GroupLogActivity = true;
                    }

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

                    txtDisplayName.Text = group.GroupDisplayName;
                    txtCodeName.Text    = group.GroupName;

                    // Flush cached information
                    DocumentContext.CurrentDocument           = null;
                    DocumentContext.CurrentPageInfo           = null;
                    DocumentContext.CurrentDocumentStylesheet = null;

                    // Display information on success
                    ShowChangesSaved();

                    // If new group was created
                    if (newGroup)
                    {
                        GroupID = group.GroupID;
                        RaiseOnSaved();
                    }
                }
            }
            catch (Exception ex)
            {
                // Display error message
                ShowError(GetString("general.saveerror"), ex.Message, null);
            }
        }
        else
        {
            // Display error message
            ShowError(errorMessage);
        }
    }
    /// <summary>
    /// Initializes the control properties.
    /// </summary>
    protected void SetupControl()
    {
        if (StopProcessing)
        {
            // Do nothing
        }
        else
        {
            SetContext();

            GroupInfo group = CommunityContext.CurrentGroup;
            if (group != null)
            {
                string path = (GroupsSecurityAccessPath == "") ? GroupInfoProvider.GetGroupSecurityAccessPath(group.GroupName, CMSContext.CurrentSiteName) : GroupsSecurityAccessPath;
                string url  = URLHelper.ResolveUrl(TreePathUtils.GetUrl(CMSContext.ResolveCurrentPath(path)));
                if (UseQueryString)
                {
                    url = URLHelper.UpdateParameterInUrl(url, "groupid", group.GroupID.ToString());
                }

                // Check whether group is approved
                if (!group.GroupApproved)
                {
                    URLHelper.Redirect(url);
                }
                else
                {
                    // Check permissions for current user
                    switch (group.GroupAccess)
                    {
                    // Anybody can view the content
                    default:
                    case SecurityAccessEnum.AllUsers:
                        break;

                    // Site members can view the content
                    case SecurityAccessEnum.AuthenticatedUsers:
                        if (!CMSContext.CurrentUser.IsAuthenticated())
                        {
                            URLHelper.Redirect(url);
                        }
                        break;

                    // Only group members can view the content
                    case SecurityAccessEnum.GroupMembers:
                        if (!CMSContext.CurrentUser.IsGroupMember(group.GroupID))
                        {
                            URLHelper.Redirect(url);
                        }
                        break;
                    }
                }
            }
            else
            {
                Visible = false;
            }

            ReleaseContext();
        }
    }
Esempio n. 3
0
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Visible)
        {
            EnableViewState = false;
        }

        if (StopProcessing)
        {
            // Do nothing
            Visible = false;
            groupPictureEdit.StopProcessing = true;
            groupPageURLElem.StopProcessing = true;
        }
        else
        {
            string currSiteName = SiteContext.CurrentSiteName;
            plcGroupLocation.Visible             = DisplayAdvanceOptions;
            plcAdvanceOptions.Visible            = DisplayAdvanceOptions;
            groupPageURLElem.EnableSiteSelection = false;
            plcOnline.Visible = ActivitySettingsHelper.ActivitiesEnabledAndModuleLoaded(currSiteName);

            ctrlSiteSelectStyleSheet.CurrentSelector.ReturnColumnName = "StyleSheetID";
            ctrlSiteSelectStyleSheet.SiteId             = SiteContext.CurrentSiteID;
            ctrlSiteSelectStyleSheet.AllowEditButtons   = false;
            ctrlSiteSelectStyleSheet.IsLiveSite         = IsLiveSite;
            lblStyleSheetName.AssociatedControlClientID = ctrlSiteSelectStyleSheet.CurrentSelector.ClientID;

            // Is allow edit display name is set on live site
            if ((AllowChangeGroupDisplayName) && (IsLiveSite))
            {
                if (!plcAdvanceOptions.Visible)
                {
                    plcCodeName.Visible = false;
                }
                plcAdvanceOptions.Visible = true;
            }

            // Web parts theme selector visibility
            if ((!AllowSelectTheme) && (IsLiveSite))
            {
                plcStyleSheetSelector.Visible = false;
            }

            RaiseOnCheckPermissions(PERMISSION_READ, this);

            if (StopProcessing)
            {
                return;
            }

            if ((GroupID == 0) && HideWhenGroupIsNotSupplied)
            {
                Visible = false;
                return;
            }

            InitializeForm();

            gi = GroupInfoProvider.GetGroupInfo(GroupID);
            if (gi != null)
            {
                if (!RequestHelper.IsPostBack())
                {
                    // Handle existing Group editing - prepare the data
                    if (GroupID > 0)
                    {
                        HandleExistingGroup();
                    }
                }

                groupPictureEdit.GroupInfo = gi;

                // UI Tools theme selector visibility
                if ((!IsLiveSite) && (gi.GroupNodeGUID == Guid.Empty))
                {
                    plcStyleSheetSelector.Visible = false;
                }

                // Init theme selector
                if (plcStyleSheetSelector.Visible)
                {
                    if (!URLHelper.IsPostback())
                    {
                        TreeProvider tree = new TreeProvider(MembershipContext.AuthenticatedUser);
                        if (gi.GroupNodeGUID != Guid.Empty)
                        {
                            TreeNode node = tree.SelectSingleNode(gi.GroupNodeGUID, TreeProvider.ALL_CULTURES, SiteContext.CurrentSiteName);
                            if (node != null)
                            {
                                ctrlSiteSelectStyleSheet.Value = node.DocumentStylesheetID;
                            }
                        }
                    }
                }
            }
            else
            {
                plcStyleSheetSelector.Visible = false;
            }

            txtDescription.IsLiveSite   = IsLiveSite;
            groupPictureEdit.IsLiveSite = IsLiveSite;
            groupPageURLElem.IsLiveSite = IsLiveSite;
        }
    }
Esempio n. 4
0
        static void Main(string[] args)
        {
            ConfigurationManager config = ConfigurationManager.Instance.AddBaseUrl("http://*****:*****@no-replay.com",
            //    Password = "******"
            //};

            userInfoProvider.Get("kermit");
            GroupInfoProvider group = new GroupInfoProvider();
            var groups = group.GetAll();

            foreach (UserInfo member in groups[0].Members)
            {
                Console.WriteLine(member.FirstName);
            }
            //ModelInfo model = new ModelInfo
            //{
            //    TenantId = "tenant updated"
            //};

            //ModelInfoProvider prov = new ModelInfoProvider();
            //prov.Update("40",model);

            //Console.WriteLine(prov.Get("40").TenantId);

            Console.ReadLine();
        }
    /// <summary>
    /// Accepts invitation.
    /// </summary>
    protected void btnAccept_OnCommand(object sender, CommandEventArgs e)
    {
        if (e.CommandName == "accept")
        {
            // Accept
            int            invitationId = ValidationHelper.GetInteger(e.CommandArgument, 0);
            InvitationInfo invitation   = InvitationInfoProvider.GetInvitationInfo(invitationId);

            // Check if time is correct
            if ((invitation.InvitationValidTo == DateTimeHelper.ZERO_TIME) ||
                (invitation.InvitationValidTo >= DateTime.Now))
            {
                GroupInfo group = GroupInfoProvider.GetGroupInfo(invitation.InvitationGroupID);
                if (group != null)
                {
                    // Check if invitation is from group member
                    if (!GroupMemberInfoProvider.IsMemberOfGroup(invitation.InvitedUserID, invitation.InvitationGroupID))
                    {
                        // Transfer user name to user info
                        if (userInfo == null)
                        {
                            userInfo = UserInfoProvider.GetUserInfo(UserName);
                        }
                        if (userInfo != null)
                        {
                            // Create group member info object
                            GroupMemberInfo groupMember = new GroupMemberInfo();
                            groupMember.MemberInvitedByUserID = invitation.InvitedByUserID;
                            groupMember.MemberUserID          = userInfo.UserID;
                            groupMember.MemberGroupID         = invitation.InvitationGroupID;
                            groupMember.MemberJoined          = DateTime.Now;

                            // Set proper status depending on group settings
                            switch (group.GroupApproveMembers)
                            {
                            case GroupApproveMembersEnum.ApprovedCanJoin:
                                groupMember.MemberStatus = GroupMemberStatus.WaitingForApproval;
                                lblInfo.Text             = MemberWaiting.Replace("##GROUPNAME##", HTMLHelper.HTMLEncode(group.GroupDisplayName)) + "<br /><br />";
                                break;

                            default:
                                groupMember.MemberApprovedByUserID = invitation.InvitedByUserID;
                                groupMember.MemberApprovedWhen     = DateTime.Now;
                                groupMember.MemberStatus           = GroupMemberStatus.Approved;
                                lblInfo.Text = MemberJoined.Replace("##GROUPNAME##", HTMLHelper.HTMLEncode(group.GroupDisplayName)) + "<br /><br />";
                                break;
                            }
                            // Store info object to database
                            GroupMemberInfoProvider.SetGroupMemberInfo(groupMember);

                            // Delete all invitations to specified group for specified user
                            string whereCondition = "InvitationGroupID = " + invitation.InvitationGroupID + " AND (InvitedUserID=" + userInfo.UserID + ")";
                            InvitationInfoProvider.DeleteInvitations(whereCondition);
                        }
                    }
                    else
                    {
                        // Show error message and delete invitation
                        lblInfo.Text     = UserIsAlreadyMember.Replace("##GROUPNAME##", HTMLHelper.HTMLEncode(group.GroupDisplayName)) + "<br /><br />";
                        lblInfo.CssClass = "InvitationErrorLabel";
                        InvitationInfoProvider.DeleteInvitationInfo(invitation);
                    }
                }
                else
                {
                    // Show error message and delete invitation
                    lblInfo.Text     = GroupNoLongerExists + "<br /><br />";
                    lblInfo.CssClass = "InvitationErrorLabel";
                    InvitationInfoProvider.DeleteInvitationInfo(invitation);
                }
            }
            else
            {
                // Show error message and delete invitation
                lblInfo.Text     = InvitationIsNotValid + "<br /><br />";
                lblInfo.CssClass = "InvitationErrorLabel";
                InvitationInfoProvider.DeleteInvitationInfo(invitation);
            }

            lblInfo.Visible = true;
            BindData();
        }
    }
Esempio n. 6
0
    /// <summary>
    /// Updates the current Group or creates new if no GroupID is present.
    /// </summary>
    public void SaveData()
    {
        // Check banned IP
        if (!BannedIPInfoProvider.IsAllowed(SiteContext.CurrentSiteName, BanControlEnum.AllNonComplete))
        {
            ShowError(GetString("General.BannedIP"));
            return;
        }

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

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

        try
        {
            GroupInfo group = new GroupInfo();
            group.GroupDisplayName    = txtDisplayName.Text;
            group.GroupDescription    = txtDescription.Text;
            group.GroupAccess         = GetGroupAccess();
            group.GroupSiteID         = mSiteId;
            group.GroupApproveMembers = GetGroupApproveMembers();
            // Automatic code name can be set after display name + site id is set
            group.Generalized.EnsureCodeName();

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                // Send approval email to admin
                if (!String.IsNullOrEmpty(SendWaitingForApprovalEmailTo))
                {
                    var siteName = SiteContext.CurrentSiteName;

                    // Create the message
                    EmailTemplateInfo eti = EmailTemplateProvider.GetEmailTemplate("Groups.WaitingForApproval", siteName);
                    if (eti != null)
                    {
                        MacroResolver resolver = MacroContext.CurrentResolver;
                        resolver.SetAnonymousSourceData(group);
                        resolver.SetNamedSourceData("Group", group);

                        EmailMessage message = new EmailMessage
                        {
                            From       = SettingsKeyInfoProvider.GetValue(siteName + ".CMSSendEmailNotificationsFrom"),
                            Recipients = SendWaitingForApprovalEmailTo
                        };

                        // Send the message using email engine
                        EmailSender.SendEmailWithTemplateText(siteName, message, eti, resolver, false);
                    }
                }
            }
            else
            {
                string groupPath = SettingsKeyInfoProvider.GetValue(SiteContext.CurrentSiteName + ".CMSGroupProfilePath");
                string url       = String.Empty;

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

            // Hide form
            if (HideFormAfterRegistration)
            {
                plcForm.Visible = false;
            }
            else
            {
                ClearForm();
            }
        }
        catch (Exception ex)
        {
            // Display error message
            ShowError(GetString("general.saveerror"), ex.Message);
        }
    }
    /// <summary>
    /// Initializes the control properties.
    /// </summary>
    protected void SetupControl()
    {
        repLatestPosts.DataBindByDefault = false;
        pagerElem.PageControl            = repLatestPosts.ID;

        if (StopProcessing)
        {
            // Do nothing
        }
        else
        {
            SetContext();

            if (!String.IsNullOrEmpty(TransformationName))
            {
                // Basic control properties
                repLatestPosts.HideControlForZeroRows = HideControlForZeroRows;
                repLatestPosts.ZeroRowsText           = ZeroRowsText;

                // Check if Group name is set
                GroupInfo gi = null;
                if ((CommunityContext.CurrentGroup != null) && (GroupName.ToLowerCSafe() == CommunityContext.CurrentGroup.GroupName.ToLowerCSafe()))
                {
                    gi = CommunityContext.CurrentGroup;
                }
                else
                {
                    gi = GroupInfoProvider.GetGroupInfo(GroupName, CMSContext.CurrentSiteName);
                }

                if (gi != null)
                {
                    // Data source properties
                    forumDataSource.TopN              = SelectTopN;
                    forumDataSource.OrderBy           = OrderBy;
                    forumDataSource.CacheItemName     = CacheItemName;
                    forumDataSource.CacheDependencies = CacheDependencies;
                    forumDataSource.CacheMinutes      = CacheMinutes;
                    forumDataSource.SelectedColumns   = Columns;
                    forumDataSource.FilterName        = FilterName;


                    #region "Repeater template properties"

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

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

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

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

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

                    #endregion


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

                    // Set paging 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, false);
                    }

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

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

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

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

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

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

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

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

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

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

                    #endregion

                    // Data source settings
                    forumDataSource.WhereCondition   = WhereCondition;
                    forumDataSource.GroupID          = gi.GroupID;
                    forumDataSource.CheckPermissions = true;
                    forumDataSource.SiteName         = SiteName;
                    repLatestPosts.DataSource        = forumDataSource.DataSource;

                    if (!DataHelper.DataSourceIsEmpty(repLatestPosts.DataSource))
                    {
                        repLatestPosts.DataBind();
                    }
                }
                else
                {
                    // Do nothing
                    forumDataSource.StopProcessing = true;
                }
            }

            ReleaseContext();
        }
    }
Esempio n. 8
0
    /// <summary>
    /// Initializes the control properties.
    /// </summary>
    public void SetupControl()
    {
        if (StopProcessing)
        {
            // Do nothing
        }
        else
        {
            // Clear placeholder first
            plcHolder.Controls.Clear();

            // Group settings
            ForumDivider1.ForumLayout = ForumLayout;

            // Friendly URLs
            ForumDivider1.UseFriendlyURL       = UseFriendlyURL;
            ForumDivider1.FriendlyURLExtension = FriendlyURLExtension;
            ForumDivider1.FriendlyBaseURL      = FriendlyBaseURL;

            // Post options
            ForumDivider1.DisplayAttachmentImage     = DisplayAttachmentImage;
            ForumDivider1.AttachmentImageMaxSideSize = AttachmentImageMaxSideSize;
            ForumDivider1.EnableAvatars         = EnableAvatars;
            ForumDivider1.AvatarMaxSideSize     = AvatarMaxSideSize;
            ForumDivider1.ViewMode              = ThreadViewMode;
            ForumDivider1.EnableFavorites       = EnableFavorites;
            ForumDivider1.EnableSignature       = EnableSignature;
            ForumDivider1.MaxRelativeLevel      = MaxRelativeLevel;
            ForumDivider1.DisplayBadgeInfo      = DisplayBadgeInfo;
            ForumDivider1.RedirectToUserProfile = RedirectToUserProfile;
            ForumDivider1.BaseURL           = BaseURL;
            ForumDivider1.UnsubscriptionURL = UnsubscriptionURL;
            ForumDivider1.EnableFriendship  = EnableFriendship && UIHelper.IsFriendsModuleEnabled(SiteContext.CurrentSiteName);
            ForumDivider1.EnableMessaging   = EnableMessaging;

            // Behaviour
            ForumDivider1.EnableSubscription       = EnableSubscription;
            ForumDivider1.EnableOnSiteManagement   = OnSiteManagement;
            ForumDivider1.HideForumForUnauthorized = HideForumForUnauthorized;
            ForumDivider1.RedirectUnauthorized     = RedirectUnauthorized;
            ForumDivider1.LogonPageURL             = LogonPageURL;
            ForumDivider1.AccessDeniedPageURL      = AccessDeniedPageURL;

            // Abuse report
            ForumDivider1.AbuseReportAccess = AbuseReportAccess;
            ForumDivider1.AbuseReportRoles  = AbuseReportRoles;

            //Paging
            ForumDivider1.EnableThreadPaging = EnableThreadPaging;
            ForumDivider1.ThreadPageSize     = ThreadPageSize;
            ForumDivider1.EnablePostsPaging  = EnablePostsPaging;
            ForumDivider1.PostsPageSize      = PostsPageSize;

            // Tree forum properties
            ForumDivider1.ShowMode   = ShowMode;
            ForumDivider1.ExpandTree = ExpandTree;

            if (CommunityContext.CurrentGroup != null)
            {
                ForumDivider1.CommunityGroupID = CommunityContext.CurrentGroup.GroupID;
            }

            if (UseUpdatePanel)
            {
                ForumDivider1.UseRedirectAfterAction = false;
            }

            string    path = ResolveUrl("~/CMSModules/Forums/Controls/ForumDivider.ascx");
            GroupInfo gi   = GroupInfoProvider.GetGroupInfo(GroupName, SiteContext.CurrentSiteName);
            if (gi != null)
            {
                var innerQuery = new ObjectQuery <ForumInfo>().WhereEquals("ForumOpen", 1).WhereEquals("ForumGroupID", new QueryColumn("GroupID")).Column(new CountColumn("ForumID"));

                forumGroups = ForumGroupInfoProvider.GetForumGroups()
                              .WhereEquals("GroupGroupID", gi.GroupID)
                              .WhereGreaterThan(innerQuery, 0)
                              .OrderBy("GroupOrder");
                if (!DataHelper.DataSourceIsEmpty(forumGroups))
                {
                    int  ctrlId   = 0;
                    bool wasAdded = false;

                    // Load all the groups
                    foreach (DataRow dr in forumGroups.Tables[0].Rows)
                    {
                        Control ctrl = LoadUserControl(path);
                        if (ctrl != null)
                        {
                            ctrl.ID = "groupElem" + ctrlId;
                            ForumViewer frmv = ctrl as ForumViewer;
                            if (frmv != null)
                            {
                                // Copy values
                                ForumDivider1.CopyValues(frmv);
                                if (wasAdded && !String.IsNullOrEmpty(GroupsSeparator))
                                {
                                    plcHolder.Controls.Add(new LiteralControl(GroupsSeparator));
                                }

                                frmv.GroupID = ValidationHelper.GetInteger(dr["GroupID"], 0);
                                plcHolder.Controls.Add(frmv);
                                wasAdded = true;
                            }
                        }

                        ctrlId++;
                    }
                }
            }
        }
    }
Esempio n. 9
0
    /// <summary>
    /// Initializes the control properties.
    /// </summary>
    protected void SetupControl()
    {
        if (StopProcessing)
        {
            // Do nothing
        }
        else
        {
            GroupInfo group = null;

            // Try to get group information from query string
            int groupId = QueryHelper.GetInteger("groupid", 0);
            group = (groupId > 0) ? GroupInfoProvider.GetGroupInfo(groupId) : CommunityContext.CurrentGroup;

            if (group != null)
            {
                // Check whether group is approved
                if (!group.GroupApproved)
                {
                    lblAccessInfo.Text = GetString("group.groupnotavailable");
                }
                else
                {
                    // Check permissions for current user
                    switch (group.GroupAccess)
                    {
                    // Anybody can view the content
                    default:
                    case SecurityAccessEnum.AllUsers:
                        // If content for selected group is available for all users redirect back to group page
                        RedirectToGroupPage(group);
                        break;

                    // Site members can view the content
                    case SecurityAccessEnum.AuthenticatedUsers:
                        if (!AuthenticationHelper.IsAuthenticated())
                        {
                            lblAccessInfo.Text = String.Format(SiteMembersOnlyText, "<a title=\"Sign in\" href=\"" + URLHelper.UpdateParameterInUrl(LoginURL, "returnurl", HTMLHelper.EncodeForHtmlAttribute(RequestContext.CurrentURL)) + "\">", "</a>");
                        }
                        else
                        {
                            RedirectToGroupPage(group);
                        }
                        break;

                    // Only group members can view the content
                    case SecurityAccessEnum.GroupMembers:
                        if (!MembershipContext.AuthenticatedUser.IsGroupMember(group.GroupID))
                        {
                            // If current user is public show text with sign in link
                            if (!AuthenticationHelper.IsAuthenticated())
                            {
                                lblAccessInfo.Text = String.Format(GroupMembersOnlyText, "<a title=\"Sign in\" href=\"" + URLHelper.UpdateParameterInUrl(LoginURL, "returnurl", HTMLHelper.EncodeForHtmlAttribute(RequestContext.CurrentURL)) + "\">", "</a>");
                            }
                            else
                            {
                                // For authenticate users display text with join the group text
                                string link = string.Empty;

                                // If join group path is defined use it, otherwise display join the group dialog
                                if (String.IsNullOrEmpty(JoinGroupPath))
                                {
                                    // Register the dialog script
                                    ScriptHelper.RegisterDialogScript(Page);

                                    string script = ScriptHelper.GetScript("function JoinToGroupAccessRequest() {\n" +
                                                                           "modalDialog('" + ApplicationUrlHelper.ResolveDialogUrl("~/CMSModules/Groups/CMSPages/JoinTheGroup.aspx") + "?groupid=" + group.GroupID + "','requestJoinToGroup', 500, 180); \n" +
                                                                           " } \n");
                                    ScriptHelper.RegisterClientScriptBlock(this, typeof(string), "JoinToGroupAccessRequest", script);

                                    link = "<a title=\"" + GetString("group.joingroup") + "\" href=\"" + HTMLHelper.EncodeForHtmlAttribute(RequestContext.CurrentURL) + "\" onclick=\"JoinToGroupAccessRequest(); return false;\">";
                                }
                                else
                                {
                                    link = "<a title=\"" + GetString("group.joingroup") + "\" href=\"" + JoinGroupPath + "\">";
                                }

                                lblAccessInfo.Text = String.Format(GroupMembersOnlyAuthenticatedText, link, "</a>");
                            }
                        }
                        else
                        {
                            RedirectToGroupPage(group);
                        }
                        break;
                    }
                }
            }
            else
            {
                Visible = false;
            }
        }
    }
Esempio n. 10
0
    /// <summary>
    /// Initializes the control properties.
    /// </summary>
    protected void SetupControl()
    {
        repLibraries.DataBindByDefault = false;
        pagerElem.PageControl          = repLibraries.ID;

        if (StopProcessing)
        {
            // Do nothing
        }
        else
        {
            // Basic control properties
            repLibraries.HideControlForZeroRows = HideControlForZeroRows;
            repLibraries.ZeroRowsText           = ZeroRowsText;

            // Data source properties
            srcLib.WhereCondition    = WhereCondition;
            srcLib.OrderBy           = OrderBy;
            srcLib.TopN              = SelectTopN;
            srcLib.CacheItemName     = CacheItemName;
            srcLib.CacheDependencies = CacheDependencies;
            srcLib.CacheMinutes      = CacheMinutes;
            srcLib.SelectedColumns   = Columns;
            srcLib.SiteName          = SiteName;

            // Set group ID
            srcLib.GroupID = -1;
            if (!string.IsNullOrEmpty(GroupName))
            {
                GroupInfo gi = GroupInfoProvider.GetGroupInfo(GroupName, (String.IsNullOrEmpty(SiteName) ? SiteContext.CurrentSiteName : SiteName));
                if (gi != null)
                {
                    srcLib.GroupID = gi.GroupID;
                }
            }


            #region "Repeater template properties"

            // Apply transformations if they exist
            if (!String.IsNullOrEmpty(TransformationName))
            {
                repLibraries.ItemTemplate = CMSDataProperties.LoadTransformation(this, TransformationName);
            }
            if (!String.IsNullOrEmpty(AlternatingItemTransformationName))
            {
                repLibraries.AlternatingItemTemplate = CMSDataProperties.LoadTransformation(this, AlternatingItemTransformationName);
            }
            if (!String.IsNullOrEmpty(FooterTransformationName))
            {
                repLibraries.FooterTemplate = CMSDataProperties.LoadTransformation(this, FooterTransformationName);
            }
            if (!String.IsNullOrEmpty(HeaderTransformationName))
            {
                repLibraries.HeaderTemplate = CMSDataProperties.LoadTransformation(this, HeaderTransformationName);
            }
            if (!String.IsNullOrEmpty(SeparatorTransformationName))
            {
                repLibraries.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;

            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);
            }

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

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

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

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

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

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

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

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

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

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

            #endregion


            // Connects repeater with data source
            repLibraries.DataSource = srcLib.DataSource;
        }

        pagerElem.RebindPager();
        repLibraries.DataBind();
    }
Esempio n. 11
0
    /// <summary>
    /// Updates picture of current group.
    /// </summary>
    /// <param name="gi">Group info object</param>
    public void UpdateGroupPicture(GroupInfo gi)
    {
        AvatarInfo ai = null;

        if (gi != null)
        {
            // Delete avatar if needed
            if (hiddenDeleteAvatar.Value == "true")
            {
                DeleteOldGroupPicture(gi);
            }

            // If some file was uploaded
            if ((uplFilePicture.PostedFile != null) && (uplFilePicture.PostedFile.ContentLength > 0) && ImageHelper.IsImage(Path.GetExtension(uplFilePicture.PostedFile.FileName)))
            {
                // Check if this grou[ has some avatar and if so check if is custom
                ai = AvatarInfoProvider.GetAvatarInfoWithoutBinary(gi.GroupAvatarID);
                bool isCustom = false;
                if ((ai != null) && ai.AvatarIsCustom)
                {
                    isCustom = true;
                }

                if (isCustom)
                {
                    AvatarInfoProvider.UploadAvatar(ai, uplFilePicture.PostedFile,
                                                    SettingsKeyProvider.GetIntValue(site.SiteName + ".CMSGroupAvatarWidth"),
                                                    SettingsKeyProvider.GetIntValue(site.SiteName + ".CMSGroupAvatarHeight"),
                                                    SettingsKeyProvider.GetIntValue(site.SiteName + ".CMSGroupAvatarMaxSideSize"));
                }
                else
                {
                    // Delete old picture
                    DeleteOldGroupPicture(gi);

                    ai = new AvatarInfo(uplFilePicture.PostedFile,
                                        SettingsKeyProvider.GetIntValue(site.SiteName + ".CMSGroupAvatarWidth"),
                                        SettingsKeyProvider.GetIntValue(site.SiteName + ".CMSGroupAvatarHeight"),
                                        SettingsKeyProvider.GetIntValue(site.SiteName + ".CMSGroupAvatarMaxSideSize"));

                    ai.AvatarName     = AvatarInfoProvider.GetUniqueAvatarName(GetString("avat.custom") + " " + gi.GroupName);
                    ai.AvatarType     = AvatarTypeEnum.Group.ToString();
                    ai.AvatarIsCustom = true;
                    ai.AvatarGUID     = Guid.NewGuid();
                }

                AvatarInfoProvider.SetAvatarInfo(ai);

                // Update group info
                gi.GroupAvatarID = ai.AvatarID;
                GroupInfoProvider.SetGroupInfo(gi);

                plcImageActions.Visible = true;
            }
            // If predefined was chosen
            else if (!string.IsNullOrEmpty(hiddenAvatarGuid.Value))
            {
                // Delete old picture
                DeleteOldGroupPicture(gi);

                Guid guid = ValidationHelper.GetGuid(hiddenAvatarGuid.Value, Guid.NewGuid());
                ai = AvatarInfoProvider.GetAvatarInfoWithoutBinary(guid);

                // Update group info
                if (ai != null)
                {
                    gi.GroupAvatarID = ai.AvatarID;
                    GroupInfoProvider.SetGroupInfo(gi);
                }

                plcImageActions.Visible = true;
            }
            else
            {
                plcImageActions.Visible = false;
            }
        }
    }
Esempio n. 12
0
    /// <summary>
    /// Updates the current Group or creates new if no GroupID is present.
    /// </summary>
    public void SaveData()
    {
        // Check banned ip
        if (!BannedIPInfoProvider.IsAllowed(CMSContext.CurrentSiteName, BanControlEnum.AllNonComplete))
        {
            lblError.Visible = true;
            lblError.Text    = GetString("General.BannedIP");
            return;
        }

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

        if (errorMessage == "")
        {
            try
            {
                codeName = GetSafeCodeName();
                codeName = GetUniqueCodeName(codeName);

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

                // Set columns GroupCreatedByUserID and GroupApprovedByUserID to current user
                CurrentUserInfo user = CMSContext.CurrentUser;

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

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

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

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

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

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

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

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

                // Clear user session a request
                CMSContext.CurrentUser.Invalidate();
                CMSContext.CurrentUser = null;

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

                // Copy document
                errorMessage = GroupInfoProvider.CopyGroupDocument(group, CMSContext.ResolveCurrentPath(GroupTemplateSourceAliasPath), CMSContext.ResolveCurrentPath(GroupTemplateTargetAliasPath), GroupProfileURLPath, culture, this.CombineWithDefaultCulture, CMSContext.CurrentUser, roleInfo);

                if (errorMessage != "")
                {
                    // Display error message
                    this.lblError.Text    = errorMessage;
                    this.lblError.Visible = true;
                    return;
                }

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

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

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

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

                // Display information on success
                this.lblInfo.Text    = GetString("group.group.createdinfo");
                this.lblInfo.Visible = true;

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

                // After registration message
                if ((this.RequireApproval) && (!CurrentUserIsAdmin()))
                {
                    this.lblInfo.Text = this.SuccessfullRegistrationWaitingForApprovalText;

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

                            MacroResolver resolver = CMSContext.CurrentResolver;
                            resolver.SourceData = new object[] { group };
                            resolver.SetNamedSourceData("Group", group);

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

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

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

                    if (!String.IsNullOrEmpty(groupPath))
                    {
                        url = TreePathUtils.GetUrl(groupPath.Replace("{GroupName}", group.GroupName));
                    }
                    this.lblInfo.Text = String.Format(this.SuccessfullRegistrationText, url);
                }

                // Hide form
                if (this.HideFormAfterRegistration)
                {
                    this.plcForm.Visible = false;
                }
                else
                {
                    ClearForm();
                }
            }
            catch (Exception ex)
            {
                // Display error message
                this.lblError.Text    = GetString("general.erroroccurred") + ex.Message;
                this.lblError.Visible = true;
            }
        }
        else
        {
            // Display error message
            this.lblError.Text    = errorMessage;
            this.lblError.Visible = true;
        }
    }
Esempio n. 13
0
    protected void Page_Load(object sender, EventArgs e)
    {
        // Get the group ID and the group InfoObject
        groupId = QueryHelper.GetInteger("groupid", 0);
        GroupInfo gi = GroupInfoProvider.GetGroupInfo(groupId);

        if (gi != null)
        {
            groupDisplayName = HTMLHelper.HTMLEncode(gi.GroupDisplayName);
        }

        // Page title
        CurrentMaster.Title.TitleText  = GetString("Group.EditHeaderCaption");
        CurrentMaster.Title.TitleImage = GetImageUrl("Objects/Community_Group/object.png");

        CurrentMaster.Title.HelpTopicName = "group_general";
        CurrentMaster.Title.HelpName      = "helpTopic";

        // Pagetitle breadcrumbs
        string[,] pageTitleTabs         = new string[2, 3];
        pageTitleTabs[0, 0]             = GetString("Group.ItemListLink");
        pageTitleTabs[0, 1]             = "~/CMSModules/Groups/Tools/Group_List.aspx";
        pageTitleTabs[0, 2]             = "_parent";
        pageTitleTabs[1, 0]             = groupDisplayName;
        pageTitleTabs[1, 1]             = "";
        pageTitleTabs[1, 2]             = "";
        CurrentMaster.Title.Breadcrumbs = pageTitleTabs;

        // Tabs
        string[,] tabs = new string[10, 4];

        // General
        tabs[0, 0] = GetString("General.General");
        tabs[0, 1] = "SetHelpTopic('helpTopic', 'group_general');";
        tabs[0, 2] = "Group_Edit_General.aspx?groupID=" + groupId;

        // Custom fields
        FormInfo formInfo = FormHelper.GetFormInfo(PredefinedObjectType.GROUP, false);

        if ((formInfo != null) && formInfo.GetFormElements(true, false, true).Any())
        {
            tabs[1, 0] = GetString("general.customfields");
            tabs[1, 2] = "Group_Edit_CustomFields.aspx?groupID=" + groupId;
        }

        // Security
        tabs[2, 0] = GetString("General.Security");
        tabs[2, 1] = "SetHelpTopic('helpTopic', 'group_security');";
        tabs[2, 2] = "Security/Security.aspx?groupID=" + groupId;

        // Members
        tabs[3, 0] = GetString("Group.Members");
        tabs[3, 1] = "SetHelpTopic('helpTopic', 'group_members_list');";
        tabs[3, 2] = "Members/Member_List.aspx?groupID=" + groupId;

        if (ResourceSiteInfoProvider.IsResourceOnSite("CMS.Roles", SiteContext.CurrentSiteName))
        {
            tabs[4, 0] = GetString("general.roles");
            tabs[4, 1] = "SetHelpTopic('helpTopic', 'group_roles_list');";
            tabs[4, 2] = "Roles/Role_List.aspx?groupID=" + groupId;
        }

        if (ResourceSiteInfoProvider.IsResourceOnSite("CMS.Forums", SiteContext.CurrentSiteName))
        {
            tabs[5, 0] = GetString("group_general.forums");
            tabs[5, 1] = "SetHelpTopic('helpTopic', 'forum_list');";
            tabs[5, 2] = "Forums/Groups/ForumGroups_List.aspx?groupid=" + groupId;
        }

        if (ResourceSiteInfoProvider.IsResourceOnSite("CMS.MediaLibrary", SiteContext.CurrentSiteName))
        {
            tabs[6, 0] = GetString("Group.MediaLibrary");
            tabs[6, 1] = "SetHelpTopic('helpTopic', 'library_list');";
            tabs[6, 2] = "MediaLibrary/Library_List.aspx?groupid=" + groupId;
        }

        if (ResourceSiteInfoProvider.IsResourceOnSite("CMS.MessageBoards", SiteContext.CurrentSiteName))
        {
            tabs[7, 0] = GetString("Group.MessageBoards");
            tabs[7, 1] = "SetHelpTopic('helpTopic', 'group_messageboard');";
            tabs[7, 2] = "MessageBoards/Boards_Default.aspx?groupid=" + groupId;
        }

        if (ResourceSiteInfoProvider.IsResourceOnSite("CMS.Polls", SiteContext.CurrentSiteName))
        {
            tabs[8, 0] = GetString("Group.Polls");
            tabs[8, 1] = "SetHelpTopic('helpTopic', 'polls_list');";
            tabs[8, 2] = "Polls/Polls_List.aspx?groupID=" + groupId;
        }

        // Check whether license for project management is avilable
        // if no hide project management tab
        if (LicenseHelper.CheckFeature(URLHelper.GetCurrentDomain(), FeatureEnum.ProjectManagement))
        {
            // Check site availability
            if (ResourceSiteInfoProvider.IsResourceOnSite("CMS.ProjectManagement", SiteContext.CurrentSiteName))
            {
                tabs[9, 0] = ResHelper.GetString("pm.project.list");
                tabs[9, 1] = "SetHelpTopic('helpTopic', 'CMS_ProjectManagement_Projects');";
                tabs[9, 2] = "ProjectManagement/Project/List.aspx?groupid=" + groupId;
            }
        }

        CurrentMaster.Tabs.Tabs      = tabs;
        CurrentMaster.Tabs.UrlTarget = "content";
    }
Esempio n. 14
0
    /// <summary>
    /// Invite button handling.
    /// </summary>
    /// <param name="sender">Sender</param>
    /// <param name="e">EventArgs</param>
    protected void btnInvite_Click(object sender, EventArgs e)
    {
        if (!IsLiveSite)
        {
            if (!CheckPermissions("cms.groups", CMSAdminControl.PERMISSION_MANAGE, this.GroupID))
            {
                return;
            }
        }

        if (DisplayGroupSelector)
        {
            GroupID = ValidationHelper.GetInteger(groupSelector.Value, 0);
        }

        Group = GroupInfoProvider.GetGroupInfo(GroupID);
        string recipientEmail = string.Empty;

        if (Group != null)
        {
            // Check whether user is group member
            if (CMSContext.CurrentUser.IsGroupMember(GroupID))
            {
                // If user can select the user
                if (plcUserSelector.Visible)
                {
                    int userId = ValidationHelper.GetInteger(userSelector.Value, 0);
                    if (userId > 0)
                    {
                        InvitedUser = UserInfoProvider.GetUserInfo(userId);

                        bool userNotFound = true;

                        // Check if user is filtered
                        if (InvitedUser != null)
                        {
                            if (this.IsLiveSite)
                            {
                                userNotFound = InvitedUser.UserIsHidden || !InvitedUser.UserEnabled;
                            }
                            else
                            {
                                userNotFound = false;
                            }
                        }

                        if (!userNotFound)
                        {
                            // Create invitation info
                            InvitationInfo ii = InviteUser(Group, InvitedUser);
                            if (ii != null)
                            {
                                // Send e-mail
                                InvitationInfoProvider.SendInvitationEmail(ii, CMSContext.CurrentSiteName);
                            }
                            else
                            {
                                // User is member
                                GroupMemberInfo gmi = GroupMemberInfoProvider.GetGroupMemberInfo(InvitedUser.UserID, GroupID);
                                if (gmi != null)
                                {
                                    lblError.Text    = GetString("groupinvitation.invitationunsuccessismember").Replace("##GROUPNAME##", HTMLHelper.HTMLEncode(Group.GroupDisplayName)).Replace("##USERNAME##", HTMLHelper.HTMLEncode(Functions.GetFormattedUserName(InvitedUser.UserName, this.IsLiveSite)));
                                    lblError.Visible = true;
                                    return;
                                }

                                // User is invited
                                DataSet ds = InvitationInfoProvider.GetInvitations("InvitedUserID=" + InvitedUser.UserID + " AND InvitationGroupID=" + GroupID, "InvitationCreated", 1);
                                if (!DataHelper.DataSourceIsEmpty(ds))
                                {
                                    int      invitedByuserId = ValidationHelper.GetInteger(ds.Tables[0].Rows[0]["InvitedByUserID"], 0);
                                    UserInfo ui = UserInfoProvider.GetUserInfo(invitedByuserId);
                                    if (ui != null)
                                    {
                                        lblError.Text    = GetString("groupinvitation.invitationunsuccesinvexists").Replace("##GROUPNAME##", HTMLHelper.HTMLEncode(Group.GroupDisplayName)).Replace("##USERNAME##", HTMLHelper.HTMLEncode(InvitedUser.UserName)).Replace("##INVITEDBY##", HTMLHelper.HTMLEncode(Functions.GetFormattedUserName(ui.UserName, this.IsLiveSite)));
                                        lblError.Visible = true;
                                    }
                                    return;
                                }

                                // General error
                                lblError.Text    = GetString("groupinvitation.invitationunsuccessmult").Replace("##GROUPNAME##", HTMLHelper.HTMLEncode(Group.GroupDisplayName)).Replace("##USERNAME##", HTMLHelper.HTMLEncode(Functions.GetFormattedUserName(InvitedUser.UserName, this.IsLiveSite)));
                                lblError.Visible = true;
                                return;
                            }
                        }
                        else
                        {
                            lblError.Text    = GetString("general.usernotfound");
                            lblError.Visible = true;
                            return;
                        }
                    }
                    else
                    {
                        lblError.Text    = GetString("groupinvitation.emptyusers");
                        lblError.Visible = true;
                        return;
                    }

                    // Succesfull invitation
                    lblInfo.Text    = SuccessfulInviteText;
                    lblInfo.Visible = true;

                    DisableAfterSuccess();

                    if (DisplayAdvancedOptions)
                    {
                        CancelButton.ResourceString = "general.back";
                        CancelButton.PostBackUrl    =
                            ResolveUrl("~/CMSModules/Groups/Tools/Members/Member_List.aspx?groupId=" + GroupID);
                    }
                    else
                    {
                        CancelButton.ResourceString = "general.close";
                        CancelButton.OnClientClick  = "Close();";
                    }
                }
                // Single invite
                else
                {
                    // Check the email address if it is new user
                    if (radNewUser.Checked)
                    {
                        string result = new Validator().IsEmail(txtEmail.Text, rfvEmail.ErrorMessage).Result;
                        if (result != String.Empty)
                        {
                            lblError.Text    = result;
                            lblError.Visible = true;
                            return;
                        }
                    }

                    InvitedUser = UserInfoProvider.GetUserInfo(InvitedUserID);

                    if ((GroupID != 0) || (InvitedUser != null) || (radNewUser.Checked))
                    {
                        // Create invitation info
                        InvitationInfo ii = InviteUser(Group, InvitedUser);

                        if (ii != null)
                        {
                            lblInfo.Text = SuccessfulInviteText;
                            DisableAfterSuccess();
                            if (DisplayAdvancedOptions)
                            {
                                CancelButton.ResourceString = "general.back";
                                CancelButton.PostBackUrl    =
                                    ResolveUrl("~/CMSModules/Groups/Tools/Members/Member_List.aspx?groupId=" + GroupID);
                            }
                            else
                            {
                                CancelButton.ResourceString = "general.close";
                                if (UseMultipleUserSelector)
                                {
                                    CancelButton.OnClientClick = "Close();";
                                }
                                else
                                {
                                    CancelButton.OnClientClick = "CloseAndRefresh();";
                                }
                            }

                            InvitationInfoProvider.SendInvitationEmail(ii, CMSContext.CurrentSiteName);

                            // Succesfull invitation
                            lblInfo.Text    = SuccessfulInviteText;
                            lblInfo.Visible = true;
                        }
                        else
                        {
                            if (InvitedUser != null)
                            {
                                string username = HTMLHelper.HTMLEncode(Functions.GetFormattedUserName(InvitedUser.UserName, this.IsLiveSite));

                                // User is member
                                GroupMemberInfo gmi = GroupMemberInfoProvider.GetGroupMemberInfo(InvitedUser.UserID, GroupID);
                                if (gmi != null)
                                {
                                    lblError.Text    = GetString("groupinvitation.invitationunsuccessismember").Replace("##GROUPNAME##", HTMLHelper.HTMLEncode(Group.GroupDisplayName)).Replace("##USERNAME##", username);
                                    lblError.Visible = true;
                                    return;
                                }

                                // User is invited
                                DataSet ds = InvitationInfoProvider.GetInvitations("InvitedUserID=" + InvitedUser.UserID + " AND InvitationGroupID=" + GroupID, "InvitationCreated", 1);
                                if (!DataHelper.DataSourceIsEmpty(ds))
                                {
                                    int      invitedByuserId = ValidationHelper.GetInteger(ds.Tables[0].Rows[0]["InvitedByUserID"], 0);
                                    UserInfo ui = UserInfoProvider.GetUserInfo(invitedByuserId);
                                    if (ui != null)
                                    {
                                        lblError.Text    = GetString("groupinvitation.invitationunsuccesinvexists").Replace("##GROUPNAME##", HTMLHelper.HTMLEncode(Group.GroupDisplayName)).Replace("##USERNAME##", username).Replace("##INVITEDBY##", HTMLHelper.HTMLEncode(Functions.GetFormattedUserName(ui.UserName, this.IsLiveSite)));
                                        lblError.Visible = true;
                                    }
                                    return;
                                }

                                // General error
                                lblError.Text    = GetString("groupinvitation.invitationunsuccessmult").Replace("##GROUPNAME##", HTMLHelper.HTMLEncode(Group.GroupDisplayName)).Replace("##USERNAME##", username);
                                lblError.Visible = true;
                                return;
                            }
                            else
                            {
                                UnSuccess();
                            }
                        }
                    }
                    else
                    {
                        UnSuccess();
                    }
                }
            }
        }
    }
Esempio n. 15
0
    /// <summary>
    /// Generates the permission matrix for the current group.
    /// </summary>
    private void CreateMatrix()
    {
        // Get group resource info
        if (resGroups == null)
        {
            resGroups = ResourceInfoProvider.GetResourceInfo("CMS.Groups");
        }

        if (resGroups != null)
        {
            group = GroupInfoProvider.GetGroupInfo(GroupID);

            // Get permissions for the current group resource
            DataSet permissions = PermissionNameInfoProvider.GetResourcePermissions(resGroups.ResourceId);
            if (DataHelper.DataSourceIsEmpty(permissions))
            {
                ShowInformation(GetString("general.emptymatrix"));
            }
            else
            {
                TableRow headerRow = new TableRow();
                headerRow.CssClass = "UniGridHead";
                TableCell       newCell       = new TableCell();
                TableHeaderCell newHeaderCell = new TableHeaderCell();

                newHeaderCell.Text                = "&nbsp;";
                newHeaderCell.CssClass            = "MatrixHeader";
                newHeaderCell.Attributes["style"] = "width:30%;";
                headerRow.Cells.Add(newHeaderCell);

                foreach (string permission in allowedPermissions)
                {
                    DataRow[] drArray = permissions.Tables[0].DefaultView.Table.Select("PermissionName = '" + permission + "'");
                    if ((drArray != null) && (drArray.Length > 0))
                    {
                        DataRow dr = drArray[0];
                        newHeaderCell                     = new TableHeaderCell();
                        newHeaderCell.CssClass            = "MatrixHeader";
                        newHeaderCell.Attributes["style"] = "width:18%;text-align:center;white-space:nowrap;";
                        newHeaderCell.Text                = dr["PermissionDisplayName"].ToString();
                        newHeaderCell.ToolTip             = dr["PermissionDescription"].ToString();
                        newHeaderCell.HorizontalAlign     = HorizontalAlign.Center;

                        headerRow.Cells.Add(newHeaderCell);
                    }
                    else
                    {
                        throw new Exception("[Security matrix] Column '" + permission + "' cannot be found.");
                    }
                }
                // Insert the empty cell at the end
                newHeaderCell      = new TableHeaderCell();
                newHeaderCell.Text = "&nbsp;";
                headerRow.Cells.Add(newHeaderCell);
                tblMatrix.Rows.Add(headerRow);

                // Render group access permissions
                object[,] accessNames = new object[5, 2];
                accessNames[0, 0]     = GetString("security.nobody");
                accessNames[0, 1]     = SecurityAccessEnum.Nobody;
                accessNames[1, 0]     = GetString("security.allusers");
                accessNames[1, 1]     = SecurityAccessEnum.AllUsers;
                accessNames[2, 0]     = GetString("security.authenticated");
                accessNames[2, 1]     = SecurityAccessEnum.AuthenticatedUsers;
                accessNames[3, 0]     = GetString("security.groupmembers");
                accessNames[3, 1]     = SecurityAccessEnum.GroupMembers;
                accessNames[4, 0]     = GetString("security.authorizedroles");
                accessNames[4, 1]     = SecurityAccessEnum.AuthorizedRoles;

                TableRow newRow   = null;
                int      rowIndex = 0;

                for (int access = 0; access <= accessNames.GetUpperBound(0); access++)
                {
                    SecurityAccessEnum currentAccess = ((SecurityAccessEnum)accessNames[access, 1]);

                    // Generate cell holding access item name
                    newRow           = new TableRow();
                    newRow.CssClass  = ((rowIndex % 2 == 0) ? "EvenRow" : "OddRow");
                    newCell          = new TableCell();
                    newCell.CssClass = "MatrixHeader";
                    newCell.Text     = accessNames[access, 0].ToString();
                    newCell.Wrap     = false;
                    newRow.Cells.Add(newCell);
                    rowIndex++;

                    // Render the permissions access items
                    bool isAllowed       = false;
                    int  permissionIndex = 0;
                    for (int permission = 0; permission < (tblMatrix.Rows[0].Cells.Count - 2); permission++)
                    {
                        newCell                 = new TableCell();
                        newCell.CssClass        = "MatrixCell";
                        newCell.HorizontalAlign = HorizontalAlign.Center;

                        // Check if the currently processed access is applied for permission
                        isAllowed = CheckPermissionAccess(currentAccess, permission, tblMatrix.Rows[0].Cells[permission + 1].Text);

                        // Disable column in roles grid if needed
                        if ((currentAccess == SecurityAccessEnum.AuthorizedRoles) && !isAllowed)
                        {
                            gridMatrix.DisableColumn(permissionIndex);
                        }

                        // Insert the radio button for the current permission
                        string permissionText = tblMatrix.Rows[0].Cells[permission + 1].Text;
                        string elemId         = ClientID + "_" + permission + "_" + access;
                        string disabled       = null;
                        if (!Enabled)
                        {
                            disabled = "disabled=\"disabled\"";
                        }
                        newCell.Text = "<label style=\"display:none;\" for=\"" + elemId + "\">" + permissionText + "</label><input type=\"radio\" id=\"" + elemId + "\" name=\"" + permissionText + "\" " + disabled + " onclick=\"" +
                                       ControlsHelper.GetPostBackEventReference(this, permission.ToString() + ";" + Convert.ToInt32(currentAccess).ToString()) + "\" " +
                                       ((isAllowed) ? "checked = \"checked\"" : "") + "/>";

                        newCell.Wrap = false;
                        newRow.Cells.Add(newCell);
                        permissionIndex++;
                    }

                    newCell      = new TableCell();
                    newCell.Text = "&nbsp;";
                    newRow.Cells.Add(newCell);
                    // Add the access row to the table
                    tblMatrix.Rows.Add(newRow);
                }

                // Get permission matrix for current group resource
                bool rowIsSeparator = false;

                // Get permission matrix for the current group resource
                mNoRolesAvailable = !gridMatrix.HasData;

                if (!mNoRolesAvailable)
                {
                    // Security - Role separator
                    newRow       = new TableRow();
                    newCell      = new TableCell();
                    newCell.Text = "&nbsp;";
                    newCell.Attributes.Add("colspan", Convert.ToString(tblMatrix.Rows[0].Cells.Count));
                    newRow.Controls.Add(newCell);
                    tblMatrix.Rows.Add(newRow);

                    // Security - Role separator text
                    newRow           = new TableRow();
                    newCell          = new TableCell();
                    newCell.CssClass = "MatrixLabel";
                    newCell.Text     = GetString("SecurityMatrix.RolesAvailability");
                    newCell.Attributes.Add("colspan", Convert.ToString(tblMatrix.Rows[0].Cells.Count - 1));
                    newRow.Controls.Add(newCell);
                    tblMatrix.Rows.Add(newRow);
                }

                // Add the latest row if present
                if (newRow != null)
                {
                    // The row is only role row and at the same time is divider between accesses section and roles section - make border higher
                    if (rowIsSeparator)
                    {
                        rowIsSeparator = false;
                    }
                    if (!mNoRolesAvailable)
                    {
                        newRow.Cells.Add(new TableCell());
                        tblMatrix.Rows.Add(newRow);
                    }
                }
            }
        }
    }
    /// <summary>
    /// Initializes the control properties.
    /// </summary>
    protected void SetupControl()
    {
        if (StopProcessing)
        {
            // Do nothing
        }
        else
        {
            if (!RequestHelper.IsPostBack())
            {
                // If user is public
                if (MembershipContext.AuthenticatedUser.IsPublic())
                {
                    // Get logon URL
                    string logonUrl = AuthenticationHelper.GetSecuredAreasLogonPage(SiteContext.CurrentSiteName);
                    logonUrl = DataHelper.GetNotEmpty(LoginURL, logonUrl);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                                        // Delete this invitation
                                        InvitationInfoProvider.DeleteInvitationInfo(invitation);
                                    }
                                }
                                else
                                {
                                    lblInfo.Text     = GroupNoLongerExists;
                                    lblInfo.CssClass = "InvitationErrorLabel";
                                    // Delete this invitation
                                    InvitationInfoProvider.DeleteInvitationInfo(invitation);
                                }
                            }
                            else
                            {
                                lblInfo.Text     = InvitationIsNotValid;
                                lblInfo.CssClass = "InvitationErrorLabel";
                                // Delete this invitation
                                InvitationInfoProvider.DeleteInvitationInfo(invitation);
                            }
                        }
                        else
                        {
                            lblInfo.Text     = InvitationNoLongerExists;
                            lblInfo.CssClass = "InvitationErrorLabel";
                        }
                        lblInfo.Visible = true;
                    }
                    else
                    {
                        // Hide control if invitation GUID isn't set
                        Visible = false;
                    }
                }
            }
        }
    }
    /// <summary>
    /// Updates picture of current group.
    /// </summary>
    /// <param name="gi">Group info object</param>
    public void UpdateGroupPicture(GroupInfo gi)
    {
        AvatarInfo ai = null;

        if (gi != null)
        {
            // Delete avatar if needed
            if (ValidationHelper.GetBoolean(hiddenDeleteAvatar.Value, false))
            {
                DeleteOldGroupPicture(gi);
            }

            // If some file was uploaded
            if ((uplFilePicture.PostedFile != null) && (uplFilePicture.PostedFile.ContentLength > 0) && ImageHelper.IsImage(Path.GetExtension(uplFilePicture.PostedFile.FileName)))
            {
                // Check if this group has some avatar and if so check if is custom
                ai = AvatarInfoProvider.GetAvatarInfoWithoutBinary(gi.GroupAvatarID);
                if ((ai != null) && ai.AvatarIsCustom)
                {
                    ReplaceExistingAvatar(ai);
                }
                else
                {
                    // Delete old picture
                    DeleteOldGroupPicture(gi);
                    ai = CreateNewAvatar();
                }

                AvatarInfoProvider.SetAvatarInfo(ai);

                // Update group info
                gi.GroupAvatarID = ai.AvatarID;
                GroupInfoProvider.SetGroupInfo(gi);


                plcImageActions.Visible = true;
            }
            // If predefined was chosen
            else if (!string.IsNullOrEmpty(hiddenAvatarGuid.Value))
            {
                // Delete old picture
                DeleteOldGroupPicture(gi);

                Guid guid = ValidationHelper.GetGuid(hiddenAvatarGuid.Value, Guid.NewGuid());
                ai = AvatarInfoProvider.GetAvatarInfoWithoutBinary(guid);

                // Update group info
                if (ai != null)
                {
                    gi.GroupAvatarID = ai.AvatarID;
                    GroupInfoProvider.SetGroupInfo(gi);
                }

                plcImageActions.Visible = true;
            }
            else
            {
                plcImageActions.Visible = false;
            }
        }
        else
        {
            bool pseudoDelete = ValidationHelper.GetBoolean(hiddenDeleteAvatar.Value, false);
            // Try to get avatar info
            if (avatarID != 0)
            {
                ai = AvatarInfoProvider.GetAvatarInfoWithoutBinary(avatarID);
            }

            // If some new picture was uploaded
            if ((uplFilePicture.PostedFile != null) && (uplFilePicture.PostedFile.ContentLength > 0) && ImageHelper.IsImage(Path.GetExtension(uplFilePicture.PostedFile.FileName)))
            {
                // Change delete to false because file will be replaced
                pseudoDelete = false;

                // If some avatar exists and is custom
                if ((ai != null) && (ai.AvatarIsCustom))
                {
                    // Delete file and upload new
                    AvatarInfoProvider.DeleteAvatarFile(ai.AvatarGUID.ToString(), ai.AvatarFileExtension, false, false);
                    ReplaceExistingAvatar(ai);
                }
                else
                {
                    ai = CreateNewAvatar();
                }

                // Update database
                AvatarInfoProvider.SetAvatarInfo(ai);
            }
            // If some predefined avatar was selected
            else if (!string.IsNullOrEmpty(hiddenAvatarGuid.Value))
            {
                // Change delete to false because file will be replaced
                pseudoDelete = false;

                // If some avatar exists and is custom
                if ((ai != null) && (ai.AvatarIsCustom))
                {
                    AvatarInfoProvider.DeleteAvatarFile(ai.AvatarGUID.ToString(), ai.AvatarFileExtension, false, false);
                    AvatarInfoProvider.DeleteAvatarInfo(ai);
                }

                Guid guid = ValidationHelper.GetGuid(hiddenAvatarGuid.Value, Guid.NewGuid());
                ai = AvatarInfoProvider.GetAvatarInfoWithoutBinary(guid);
            }

            // If file was deleted - not replaced
            if (pseudoDelete)
            {
                // Delete it
                ai = AvatarInfoProvider.GetAvatarInfoWithoutBinary(avatarID);
                if (ai != null)
                {
                    if (ai.AvatarIsCustom)
                    {
                        AvatarInfoProvider.DeleteAvatarInfo(ai);
                    }
                }

                ai       = null;
                avatarID = 0;
                plcImageActions.Visible = false;
                GroupPicture.AvatarID   = 0;
            }

            // Update avatar id
            if (ai != null)
            {
                GroupPicture.AvatarID   = avatarID = ai.AvatarID;
                plcImageActions.Visible = true;
            }
        }
    }
Esempio n. 18
0
    protected override void CreateChildControls()
    {
        base.CreateChildControls();

        // Get page url
        string page = QueryHelper.GetText("tab", this.SelectedPage);

        if (!String.IsNullOrEmpty(page))
        {
            page = page.ToLower();
        }

        // Check MANAGE permission
        if (RaiseOnCheckPermissions(CMSAdminControl.PERMISSION_MANAGE, this))
        {
            if (this.StopProcessing)
            {
                return;
            }
        }

        if ((this.GroupID == 0) && this.HideWhenGroupIsNotSupplied)
        {
            // Hide if groupID == 0
            this.Visible = false;
            return;
        }

        gi = GroupInfoProvider.GetGroupInfo(this.GroupID);

        // If no group, display the info and return
        if (gi == null)
        {
            this.lblInfo.Text       = GetString("group.groupprofile.nogroup");
            this.lblInfo.Visible    = true;
            this.tabMenu.Visible    = false;
            this.pnlContent.Visible = false;
            return;
        }

        // Get current URL
        string absoluteUri = URLHelper.CurrentURL;

        // Menu initialization
        tabMenu.TabControlIdPrefix = "GroupProfile";
        tabMenu.UrlTarget          = "_self";
        tabMenu.Tabs = new string[9, 5];

        tabMenu.UsePostback = true;

        int    i          = 0;
        string defaultTab = null;

        #region "Show/hide tabs"

        // Show general tab
        if (ShowGeneralTab)
        {
            tabMenu.Tabs[i, 0] = GetString("General.General");
            tabMenu.Tabs[i, 2] = HTMLHelper.HTMLEncode(URLHelper.AddParameterToUrl(absoluteUri, "tab", "general"));
            defaultTab         = "general";
            generalTabIndex    = i;
            i++;
        }

        // Show security tab
        if (ShowSecurityTab)
        {
            tabMenu.Tabs[i, 0] = GetString("General.Security");
            tabMenu.Tabs[i, 2] = HTMLHelper.HTMLEncode(URLHelper.AddParameterToUrl(absoluteUri, "tab", "security"));
            if (String.IsNullOrEmpty(defaultTab))
            {
                defaultTab = "security";
            }

            securityTabIndex = i;
            i++;
        }

        // Show members tab
        if (ShowMembersTab)
        {
            tabMenu.Tabs[i, 0] = GetString("Group.Members");
            tabMenu.Tabs[i, 2] = HTMLHelper.HTMLEncode(URLHelper.AddParameterToUrl(absoluteUri, "tab", "members"));
            if (String.IsNullOrEmpty(defaultTab))
            {
                defaultTab = "members";
            }

            membersTabIndex = i;
            i++;
        }

        // Show roles tab
        if (ShowRolesTab && ResourceSiteInfoProvider.IsResourceOnSite("CMS.Roles", CMSContext.CurrentSiteName))
        {
            tabMenu.Tabs[i, 0] = GetString("general.roles");
            tabMenu.Tabs[i, 2] = HTMLHelper.HTMLEncode(URLHelper.AddParameterToUrl(absoluteUri, "tab", "roles"));
            if (String.IsNullOrEmpty(defaultTab))
            {
                defaultTab = "roles";
            }

            rolesTabIndex = i;
            i++;
        }

        // Show forums tab
        if (ShowForumsTab && ResourceSiteInfoProvider.IsResourceOnSite("CMS.Forums", CMSContext.CurrentSiteName))
        {
            tabMenu.Tabs[i, 0] = GetString("Group.Forums");
            tabMenu.Tabs[i, 2] = HTMLHelper.HTMLEncode(URLHelper.AddParameterToUrl(absoluteUri, "tab", "forums"));
            if (String.IsNullOrEmpty(defaultTab))
            {
                defaultTab = "forums";
            }

            forumsTabIndex = i;
            i++;
        }

        // Show media tab
        if (ShowMediaTab && ResourceSiteInfoProvider.IsResourceOnSite("CMS.MediaLibrary", CMSContext.CurrentSiteName))
        {
            tabMenu.Tabs[i, 0] = GetString("Group.MediaLibrary");
            tabMenu.Tabs[i, 2] = HTMLHelper.HTMLEncode(URLHelper.AddParameterToUrl(absoluteUri, "tab", "medialibrary"));
            if (String.IsNullOrEmpty(defaultTab))
            {
                defaultTab = "medialibrary";
            }

            mediaTabIndex = i;
            i++;
        }

        // Show message boards tab
        if (ShowMessageBoardsTab && ResourceSiteInfoProvider.IsResourceOnSite("CMS.MessageBoards", CMSContext.CurrentSiteName))
        {
            tabMenu.Tabs[i, 0] = GetString("Group.MessageBoards");
            tabMenu.Tabs[i, 2] = HTMLHelper.HTMLEncode(URLHelper.AddParameterToUrl(absoluteUri, "tab", "messageboards"));
            if (String.IsNullOrEmpty(defaultTab))
            {
                defaultTab = "messageboards";
            }

            messageBoardsTabIndex = i;
            i++;
        }

        // Show polls tab
        if (ShowPollsTab && ResourceSiteInfoProvider.IsResourceOnSite("CMS.Polls", CMSContext.CurrentSiteName))
        {
            tabMenu.Tabs[i, 0] = GetString("Group.Polls");
            tabMenu.Tabs[i, 2] = HTMLHelper.HTMLEncode(URLHelper.AddParameterToUrl(absoluteUri, "tab", "polls"));
            if (String.IsNullOrEmpty(defaultTab))
            {
                defaultTab = "polls";
            }

            pollsTabIndex = i;
            i++;
        }

        // Show projects tab
        if (ShowProjectsTab)
        {
            // Check whether license for project management is available
            // if no hide project management tab
            if (LicenseHelper.CheckFeature(URLHelper.GetCurrentDomain(), FeatureEnum.ProjectManagement))
            {
                // Check site availability
                if (ResourceSiteInfoProvider.IsResourceOnSite("CMS.ProjectManagement", CMSContext.CurrentSiteName))
                {
                    tabMenu.Tabs[i, 0] = ResHelper.GetString("pm.project.list");
                    tabMenu.Tabs[i, 2] = HTMLHelper.HTMLEncode(URLHelper.AddParameterToUrl(absoluteUri, "tab", "projects"));
                    if (String.IsNullOrEmpty(defaultTab))
                    {
                        defaultTab = "projects";
                    }

                    projectTabIndex = i;
                }
            }
        }

        #endregion

        if (string.IsNullOrEmpty(page))
        {
            page = defaultTab;
            tabMenu.SelectedTab = 0;
        }

        // Select current page
        switch (page)
        {
        case "general":
            tabMenu.SelectedTab = generalTabIndex;

            // Show general content
            if (ShowGeneralTab)
            {
                ctrl    = LoadControl("~/CMSModules/Groups/Controls/GroupEdit.ascx") as CMSAdminControl;
                ctrl.ID = "groupEditElem";

                if (ctrl != null)
                {
                    ctrl.SetValue("GroupID", gi.GroupID);
                    ctrl.SetValue("SiteID", CMSContext.CurrentSiteID);
                    ctrl.SetValue("IsLiveSite", this.IsLiveSite);
                    ctrl.SetValue("AllowChangeGroupDisplayName", AllowChangeGroupDisplayName);
                    ctrl.SetValue("AllowSelectTheme", AllowSelectTheme);
                    ctrl.OnCheckPermissions += new CheckPermissionsEventHandler(ctrl_OnCheckPermissions);
                    pnlContent.Controls.Add(ctrl);
                }
            }
            break;

        case "security":
            tabMenu.SelectedTab = securityTabIndex;

            // Show security content
            if (ShowSecurityTab)
            {
                ctrl    = LoadControl("~/CMSModules/Groups/Controls/Security/GroupSecurity.ascx") as CMSAdminControl;
                ctrl.ID = "securityElem";

                if (ctrl != null)
                {
                    ctrl.SetValue("GroupID", gi.GroupID);
                    ctrl.SetValue("IsLiveSite", this.IsLiveSite);
                    ctrl.OnCheckPermissions += new CheckPermissionsEventHandler(ctrl_OnCheckPermissions);
                    pnlContent.Controls.Add(ctrl);
                }
            }
            break;

        case "members":
            if (membersTabIndex >= 0)
            {
                tabMenu.SelectedTab = membersTabIndex;

                // Show members content
                if (ShowMembersTab)
                {
                    ctrl    = LoadControl("~/CMSModules/Groups/Controls/Members/Members.ascx") as CMSAdminControl;
                    ctrl.ID = "securityElem";

                    if (ctrl != null)
                    {
                        ctrl.SetValue("GroupID", gi.GroupID);
                        ctrl.SetValue("IsLiveSite", this.IsLiveSite);
                        ctrl.OnCheckPermissions += new CheckPermissionsEventHandler(ctrl_OnCheckPermissions);
                        pnlContent.Controls.Add(ctrl);
                    }
                }
            }
            break;

        case "forums":
            if (forumsTabIndex >= 0)
            {
                tabMenu.SelectedTab = forumsTabIndex;

                // Show forums content
                if (ShowForumsTab)
                {
                    ctrl    = LoadControl("~/CMSModules/Forums/Controls/LiveControls/Groups.ascx") as CMSAdminControl;
                    ctrl.ID = "forumElem";

                    if (ctrl != null)
                    {
                        ctrl.SetValue("GroupID", gi.GroupID);
                        ctrl.SetValue("CommunityGroupGUID", gi.GroupGUID);
                        ctrl.SetValue("IsLiveSite", this.IsLiveSite);
                        ctrl.DisplayMode         = ControlDisplayModeEnum.Simple;
                        ctrl.OnCheckPermissions += new CheckPermissionsEventHandler(ctrl_OnCheckPermissions);

                        pnlContent.Controls.Add(ctrl);
                    }
                }
            }
            break;

        case "roles":
            if (rolesTabIndex >= 0)
            {
                tabMenu.SelectedTab = rolesTabIndex;
                // Show roles content
                if (ShowRolesTab)
                {
                    ctrl    = LoadControl("~/CMSModules/Membership/Controls/Roles/Roles.ascx") as CMSAdminControl;
                    ctrl.ID = "rolesElem";

                    if (ctrl != null)
                    {
                        ctrl.SetValue("GroupID", gi.GroupID);
                        ctrl.SetValue("GroupGUID", gi.GroupGUID);
                        ctrl.SetValue("SiteID", CMSContext.CurrentSiteID);
                        ctrl.SetValue("IsLiveSite", this.IsLiveSite);
                        ctrl.DisplayMode         = ControlDisplayModeEnum.Simple;
                        ctrl.OnCheckPermissions += new CheckPermissionsEventHandler(ctrl_OnCheckPermissions);

                        pnlContent.Controls.Add(ctrl);
                    }
                }
            }
            break;

        case "polls":
            if (pollsTabIndex >= 0)
            {
                tabMenu.SelectedTab = pollsTabIndex;

                // Show polls content
                if (ShowPollsTab)
                {
                    ctrl    = LoadControl("~/CMSModules/Polls/Controls/Polls.ascx") as CMSAdminControl;
                    ctrl.ID = "pollsElem";

                    if (ctrl != null)
                    {
                        ctrl.SetValue("GroupID", gi.GroupID);
                        ctrl.SetValue("GroupGUID", gi.GroupGUID);
                        ctrl.SetValue("SiteID", CMSContext.CurrentSiteID);
                        ctrl.SetValue("IsLiveSite", this.IsLiveSite);
                        ctrl.DisplayMode         = ControlDisplayModeEnum.Simple;
                        ctrl.OnCheckPermissions += new CheckPermissionsEventHandler(ctrl_OnCheckPermissions);
                        pnlContent.Controls.Add(ctrl);
                    }
                }
            }
            break;

        case "messageboards":
            if (messageBoardsTabIndex >= 0)
            {
                tabMenu.SelectedTab = messageBoardsTabIndex;

                // Show message boards content
                if (ShowMessageBoardsTab)
                {
                    ctrl    = LoadControl("~/CMSModules/MessageBoards/Controls/LiveControls/Boards.ascx") as CMSAdminControl;
                    ctrl.ID = "boardElem";

                    if (ctrl != null)
                    {
                        ctrl.SetValue("GroupID", gi.GroupID);
                        ctrl.SetValue("IsLiveSite", this.IsLiveSite);
                        ctrl.DisplayMode         = ControlDisplayModeEnum.Simple;
                        ctrl.OnCheckPermissions += new CheckPermissionsEventHandler(ctrl_OnCheckPermissions);

                        pnlContent.Controls.Add(ctrl);
                    }
                }
            }
            break;

        case "medialibrary":
            if (mediaTabIndex >= 0)
            {
                tabMenu.SelectedTab = mediaTabIndex;

                // Show media content
                if (ShowMediaTab)
                {
                    ctrl    = LoadControl("~/CMSModules/MediaLibrary/Controls/LiveControls/MediaLibraries.ascx") as CMSAdminControl;
                    ctrl.ID = "libraryElem";

                    if (ctrl != null)
                    {
                        ctrl.SetValue("GroupGUID", gi.GroupID);
                        ctrl.SetValue("GroupID", gi.GroupID);
                        ctrl.SetValue("IsLiveSite", this.IsLiveSite);
                        ctrl.DisplayMode         = ControlDisplayModeEnum.Simple;
                        ctrl.OnCheckPermissions += new CheckPermissionsEventHandler(ctrl_OnCheckPermissions);

                        pnlContent.Controls.Add(ctrl);
                    }
                }
            }
            break;

        case "projects":
            if (projectTabIndex >= 0)
            {
                tabMenu.SelectedTab = projectTabIndex;

                // Show projects content
                if (ShowProjectsTab)
                {
                    ctrl    = LoadControl("~/CMSModules/ProjectManagement/Controls/LiveControls/GroupProjects.ascx") as CMSAdminControl;
                    ctrl.ID = "projectElem";
                    if (ctrl != null)
                    {
                        ctrl.SetValue("CommunityGroupID", gi.GroupID);
                        ctrl.SetValue("IsLiveSite", this.IsLiveSite);
                        ctrl.DisplayMode         = ControlDisplayModeEnum.Simple;
                        ctrl.OnCheckPermissions += new CheckPermissionsEventHandler(ctrl_OnCheckPermissions);
                        pnlContent.Controls.Add(ctrl);
                    }
                }
            }
            break;


        default:
            break;
        }

        if (!RequestHelper.IsPostBack())
        {
            ReloadData();
        }
    }
    /// <summary>
    /// Generates the permission matrix for the current group.
    /// </summary>
    private void CreateMatrix()
    {
        // Get group resource info
        if (resGroups == null)
        {
            resGroups = ResourceInfoProvider.GetResourceInfo("CMS.Groups");
        }

        if (resGroups != null)
        {
            group = GroupInfoProvider.GetGroupInfo(GroupID);

            // Get permissions for the current group resource
            DataSet permissions = PermissionNameInfoProvider.GetResourcePermissions(resGroups.ResourceID);
            if (DataHelper.DataSourceIsEmpty(permissions))
            {
                ShowInformation(GetString("general.emptymatrix"));
            }
            else
            {
                TableRow headerRow = new TableRow();
                headerRow.TableSection = TableRowSection.TableHeader;
                headerRow.CssClass     = "unigrid-head";

                TableHeaderCell newHeaderCell = new TableHeaderCell();
                newHeaderCell.CssClass = "first-column";
                headerRow.Cells.Add(newHeaderCell);

                foreach (string permission in allowedPermissions)
                {
                    DataRow[] drArray = permissions.Tables[0].DefaultView.Table.Select("PermissionName = '" + permission + "'");
                    if (drArray.Length > 0)
                    {
                        DataRow dr = drArray[0];
                        newHeaderCell          = new TableHeaderCell();
                        newHeaderCell.CssClass = "matrix-header";
                        newHeaderCell.Text     = dr["PermissionDisplayName"].ToString();
                        newHeaderCell.ToolTip  = dr["PermissionDescription"].ToString();

                        headerRow.Cells.Add(newHeaderCell);
                    }
                    else
                    {
                        throw new Exception("[Security matrix] Column '" + permission + "' cannot be found.");
                    }
                }
                tblMatrix.Rows.Add(headerRow);

                // Render group access permissions
                object[,] accessNames = new object[5, 2];
                accessNames[0, 0]     = GetString("security.nobody");
                accessNames[0, 1]     = SecurityAccessEnum.Nobody;
                accessNames[1, 0]     = GetString("security.allusers");
                accessNames[1, 1]     = SecurityAccessEnum.AllUsers;
                accessNames[2, 0]     = GetString("security.authenticated");
                accessNames[2, 1]     = SecurityAccessEnum.AuthenticatedUsers;
                accessNames[3, 0]     = GetString("security.groupmembers");
                accessNames[3, 1]     = SecurityAccessEnum.GroupMembers;
                accessNames[4, 0]     = GetString("security.authorizedroles");
                accessNames[4, 1]     = SecurityAccessEnum.AuthorizedRoles;

                TableRow newRow = null;

                TableCell newCell;
                for (int access = 0; access <= accessNames.GetUpperBound(0); access++)
                {
                    SecurityAccessEnum currentAccess = ((SecurityAccessEnum)accessNames[access, 1]);

                    // Generate cell holding access item name
                    newRow           = new TableRow();
                    newCell          = new TableCell();
                    newCell.CssClass = "matrix-header";
                    newCell.Text     = accessNames[access, 0].ToString();
                    newRow.Cells.Add(newCell);

                    // Render the permissions access items
                    int permissionIndex = 0;
                    for (int permission = 0; permission < (tblMatrix.Rows[0].Cells.Count - 1); permission++)
                    {
                        newCell          = new TableCell();
                        newCell.CssClass = "matrix-cell";

                        // Check if the currently processed access is applied for permission
                        bool isAllowed = CheckPermissionAccess(currentAccess, permission, tblMatrix.Rows[0].Cells[permission + 1].Text);

                        // Disable column in roles grid if needed
                        if ((currentAccess == SecurityAccessEnum.AuthorizedRoles) && !isAllowed)
                        {
                            gridMatrix.DisableColumn(permissionIndex);
                        }

                        // Insert the radio button for the current permission
                        var radio = new CMSRadioButton
                        {
                            Checked = isAllowed,
                            Enabled = Enabled,
                        };
                        radio.Attributes.Add("onclick", ControlsHelper.GetPostBackEventReference(this, permission + ";" + Convert.ToInt32(currentAccess)));
                        newCell.Controls.Add(radio);

                        newRow.Cells.Add(newCell);
                        permissionIndex++;
                    }

                    // Add the access row to the table
                    tblMatrix.Rows.Add(newRow);
                }

                // Hide if no roles available
                headTitle.Visible = gridMatrix.HasData;
            }
        }
    }
Esempio n. 20
0
    /// <summary>
    /// Updates the current Group or creates new if no MemberID is present.
    /// </summary>
    public bool SaveData()
    {
        // Check MANAGE permission for groups module
        if (!CheckPermissions("cms.groups", CMSAdminControl.PERMISSION_MANAGE, this.GroupID))
        {
            return(false);
        }

        EnsureMember();

        newItem = (this.MemberID == 0);

        if (gmi != null)
        {
            // Get user info
            UserInfo ui = UserInfoProvider.GetUserInfo(gmi.MemberUserID);
            if (ui != null)
            {
                // Save user roles
                SaveRoles(ui.UserID);

                gmi.MemberComment = this.txtComment.Text;
                GroupMemberInfoProvider.SetGroupMemberInfo(gmi);

                return(true);
            }
        }
        else
        {
            // New member
            if (newItem)
            {
                int userId = ValidationHelper.GetInteger(userSelector.Value, 0);

                // Check if some user was selected
                if (userId == 0)
                {
                    lblError.Visible        = true;
                    lblError.ResourceString = "group.member.selectuser";
                    return(false);
                }

                // Check if user is not already group member
                gmi = GroupMemberInfoProvider.GetGroupMemberInfo(userId, this.GroupID);
                if (gmi != null)
                {
                    lblError.Visible        = true;
                    lblError.ResourceString = "group.member.userexists";
                    return(false);
                }

                // New member object
                gmi = new GroupMemberInfo();
                gmi.MemberGroupID = this.GroupID;
                gmi.MemberJoined  = DateTime.Now;
                gmi.MemberUserID  = userId;
                gmi.MemberComment = this.txtComment.Text;

                if (this.chkApprove.Checked)
                {
                    // Approve member
                    gmi.MemberStatus           = GroupMemberStatus.Approved;
                    gmi.MemberApprovedWhen     = DateTime.Now;
                    gmi.MemberApprovedByUserID = CMSContext.CurrentUser.UserID;
                }
                else
                {
                    gmi.MemberStatus           = GroupMemberStatus.WaitingForApproval;
                    gmi.MemberApprovedByUserID = CMSContext.CurrentUser.UserID;
                }

                // Save member to database
                GroupMemberInfoProvider.SetGroupMemberInfo(gmi);
                GroupInfo group = GroupInfoProvider.GetGroupInfo(this.GroupID);
                if (group != null)
                {
                    // Send notification email
                    if ((this.chkApprove.Checked) && (group.GroupSendWaitingForApprovalNotification))
                    {
                        GroupMemberInfoProvider.SendNotificationMail("Groups.MemberJoinedConfirmation", CMSContext.CurrentSiteName, gmi, false);
                    }
                    else
                    {
                        if (group.GroupSendWaitingForApprovalNotification)
                        {
                            GroupMemberInfoProvider.SendNotificationMail("Groups.MemberJoinedWaitingForApproval ", CMSContext.CurrentSiteName, gmi, false);
                        }
                    }
                }

                // Save user roles
                SaveRoles(userId);

                this.MemberID = gmi.MemberID;
                return(true);
            }
        }

        return(false);
    }
    /// <summary>
    /// Updates the current Group or creates new if no MemberID is present.
    /// </summary>
    public bool SaveData()
    {
        // Check MANAGE permission for groups module
        if (!CheckPermissions("cms.groups", PERMISSION_MANAGE, GroupID))
        {
            return(false);
        }

        newItem = (MemberID == 0);

        if (CurrentMember != null)
        {
            if (CurrentMember.MemberID > 0)
            {
                // Get user info
                UserInfo ui = UserInfoProvider.GetUserInfo(CurrentMember.MemberUserID);
                if (ui != null)
                {
                    // Save user roles
                    SaveRoles(ui.UserID);

                    CurrentMember.MemberComment = txtComment.Text;
                    GroupMemberInfoProvider.SetGroupMemberInfo(CurrentMember);

                    return(true);
                }
            }
            else
            {
                // New member
                if (newItem)
                {
                    int userId = ValidationHelper.GetInteger(userSelector.Value, 0);

                    // Check if some user was selected
                    if (userId == 0)
                    {
                        ShowError(GetString("group.member.selectuser"));
                        return(false);
                    }

                    // Check if user is not already group member
                    var existing = GroupMemberInfoProvider.GetGroupMemberInfo(userId, GroupID);
                    if (existing != null)
                    {
                        ShowError(GetString("group.member.userexists"));
                        return(false);
                    }

                    // New member object
                    CurrentMember.MemberGroupID = GroupID;
                    CurrentMember.MemberJoined  = DateTime.Now;
                    CurrentMember.MemberUserID  = userId;
                    CurrentMember.MemberComment = txtComment.Text;

                    if (chkApprove.Checked)
                    {
                        // Approve member
                        CurrentMember.MemberStatus           = GroupMemberStatus.Approved;
                        CurrentMember.MemberApprovedWhen     = DateTime.Now;
                        CurrentMember.MemberApprovedByUserID = MembershipContext.AuthenticatedUser.UserID;
                    }
                    else
                    {
                        CurrentMember.MemberStatus           = GroupMemberStatus.WaitingForApproval;
                        CurrentMember.MemberApprovedByUserID = MembershipContext.AuthenticatedUser.UserID;
                    }

                    // Save member to database
                    GroupMemberInfoProvider.SetGroupMemberInfo(CurrentMember);
                    GroupInfo group = GroupInfoProvider.GetGroupInfo(GroupID);
                    if (group != null)
                    {
                        // Send notification email
                        if ((chkApprove.Checked) && (group.GroupSendWaitingForApprovalNotification))
                        {
                            GroupMemberInfoProvider.SendNotificationMail("Groups.MemberJoinedConfirmation", SiteContext.CurrentSiteName, CurrentMember, false);
                        }
                        else
                        {
                            if (group.GroupSendWaitingForApprovalNotification)
                            {
                                GroupMemberInfoProvider.SendNotificationMail("Groups.MemberJoinedWaitingForApproval ", SiteContext.CurrentSiteName, CurrentMember, false);
                            }
                        }
                    }

                    // Save user roles
                    SaveRoles(userId);

                    MemberID = CurrentMember.MemberID;
                    return(true);
                }
            }
        }

        return(false);
    }
    /// <summary>
    /// Initializes the control properties.
    /// </summary>
    protected void SetupControl()
    {
        if (StopProcessing)
        {
            // Do nothing
        }
        else
        {
            // Initialize properties
            string script = "";

            // Set current user
            currentUser = CMSContext.CurrentUser;

            // Get Enable Friends setting
            bool friendsEnabled = UIHelper.IsFriendsModuleEnabled(CMSContext.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;
            lnkMyTasks.Text                = MyTasksText;

            // 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 = CMSContext.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 = URLHelper.ResolveUrl(TreePathUtils.GetUrl(GroupMemberInfoProvider.GetMemberManagementPath(currentUser.UserName, CMSContext.CurrentSiteName)));
                    pnlEditMyProfile.Visible     = true;
                    pnlProfileLinks.Visible      = true;
                }

                // Display My profile link if set so
                if (DisplayMyProfileLink)
                {
                    lnkMyProfile.NavigateUrl = URLHelper.ResolveUrl(TreePathUtils.GetUrl(GroupMemberInfoProvider.GetMemberProfilePath(currentUser.UserName, CMSContext.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
                    ModuleEntry entry = ModuleEntry.GetModuleEntry(ModuleEntry.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;
                }

                // Display My tasks link
                if (DisplayMyTasks)
                {
                    lnkMyTasks.NavigateUrl   = GetUrl(MyTasksPath);
                    pnlMyTasks.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(CMSContext.CurrentUser.UserID, currentGroup.GroupID);
                        if (gmi == null)
                        {
                            if (String.IsNullOrEmpty(JoinGroupPath))
                            {
                                script += "function JoinToGroupRequest() {\n" +
                                          "modalDialog('" + CMSContext.ResolveDialogUrl("~/CMSModules/Groups/CMSPages/JoinTheGroup.aspx") + "?groupid=" + currentGroup.GroupID + "','requestJoinToGroup', 500, 180); \n" +
                                          " } \n";

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

                                lnkLeaveGroup.Attributes.Add("onclick", "LeaveTheGroupRequest();return false;");
                                lnkLeaveGroup.NavigateUrl = URLHelper.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.IsGlobalAdministrator)))
                    {
                        lnkManageGroup.NavigateUrl = ResolveUrl(TreePathUtils.GetUrl(GroupInfoProvider.GetGroupManagementPath(currentGroup.GroupName, CMSContext.CurrentSiteName)));
                        pnlManageGroup.Visible     = true;
                        pnlGroupLinks.Visible      = true;
                    }
                }

                if (DisplayInviteToGroup)
                {
                    // Get group info from community context
                    GroupInfo currentGroup = CommunityContext.CurrentGroup;
                    // Get user info from site context
                    UserInfo siteContextUser = SiteContext.CurrentUser;

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

                        if (((gmi != null) && (gmi.MemberStatus == GroupMemberStatus.Approved)) || (CMSContext.CurrentUser.IsGlobalAdministrator))
                        {
                            pnlInviteToGroup.Visible = true;

                            if (String.IsNullOrEmpty(InviteGroupPath))
                            {
                                script += "function InviteToGroup() {\n modalDialog('" + CMSContext.ResolveDialogUrl("~/CMSModules/Groups/CMSPages/InviteToGroup.aspx") + "?groupid=" + currentGroup.GroupID + "','inviteToGroup', 500, 345); \n } \n";
                                lnkInviteToGroup.Attributes.Add("onclick", "InviteToGroup();return false;");
                                lnkInviteToGroup.NavigateUrl = URLHelper.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, CMSContext.CurrentSite) != 0))
                    {
                        pnlInviteToGroup.Visible = true;

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

                if (SiteContext.CurrentUser != null)
                {
                    // Get user info from site context
                    UserInfo siteContextUser = SiteContext.CurrentUser;

                    // Display Friendship link if set so and user is visiting an user's page
                    if (DisplayFriendshipLinks && (currentUser.UserID != siteContextUser.UserID) && friendsEnabled)
                    {
                        FriendshipStatusEnum status = CMSContext.CurrentUser.HasFriend(siteContextUser.UserID);
                        switch (status)
                        {
                        case FriendshipStatusEnum.Approved:
                            // Friendship rejection
                            script += "function ShortcutFriendshipReject(id) { \n" +
                                      "modalDialog('" + CMSContext.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 = URLHelper.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('" + CMSContext.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 = URLHelper.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 = URLHelper.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 = URLHelper.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);
        }
    }
Esempio n. 23
0
    /// <summary>
    /// Handles the UniGrid's OnAction event.
    /// </summary>
    /// <param name="actionName">Name of item (button) that throws event</param>
    /// <param name="actionArgument">ID (value of Primary key) of corresponding data row</param>
    protected void gridElem_OnAction(string actionName, object actionArgument)
    {
        switch (actionName)
        {
        case "delete":
        case "approve":
        case "reject":

            // Check MANAGE permission for groups module
            if (!CheckPermissions("cms.groups", PERMISSION_MANAGE, GroupID))
            {
                return;
            }

            break;
        }

        if (actionName == "delete")
        {
            // Delete member
            GroupMemberInfoProvider.DeleteGroupMemberInfo(ValidationHelper.GetInteger(actionArgument, 0));
        }
        else if (actionName == "approve")
        {
            // Approve member
            GroupMemberInfo gmi = GroupMemberInfoProvider.GetGroupMemberInfo(ValidationHelper.GetInteger(actionArgument, 0));
            if (gmi != null)
            {
                gmi.MemberApprovedByUserID = CMSContext.CurrentUser.UserID;
                gmi.MemberStatus           = GroupMemberStatus.Approved;
                gmi.MemberApprovedWhen     = DateTime.Now;
                gmi.MemberRejectedWhen     = DataHelper.DATETIME_NOT_SELECTED;
                GroupMemberInfoProvider.SetGroupMemberInfo(gmi);
                GroupInfo group = GroupInfoProvider.GetGroupInfo(GroupID);
                if ((group != null) && (group.GroupSendWaitingForApprovalNotification))
                {
                    // Send notification email
                    GroupMemberInfoProvider.SendNotificationMail("Groups.MemberApproved", CMSContext.CurrentSiteName, gmi, false);
                }
            }
        }
        else if (actionName == "reject")
        {
            // Reject member
            GroupMemberInfo gmi = GroupMemberInfoProvider.GetGroupMemberInfo(ValidationHelper.GetInteger(actionArgument, 0));
            if (gmi != null)
            {
                gmi.MemberApprovedByUserID = CMSContext.CurrentUser.UserID;
                gmi.MemberStatus           = GroupMemberStatus.Rejected;
                gmi.MemberApprovedWhen     = DataHelper.DATETIME_NOT_SELECTED;
                gmi.MemberRejectedWhen     = DateTime.Now;
                GroupMemberInfoProvider.SetGroupMemberInfo(gmi);
                GroupInfo group = GroupInfoProvider.GetGroupInfo(GroupID);
                if ((group != null) && (group.GroupSendWaitingForApprovalNotification))
                {
                    // Send notification email
                    GroupMemberInfoProvider.SendNotificationMail("Groups.MemberRejected", CMSContext.CurrentSiteName, gmi, false);
                }
            }
        }
        RaiseOnAction(actionName, actionArgument);
    }
    /// <summary>
    /// Initializes the control properties.
    /// </summary>
    protected void SetupControl()
    {
        if (StopProcessing)
        {
            // Do nothing
        }
        else
        {
            // Initialize properties
            string script = "";

            // Set current user
            currentUser = MembershipContext.AuthenticatedUser;

            // 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;
            lnkInviteToGroup.Text  = InviteGroupText;
            lnkManageGroup.Text    = ManageGroupText;
            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 && !AuthenticationMode.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 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)
                    {
                        // 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);
                        }
                    }
                }
            }

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

            // Register the dialog script
            ScriptHelper.RegisterDialogScript(Page);
        }
    }