Пример #1
0
        void SiteMap_MenuItemDataBound(object sender, MenuEventArgs e)
        {
            Menu            menu    = (Menu)sender;
            mojoSiteMapNode mapNode = (mojoSiteMapNode)e.Item.DataItem;

            if ((usePageImages) && (mapNode.MenuImage.Length > 0))
            {
                e.Item.ImageUrl = mapNode.MenuImage;
            }

            bool remove = false;

            if (mapNode.Roles == null)
            {
                if ((!isAdmin) && (!isContentAdmin) && (!isSiteEditor))
                {
                    remove = true;
                }
            }
            else
            {
                if ((!isAdmin) && (mapNode.Roles.Count == 1) && (mapNode.Roles[0].ToString() == "Admins"))
                {
                    remove = true;
                }

                if ((!isAdmin) && (!isContentAdmin) && (!isSiteEditor) && (!WebUser.IsInRoles(mapNode.Roles)))
                {
                    remove = true;
                }
            }

            if ((treatChildPageIndexAsSiteMap) || (hidePagesNotInSiteMap))
            {
                if (!mapNode.IncludeInSiteMap)
                {
                    remove = true;
                }
            }
            else
            {
                if (!mapNode.IncludeInMenu)
                {
                    remove = true;
                }
            }

            if ((mapNode.HideAfterLogin) && (Request.IsAuthenticated))
            {
                remove = true;
            }

            if (isMobileSkin)
            {
                if (mapNode.PublishMode == webOnly)
                {
                    remove = true;
                }
            }
            else
            {
                if (mapNode.PublishMode == mobileOnly)
                {
                    remove = true;
                }
            }

            if (remove)
            {
                if (e.Item.Depth == 0)
                {
                    menu.Items.Remove(e.Item);
                }
                else
                {
                    MenuItem parent = e.Item.Parent;
                    if (parent != null)
                    {
                        parent.ChildItems.Remove(e.Item);
                    }
                }
            }
        }
Пример #2
0
        private void SetupWorkflowControls()
        {
            if (HttpContext.Current == null)
            {
                return;
            }

            if (siteModule == null)
            {
                return;
            }
            if (module == null)
            {
                return;
            }


            CmsPage cmsPage = this.Page as CmsPage;

            if ((cmsPage != null) && (cmsPage.ViewMode == PageViewMode.WorkInProgress))
            {
                //ScriptReference script = new ScriptReference();
                //script.Path = "~/ClientScript/jqmojo/jquery.cluetip.js";
                //cmsPage.ScriptConfig.AddPathScriptReference(script);

                //this.Controls.Add(statusLink);

                switch (workflowStatus)
                {
                case ContentWorkflowStatus.Draft:

                    ibPostDraftContentForApproval.ImageUrl = Page.ResolveUrl(WebConfigSettings.RequestApprovalImage);
                    ibPostDraftContentForApproval.ToolTip  = Resource.RequestApprovalToolTip;
                    ibPostDraftContentForApproval.Visible  = true;
                    //statusLink.HelpKey = "workflowstatus-draft-help";

                    statusIcon.ToolTip = Resource.WorkflowDraft;
                    //statusLink.Visible = true;
                    //statusLink.HookupScript();

                    if (WebConfigSettings.WorkflowShowPublishForUnSubmittedDraft)
                    {
                        if (
                            (cmsPage.CurrentPage != null) &&
                            (isAdminEditor || WebUser.IsInRoles(cmsPage.CurrentPage.EditRoles) || WebUser.IsInRoles(this.module.AuthorizedEditRoles) ||
                             (WebConfigSettings.Use3LevelContentWorkflow && (WebUser.IsInRoles(cmsPage.CurrentPage.DraftApprovalRoles) || WebUser.IsInRoles(this.module.DraftApprovalRoles)))
                            )
                            )
                        {
                            ibApproveContent.ImageUrl = Page.ResolveUrl(WebConfigSettings.ApproveContentImage);
                            ibApproveContent.Visible  = true;
                            ibApproveContent.ToolTip  = Resource.ApproveContentToolTip;
                        }
                    }

                    break;

                case ContentWorkflowStatus.AwaitingApproval:

                    if (WebConfigSettings.Use3LevelContentWorkflow)
                    {
                        //joe davis
                        //disable edit link because draft is awaiting approval
                        lnkModuleEdit.Visible = false;
                    }

                    //if (WebUser.IsAdminOrContentAdminOrContentPublisher)
                    if (
                        (cmsPage.CurrentPage != null) &&
                        (isAdminEditor || WebUser.IsInRoles(cmsPage.CurrentPage.EditRoles) || WebUser.IsInRoles(this.module.AuthorizedEditRoles) ||
                         (WebConfigSettings.Use3LevelContentWorkflow && (WebUser.IsInRoles(cmsPage.CurrentPage.DraftApprovalRoles) || WebUser.IsInRoles(this.module.DraftApprovalRoles)))
                        )
                        )
                    {
                        if (WebConfigSettings.Use3LevelContentWorkflow)
                        {
                            //user can edit current draft awaiting approval
                            lnkModuleEdit.Visible = true;
                        }

                        //add in the reject and approve links:
                        ibApproveContent.ImageUrl = Page.ResolveUrl(WebConfigSettings.ApproveContentImage);
                        ibApproveContent.Visible  = true;
                        ibApproveContent.ToolTip  = Resource.ApproveContentToolTip;

                        lnkRejectContent.NavigateUrl =
                            siteRoot
                            + "/Admin/RejectContent.aspx?mid=" + module.ModuleId.ToInvariantString()
                            + "&pageid=" + module.PageId.ToInvariantString();

                        lnkRejectContent.ImageUrl = Page.ResolveUrl(WebConfigSettings.RejectContentImage);
                        lnkRejectContent.ToolTip  = Resource.RejectContentToolTip;
                        lnkRejectContent.Visible  = true;
                    }

                    statusIcon.ToolTip = WebConfigSettings.Use3LevelContentWorkflow ? Resource.WorkflowAwaitingApproval3Level : Resource.WorkflowAwaitingApproval;

                    //statusLink.Visible = true;
                    //statusLink.HookupScript();

                    break;

                case ContentWorkflowStatus.AwaitingPublishing:
                    //joe davis
                    if (
                        (cmsPage.CurrentPage != null) &&
                        (isAdminEditor || WebUser.IsInRoles(cmsPage.CurrentPage.EditRoles) || WebUser.IsInRoles(this.module.AuthorizedEditRoles))
                        )
                    {
                        //add in the reject and publish links:
                        ibPublishContent.ImageUrl = Page.ResolveUrl(WebConfigSettings.PublishContentImage);
                        ibPublishContent.Visible  = true;
                        ibPublishContent.ToolTip  = Resource.PublishContentToolTip;

                        lnkRejectContent.NavigateUrl =
                            siteRoot
                            + "/Admin/RejectContent.aspx?mid=" + module.ModuleId.ToInvariantString()
                            + "&pageid=" + module.PageId.ToInvariantString();

                        lnkRejectContent.ImageUrl = Page.ResolveUrl(WebConfigSettings.RejectContentImage);
                        lnkRejectContent.ToolTip  = Resource.RejectContentToolTip;
                        lnkRejectContent.Visible  = true;
                    }

                    statusIcon.ToolTip = Resource.WorkflowAwaitingPublishing;

                    break;

                case ContentWorkflowStatus.ApprovalRejected:
                    // statusLink.HelpKey = "workflowstatus-rejected-help";
                    statusIcon.ToolTip = Resource.WorkflowRejected;
                    //statusLink.Visible = true;
                    //statusLink.HookupScript();
                    break;
                }

                if (
                    (workflowStatus != ContentWorkflowStatus.Cancelled) &&
                    (workflowStatus != ContentWorkflowStatus.Approved) &&
                    (workflowStatus != ContentWorkflowStatus.None)
                    )
                {
                    //allow changes to be cancelled:
                    ibCancelChanges.ImageUrl = Page.ResolveUrl(WebConfigSettings.CancelContentChangesImage);
                    ibCancelChanges.ToolTip  = Resource.CancelChangesToolTip;
                    ibCancelChanges.Visible  = true;
                }
            }
        }
Пример #3
0
        public PopulatedItem(Item item, List <Field> fields, List <ItemFieldValue> values, bool canEdit = false)
        {
            //List<PopulatedValue> popValues = new List<PopulatedValue>();

            //Item = item;
            Guid       = item.ItemGuid;
            Id         = item.ItemID;
            SortOrder  = item.SortOrder;
            CreatedUTC = item.CreatedUtc;
            UpdatedUTC = item.LastModUtc;
            Values     = new Dictionary <string, object>();
            foreach (Field field in fields)
            {
                if (String.IsNullOrWhiteSpace(field.Token))
                {
                    field.Token = "$_NONE_$";
                }
                if (!WebUser.IsAdmin && !WebUser.IsInRoles(field.ViewRoles) && !WebUser.IsInRoles(field.EditRoles))
                {
                    Values.Add(field.Name, null);
                    continue;
                }

                var thisValue = values.Where(v => v.FieldGuid == field.FieldGuid).FirstOrDefault();

                bool fieldValueFound = thisValue != null;

                if (fieldValueFound && (!String.IsNullOrWhiteSpace(thisValue.FieldValue) &&
                                        !thisValue.FieldValue.StartsWith("&deleted&") &&
                                        !thisValue.FieldValue.StartsWith("&amp;deleted&amp;") &&
                                        !thisValue.FieldValue.StartsWith("<p>&deleted&</p>") &&
                                        !thisValue.FieldValue.StartsWith("<p>&amp;deleted&amp;</p>")))
                {
                    //popValues.Add(new PopulatedValue
                    //{
                    //	Name = field.Name,
                    //	Token = field.Token,
                    //	Value = thisValue.FieldValue,
                    //	ValueGuid = thisValue.ValueGuid,
                    //	FieldGuid = thisValue.FieldGuid
                    //});
                    if (field.ControlType == "DynamicCheckBoxList" || field.ControlType == "CheckBoxList")
                    {
                        Values.Add(field.Name, thisValue.FieldValue.SplitOnCharAndTrim(';'));
                    }
                    else if (field.ControlType == "CheckBox" && field.CheckBoxReturnBool == true)
                    {
                        Values.Add(field.Name, Convert.ToBoolean(thisValue.FieldValue));
                    }
                    else
                    {
                        Values.Add(field.Name, thisValue.FieldValue);
                    }
                }
                else
                {
                    Values.Add(field.Name, null);
                }
            }
            //Values = popValues;
        }
Пример #4
0
        private void LoadSettings()
        {
            virtualRoot = WebUtils.GetApplicationRoot();

            pageId                = WebUtils.ParseInt32FromQueryString("pageid", -1);
            moduleId              = WebUtils.ParseInt32FromQueryString("mid", -1);
            groupId               = WebUtils.ParseInt32FromQueryString("groupid", -1);
            topicId               = WebUtils.ParseInt32FromQueryString("topic", -1);
            postId                = WebUtils.ParseInt32FromQueryString("postid", -1);
            pageNumber            = WebUtils.ParseInt32FromQueryString("pagenumber", 1);
            lnkCancel.NavigateUrl = SiteUtils.GetCurrentPageUrl();
            timeOffset            = SiteUtils.GetUserTimeOffset();

            switch (siteSettings.AvatarSystem)
            {
            case "gravatar":
                allowGravatars = true;
                disableAvatars = true;
                break;

            case "internal":
                allowGravatars = false;
                disableAvatars = false;
                break;

            case "none":
            default:
                allowGravatars = false;
                disableAvatars = true;
                break;
            }

            if (Request.IsAuthenticated)
            {
                theUser = SiteUtils.GetCurrentSiteUser();
                if (groupId > -1)
                {
                    isSubscribedToGroup = Group.IsSubscribed(groupId, theUser.UserId);
                }
                if (topicId > -1)
                {
                    isSubscribedToTopic = GroupTopic.IsSubscribed(topicId, theUser.UserId);
                }
            }

            if (WebUser.IsAdminOrContentAdmin)
            {
                edMessage.WebEditor.ToolBar = ToolBar.FullWithTemplates;
            }
            else if ((Request.IsAuthenticated) && (WebUser.IsInRoles(siteSettings.UserFilesBrowseAndUploadRoles)))
            {
                edMessage.WebEditor.ToolBar = ToolBar.GroupWithImages;
            }
            else
            {
                edMessage.WebEditor.ToolBar = ToolBar.Group;
            }

            edMessage.WebEditor.SetFocusOnStart = true;
            edMessage.WebEditor.Height          = Unit.Parse("350px");

            moduleSettings = ModuleSettings.GetModuleSettings(moduleId);

            useSpamBlockingForAnonymous = WebUtils.ParseBoolFromHashtable(
                moduleSettings, "GroupEnableAntiSpamSetting", useSpamBlockingForAnonymous);

            includePostBodyInNotification = WebUtils.ParseBoolFromHashtable(
                moduleSettings, "IncludePostBodyInNotificationEmail", includePostBodyInNotification);



            if (useSpamBlockingForAnonymous)
            {
                captcha.ProviderName        = siteSettings.CaptchaProvider;
                captcha.Captcha.ControlID   = "captcha" + moduleId.ToString(CultureInfo.InvariantCulture);
                captcha.RecaptchaPrivateKey = siteSettings.RecaptchaPrivateKey;
                captcha.RecaptchaPublicKey  = siteSettings.RecaptchaPublicKey;
            }
        }
Пример #5
0
        public bool UserCanOnlyEditModuleAsDraft(int moduleId, Guid featureGuid)
        {
            if (!Request.IsAuthenticated)
            {
                return(false);
            }

            if (WebUser.IsAdminOrContentAdmin)
            {
                return(false);
            }

            if (SiteUtils.UserIsSiteEditor())
            {
                return(false);
            }

            if (!WebConfigSettings.EnableContentWorkflow)
            {
                return(false);
            }
            if (CurrentSite == null)
            {
                return(false);
            }
            if (!CurrentSite.EnableContentWorkflow)
            {
                return(false);
            }

            if (CurrentPage == null)
            {
                return(false);
            }

            bool moduleFoundOnPage = false;

            foreach (Module m in CurrentPage.Modules)
            {
                if (
                    (m.ModuleId == moduleId) &&
                    ((featureGuid == Guid.Empty) || (m.FeatureGuid == featureGuid))
                    )
                {
                    moduleFoundOnPage = true;
                }
            }

            if (!moduleFoundOnPage)
            {
                return(false);
            }

            if (WebUser.IsInRoles(CurrentPage.DraftEditOnlyRoles))
            {
                return(true);
            }

            SiteUser currentUser = SiteUtils.GetCurrentSiteUser();

            if (currentUser == null)
            {
                return(false);
            }

            foreach (Module m in CurrentPage.Modules)
            {
                if (m.ModuleId == moduleId)
                {
                    if (WebUser.IsInRoles(m.DraftEditRoles))
                    {
                        return(true);
                    }
                }
            }

            return(false);
        }
Пример #6
0
        private void LoadSettings()
        {
            timeOffset = SiteUtils.GetUserTimeOffset();
            timeZone   = SiteUtils.GetUserTimeZone();
            //lnkAllUsers.NavigateUrl = SiteRoot + "/MemberList.aspx";
            IsAdmin = WebUser.IsAdmin;

            ShowEmailInMemberList     = WebConfigSettings.ShowEmailInMemberList || displaySettings.ShowEmail;
            ShowUserIDInMemberList    = WebConfigSettings.ShowUserIDInMemberList || displaySettings.ShowUserId;
            ShowLoginNameInMemberList = WebConfigSettings.ShowLoginNameInMemberList || displaySettings.ShowLoginName;
            ShowJoinDate = displaySettings.ShowJoinDate;

            // this can't be used in related site mode because we can't assume forum posts were in this site.
            ShowForumPostColumn = WebConfigSettings.ShowForumPostsInMemberList && displaySettings.ShowForumPosts && !WebConfigSettings.UseRelatedSiteMode;

            allowView = WebUser.IsInRoles(siteSettings.RolesThatCanViewMemberList);

            if ((IsAdmin) || (WebUser.IsInRoles(siteSettings.RolesThatCanManageUsers)))
            {
                canManageUsers        = true;
                spnIPLookup.Visible   = true;
                btnFindLocked.Visible = true;
            }


            btnFindNotApproved.Visible = canManageUsers && siteSettings.RequireApprovalBeforeLogin;

            if (canManageUsers || WebUser.IsInRoles(siteSettings.RolesThatCanCreateUsers))
            {
                lnkNewUser.Visible     = true;
                lnkNewUser.Text        = Resource.MemberListAddUserLabel;
                lnkNewUser.NavigateUrl = SiteRoot + "/Admin/ManageUsers.aspx?userId=-1";
            }

            pageNumber = WebUtils.ParseInt32FromQueryString("pagenumber", 1);

            sortMode = WebUtils.ParseInt32FromQueryString("sd", sortMode);

            if ((sortMode == 0) && (displaySettings.ShowFirstAndLastName))
            {
                sortMode = 2; // lastname, firstname
            }

            if (Request.Params["letter"] != null)
            {
                userNameBeginsWith = Request.Params["letter"].Trim();
            }

            if (Request.Params["search"] != null)
            {
                searchText = Request.Params["search"].Trim();
            }

            showLocked     = WebUtils.ParseBoolFromQueryString("locked", showLocked);
            showUnApproved = WebUtils.ParseBoolFromQueryString("needapproval", showUnApproved);

            pageSize = WebConfigSettings.MemberListPageSize;

            mojoProfileConfiguration profileConfig = mojoProfileConfiguration.GetConfig();

            if (profileConfig != null)
            {
                if (profileConfig.Contains("WebSiteUrl"))
                {
                    mojoProfilePropertyDefinition webSiteUrlProperty = profileConfig.GetPropertyDefinition("WebSiteUrl");
                    if (
                        (webSiteUrlProperty.OnlyVisibleForRoles.Length == 0) ||
                        (WebUser.IsInRoles(webSiteUrlProperty.OnlyVisibleForRoles))
                        )
                    {
                        ShowWebSiteColumn = true;
                    }
                }
            }

            // displaySettings can be configured from theme.skin
            if (displaySettings.HideWebSiteColumn)
            {
                ShowWebSiteColumn = false;
            }

            if (displaySettings.TableCssClass.Length > 0)
            {
                tableClassMarkup = " class='" + displaySettings.TableCssClass + "'";
            }

            tableAttributes = displaySettings.TableAttributes;

            if (!ShowWebSiteColumn)
            {
                thWebLink.Visible = false;
            }
            if (!ShowJoinDate)
            {
                thJoinDate.Visible = false;
            }



            if (IsAdmin)
            {
                pnlAdminCrumbs.Visible = true;
            }

            if (!ShowForumPostColumn)
            {
                thForumPosts.Visible = false;
            }

            //this page has no content other than nav
            SiteUtils.AddNoIndexFollowMeta(Page);

            AddClassToBody("memberlist");

            if (displaySettings.TableCssClass == "jqtable")
            {
                ScriptConfig.IncludeJQTable = true;
            }
        }
Пример #7
0
        private void PopulateControls()
        {
            GroupTopic topic = null;

            if (topicId == -1)
            {
                this.btnDelete.Visible   = false;
                this.rptMessages.Visible = false;
                Title = SiteUtils.FormatPageTitle(siteSettings, CurrentPage.PageName + " - " + GroupResources.NewTopicLabel);
            }
            else
            {
                if (postId > -1)
                {
                    topic = new GroupTopic(topicId, postId);
                    if (WebUser.IsAdmin ||
                        (isSiteEditor) ||
                        (WebUser.IsInRoles(CurrentPage.EditRoles)) ||
                        ((this.theUser != null) && (this.theUser.UserId == topic.PostUserId))
                        )
                    {
                        this.txtSubject.Text = topic.PostSubject;
                        edMessage.Text       = topic.PostMessage;
                    }
                }
                else
                {
                    topic = new GroupTopic(topicId);
                    this.txtSubject.Text
                        = ResourceHelper.GetMessageTemplate(ResourceHelper.GetDefaultCulture(), "GroupPostReplyPrefix.config")
                          + topic.Subject;
                }

                if ((group != null) && (topic != null))
                {
                    Title = SiteUtils.FormatPageTitle(siteSettings, group.Title + " - " + topic.Subject);
                }

                if (groupId == -1)
                {
                    groupId = topic.GroupId;
                }

                using (IDataReader reader = topic.GetPostsReverseSorted())
                {
                    this.rptMessages.DataSource = reader;
                    this.rptMessages.DataBind();
                }
            }

            if (group != null)
            {
                litGroupPostLabel.Text   = group.Title;
                litGroupDescription.Text = group.Description;
            }

            if (postId == -1)
            {
                string hookupInputScript = "<script type=\"text/javascript\">"
                                           + "document.getElementById('" + this.txtSubject.ClientID + "').focus();</script>";

                if (!Page.ClientScript.IsStartupScriptRegistered("finitscript"))
                {
                    this.Page.ClientScript.RegisterStartupScript(
                        typeof(Page),
                        "finitscript", hookupInputScript);
                }
            }

            chkNotifyOnReply.Checked = isSubscribedToTopic;

            lnkPageCrumb.Text        = CurrentPage.PageName;
            lnkPageCrumb.NavigateUrl = SiteUtils.GetCurrentPageUrl();
            lnkGroup.HRef            = SiteRoot + "/Groups/GroupView.aspx?ItemID="
                                       + group.ItemId.ToInvariantString()
                                       + "&amp;pageid=" + pageId.ToInvariantString()
                                       + "&amp;mid=" + group.ModuleId.ToInvariantString();

            lnkGroup.InnerHtml = group.Title;
            if (topic != null)
            {
                lblTopicDescription.Text = Server.HtmlEncode(topic.Subject);
            }
        }
Пример #8
0
        private void PopulateControls()
        {
            if (forum == null)
            {
                return;
            }

            //TODO: need to look into this:
            // http://googlewebmastercentral.blogspot.com/2011/09/pagination-with-relnext-and-relprev.html
            //http://www.whatwg.org/specs/web-apps/current-work/multipage/links.html#sequential-link-types

            string pageUrl;

            if (ForumConfiguration.CombineUrlParams)
            {
                pageUrl = SiteRoot
                          + "/Forums/ForumView.aspx?pageid=" + PageId.ToInvariantString()
                          + "&amp;f=" + forum.ItemId.ToInvariantString()
                          + "~{0}";
            }
            else
            {
                pageUrl = SiteRoot
                          + "/Forums/ForumView.aspx?"
                          + "ItemID=" + forum.ItemId.ToInvariantString()
                          + "&amp;mid=" + ModuleId.ToInvariantString()
                          + "&amp;pageid=" + PageId.ToInvariantString()
                          + "&amp;pagenumber={0}";
            }

            pgrTop.PageURLFormat = pageUrl;
            pgrTop.ShowFirstLast = true;
            pgrTop.CurrentIndex  = pageNumber;
            pgrTop.PageSize      = forum.ThreadsPerPage;
            pgrTop.PageCount     = forum.TotalPages;
            pgrTop.Visible       = (pgrTop.PageCount > 1);

            pgrBottom.PageURLFormat = pageUrl;
            pgrBottom.ShowFirstLast = true;
            pgrBottom.CurrentIndex  = pageNumber;
            pgrBottom.PageSize      = forum.ThreadsPerPage;
            pgrBottom.PageCount     = forum.TotalPages;
            pgrBottom.Visible       = (pgrBottom.PageCount > 1);

            lnkNewThread.HRef = SiteRoot
                                + "/Forums/EditPost.aspx?forumid=" + ItemId.ToInvariantString()
                                + "&amp;pageid=" + PageId.ToInvariantString()
                                + "&amp;mid=" + ModuleId.ToInvariantString();

            lnkNewThreadBottom.HRef = lnkNewThread.HRef;

            lnkNewThread.Visible       = WebUser.IsInRoles(forum.RolesThatCanPost) && !forum.Closed;
            lnkNewThreadBottom.Visible = lnkNewThread.Visible;

            lnkLogin.Visible = !lnkNewThread.Visible && !Request.IsAuthenticated;



            using (IDataReader reader = forum.GetThreads(pageNumber))
            {
                rptForums.DataSource = reader;

#if MONO
                this.rptForums.DataBind();
#else
                this.DataBind();
#endif
            }
        }
Пример #9
0
        private bool ShouldRender(gbSiteMapNode mapNode)
        {
            if (mapNode == null)
            {
                return(false);
            }

            if (
                languageId > 0 &&
                mapNode["Title" + languageId.ToString()] == null
                )
            {
                return(false);
            }

            if (mapNode.Roles == null)
            {
                if ((!isAdmin) && (!isContentAdmin) && (!isSiteEditor))
                {
                    return(false);
                }
            }
            else
            {
                if ((!isAdmin) && (mapNode.Roles.Count == 1) && (mapNode.Roles[0].ToString() == "Admins"))
                {
                    return(false);
                }

                if ((!isAdmin) && (!isContentAdmin) && (!isSiteEditor) && (!WebUser.IsInRoles(mapNode.Roles)))
                {
                    return(false);
                }
            }

            //if (!mapNode.IncludeInMenu && config.IsSubMenu) { return false; }
            if (!mapNode.IsPublished)
            {
                return(false);
            }

            if (config.ZonePosition > 0)
            {
                if ((mapNode.Position & config.ZonePosition) == 0)
                {
                    return(false);
                }
            }

            if ((mapNode.HideAfterLogin) && (Page.Request.IsAuthenticated))
            {
                return(false);
            }

            if ((!isMobileSkin) && (mapNode.PublishMode == mobileOnly))
            {
                return(false);
            }

            if ((isMobileSkin) && (mapNode.PublishMode == webOnly))
            {
                return(false);
            }

            return(true);
        }
Пример #10
0
        public ReturnObject GetModuleItems(RequestObject r)
        {
            siteSettings = CacheHelper.GetCurrentSiteSettings();
            currentPage  = new PageSettings(siteSettings.SiteId, r.PageId);
            bool allowed = false;
            bool canEdit = false;

            if (currentPage != null)
            {
                allowed = WebUser.IsInRoles(currentPage.AuthorizedRoles);
            }
            module = new Module(r.ModuleId);
            if (module != null)
            {
                allowed = WebUser.IsInRoles(module.ViewRoles);
            }
            if (!allowed)
            {
                return(new ReturnObject()
                {
                    Status = "error",
                    ExtraData = new Dictionary <string, string>
                    {
                        ["ErrorCode"] = "100",
                        ["ErrorMessage"] = "Not Allowed"
                    }
                });
            }

            config = new ModuleConfiguration(module);

            int         totalPages = 0;
            int         totalRows  = 0;
            List <Item> items      = new List <Item>();

            if (r.SearchObject != null && r.SearchObject.Count > 0)
            {
                foreach (var set in r.SearchObject)
                {
                    if (set.Value.Contains(";"))
                    {
                        foreach (var setA in set.Value.SplitOnCharAndTrim(';'))
                        {
                            items.AddRange(GetItems(
                                               module.ModuleGuid,
                                               r.PageNumber,
                                               r.PageSize,
                                               out totalPages,
                                               out totalRows,
                                               setA,
                                               set.Key,
                                               r.GetAllForSolution
                                               ));
                        }
                    }
                    else
                    {
                        items.AddRange(GetItems(
                                           module.ModuleGuid,
                                           r.PageNumber,
                                           r.PageSize,
                                           out totalPages,
                                           out totalRows,
                                           set.Value,
                                           set.Key,
                                           r.GetAllForSolution
                                           ));
                    }
                    //we have to figure out paging with this
                }
                items = items.Distinct(new SimpleItemComparer()).ToList();
            }
            else
            {
                items.AddRange(GetItems(
                                   module.ModuleGuid,
                                   r.PageNumber,
                                   r.PageSize,
                                   out totalPages,
                                   out totalRows,
                                   r.SearchTerm,
                                   r.SearchField,
                                   r.GetAllForSolution,
                                   r.SortDescending));
            }

            List <PopulatedItem> popItems = new List <PopulatedItem>();
            SuperFlexiObject     sfObject = new SuperFlexiObject()
            {
                FriendlyName    = config.ModuleFriendlyName,
                ModuleTitle     = module.ModuleTitle,
                GlobalSortOrder = config.GlobalViewSortOrder,
                Items           = popItems
            };

            if (items != null && items.Count > 0)
            {
                List <Field>          fields            = Field.GetAllForDefinition(config.FieldDefinitionGuid).Where(f => f.ControlType != "InstructionBlock").ToList();
                var                   itemGuids         = items.Select(x => x.ItemGuid).ToList();
                List <ItemFieldValue> values            = ItemFieldValue.GetByItemGuids(itemGuids);
                Module                itemModule        = null;
                Guid                  currentModuleGuid = Guid.Empty;
                foreach (Item item in items.OrderBy(x => x.ModuleID).ToList())
                {
                    if (item.ModuleGuid != currentModuleGuid)
                    {
                        currentModuleGuid = item.ModuleGuid;
                        itemModule        = new Module(item.ModuleGuid);
                    }
                    if (itemModule == null)
                    {
                        continue;
                    }
                    if (!WebUser.IsInRoles(itemModule.ViewRoles))
                    {
                        continue;
                    }
                    var populatedItem = new PopulatedItem(item, fields, values.Where(v => v.ItemGuid == item.ItemGuid).ToList(), canEdit);
                    if (populatedItem != null)
                    {
                        if (r.SearchObject != null && r.SearchObject.Count > 0)
                        {
                            int matchCount = 0;
                            foreach (var searchItem in r.SearchObject)
                            {
                                var           value              = populatedItem.Values[searchItem.Key];
                                List <string> itemValArray       = value as List <string>;
                                List <string> searchItemValArray = searchItem.Value.SplitOnCharAndTrim(';');
                                //log.Info($"[{searchItem.Key}]={searchItem.Value}");

                                /*  Check if itemValArray == null because if it is, that means the value is just a plain value, not a List<string>.
                                 *  If we try to do a comparison on value.ToString() when value is a List<string>, .ToString() returns System.Collections.Generic...
                                 *  and then our comparison is actually looking for matches in "System.Collections.Generic...". We had that happen with the word
                                 *  "Collections". Oops.
                                 */

                                if ((itemValArray == null && value.ToString().ToLower().IndexOf(searchItem.Value.ToLower()) >= 0) ||
                                    (itemValArray != null && itemValArray.Any(s => s.Equals(searchItem.Value, StringComparison.OrdinalIgnoreCase))) ||
                                    (searchItemValArray != null && searchItemValArray.Any(s => s.Equals(value.ToString(), StringComparison.OrdinalIgnoreCase))))
                                {
                                    matchCount++;
                                }
                            }

                            if (matchCount == r.SearchObject.Count)
                            {
                                popItems.Add(populatedItem);
                            }
                        }
                        else
                        {
                            popItems.Add(populatedItem);
                        }
                    }
                }
            }

            return(new ReturnObject()
            {
                Status = "success",
                Data = sfObject,
                TotalPages = totalPages,
                TotalRows = totalRows > popItems.Count ? totalRows : popItems.Count,
                AllowEdit = ShouldAllowEdit(),
                CmsModuleId = module.ModuleId,
                CmsPageId = module.PageId
            });
        }
Пример #11
0
        public ReturnObject GetFieldValues(RequestObject r)
        {
            siteSettings = CacheHelper.GetCurrentSiteSettings();
            currentPage  = new PageSettings(siteSettings.SiteId, r.PageId);
            bool allowed = false;

            if (currentPage != null)
            {
                allowed = WebUser.IsInRoles(currentPage.AuthorizedRoles);
            }
            module = new Module(r.ModuleId);
            if (module != null)
            {
                allowed = WebUser.IsInRoles(module.ViewRoles);
            }
            if (!allowed)
            {
                return(new ReturnObject()
                {
                    Status = "error",
                    ExtraData = new Dictionary <string, string>
                    {
                        ["ErrorCode"] = "100",
                        ["ErrorMessage"] = "Not Allowed"
                    }
                });
            }

            config = new ModuleConfiguration(module);

            int totalPages = 0;
            int totalRows  = 0;

            var fieldValues = ItemFieldValue.GetPageOfValues(
                module.ModuleGuid,
                config.FieldDefinitionGuid,
                r.Field,
                r.PageNumber,
                r.PageSize,
                out totalPages,
                out totalRows);

            //much of the below is temporary, we needed to implement in a hurry
            //to-do: implement distinct on sql side
            List <string> values = new List <string>();

            var dbField = new Field(fieldValues.Select(fv => fv.FieldGuid).FirstOrDefault());

            switch (dbField.ControlType)
            {
            case "DynamicCheckBoxList":
                foreach (var val in fieldValues)
                {
                    values.AddRange(val.FieldValue.SplitOnCharAndTrim(';'));
                }
                break;

            default:
                values = fieldValues.Select(fv => fv.FieldValue).ToList();
                break;
                //we will add the other cases later
            }

            values = values.Distinct().OrderBy(v => v).ToList();

            totalRows = values.Count();

            return(new ReturnObject()
            {
                Status = "success",
                Data = values,
                TotalPages = totalPages,
                TotalRows = totalRows
            });
        }
Пример #12
0
        private void LoadSettings(HttpContext context)
        {
            siteSettings = CacheHelper.GetCurrentSiteSettings();
            if (siteSettings == null)
            {
                return;
            }

            //this is only used to resolve the paths since httphandler does not have it built in

            page.AppRelativeVirtualPath = context.Request.AppRelativeCurrentExecutionFilePath;

            FileSystemProvider p = FileSystemManager.Providers[WebConfigSettings.FileSystemProvider];

            if (p == null)
            {
                log.Error("Could not load file system provider " + WebConfigSettings.FileSystemProvider);
                return;
            }

            fileSystem = p.GetFileSystem();
            if (fileSystem == null)
            {
                log.Error("Could not load file system from provider " + WebConfigSettings.FileSystemProvider);
                return;
            }

            rootDir = fileSystem.VirtualRoot.Replace("~", string.Empty);

            if ((WebUser.IsAdminOrContentAdmin) || (SiteUtils.UserIsSiteEditor()))
            {
                allowedExtensions = WebConfigSettings.AllowedUploadFileExtensions;
                canView           = true;
            }
            else if (WebUser.IsInRoles(siteSettings.GeneralBrowseAndUploadRoles))
            {
                allowedExtensions = WebConfigSettings.AllowedUploadFileExtensions;
                canView           = true;
            }
            else if (WebUser.IsInRoles(siteSettings.UserFilesBrowseAndUploadRoles))
            {
                currentUser = SiteUtils.GetCurrentSiteUser();
                if (currentUser == null)
                {
                    return;
                }
                allowedExtensions = WebConfigSettings.AllowedLessPriveledgedUserUploadFileExtensions;
                canView           = true;
            }

            if (!canView)
            {
                return;
            }

            currentDir = rootDir;

            if (context.Request.Params.Get("dir") != null)
            {
                string requestedDir = context.Server.UrlDecode(context.Request.Params.Get("dir"));

                if (requestedDir == "/Pages/")
                {
                    currentDir = requestedDir;
                }
                else
                {
                    if (IsChildDirectory(context, requestedDir))
                    {
                        currentDir = requestedDir;;
                    }
                }
            }

            ResolveType(context);
        }
Пример #13
0
        private void PopulateLabels()
        {
            Title = SiteUtils.FormatPageTitle(siteSettings, Resource.AdminMenuHeading);

            heading.Text = Resource.AdminMenuHeading;

            liSiteSettings.Visible      = IsAdminOrContentAdmin || isSiteEditor;
            lnkSiteSettings.Text        = Resource.AdminMenuSiteSettingsLink;
            lnkSiteSettings.NavigateUrl = SiteRoot + "/Admin/SiteSettings.aspx";

            liSiteList.Visible      = ((WebConfigSettings.AllowMultipleSites) && (siteSettings.IsServerAdminSite) && IsAdmin);
            lnkSiteList.Text        = Resource.SiteList;
            lnkSiteList.NavigateUrl = SiteRoot + "/Admin/SiteList.aspx";

            lnkSecurityAdvisor.Text        = Resource.SecurityAdvisor;
            lnkSecurityAdvisor.NavigateUrl = SiteRoot + "/Admin/SecurityAdvisor.aspx";
            if (IsAdmin && siteSettings.IsServerAdminSite)
            {
                liSecurityAdvisor.Visible = true;
                if (!securityAdvisor.UsingCustomMachineKey())
                {
                    liSecurityAdvisor.Attributes["class"] += " secwarning";
                    lnkSecurityAdvisor.Text = Resource.SecurityAdvisorNeedsAttention;
                }
            }

            liCommerceReports.Visible      = (isCommerceReportViewer && (commerceConfig != null) && (commerceConfig.IsConfigured));
            lnkCommerceReports.Text        = Resource.CommerceReportsLink;
            lnkCommerceReports.NavigateUrl = SiteRoot + "/Admin/SalesSummary.aspx";

            liContentManager.Visible      = (IsAdminOrContentAdmin || isSiteEditor);
            lnkContentManager.Text        = Resource.AdminMenuContentManagerLink;
            lnkContentManager.NavigateUrl = SiteRoot + "/Admin/ContentCatalog.aspx";

            liContentWorkFlow.Visible      = (WebConfigSettings.EnableContentWorkflow && siteSettings.EnableContentWorkflow);
            lnkContentWorkFlow.Visible     = siteSettings.EnableContentWorkflow && WebUser.IsAdminOrContentAdminOrContentPublisher;
            lnkContentWorkFlow.Text        = Resource.AdminMenuContentWorkflowLabel;
            lnkContentWorkFlow.NavigateUrl = SiteRoot + "/Admin/ContentWorkflow.aspx";

            liContentTemplates.Visible      = (IsAdminOrContentAdmin || isSiteEditor || (WebUser.IsInRoles(siteSettings.RolesThatCanEditContentTemplates)));
            lnkContentTemplates.Text        = Resource.ContentTemplates;
            lnkContentTemplates.NavigateUrl = SiteRoot + "/Admin/ContentTemplates.aspx";

            liStyleTemplates.Visible      = (IsAdminOrContentAdmin || isSiteEditor || (WebUser.IsInRoles(siteSettings.RolesThatCanEditContentTemplates)));
            lnkStyleTemplates.Text        = Resource.ContentStyleTemplates;
            lnkStyleTemplates.NavigateUrl = SiteRoot + "/Admin/ContentStyles.aspx";

            liPageTree.Visible      = (IsAdminOrContentAdmin || isSiteEditor || (SiteMapHelper.UserHasAnyCreatePagePermissions(siteSettings)));
            lnkPageTree.Text        = Resource.AdminMenuPageTreeLink;
            lnkPageTree.NavigateUrl = SiteRoot + WebConfigSettings.PageTreeRelativeUrl;

            liRoleAdmin.Visible      = (WebUser.IsRoleAdmin || IsAdmin);
            lnkRoleAdmin.Text        = Resource.AdminMenuRoleAdminLink;
            lnkRoleAdmin.NavigateUrl = SiteRoot + "/Admin/RoleManager.aspx";

            liPermissions.Visible          = IsAdmin;
            lnkPermissionAdmin.Text        = Resource.SiteSettingsPermissionsTab;
            lnkPermissionAdmin.NavigateUrl = SiteRoot + "/Admin/PermissionsMenu.aspx";

            if ((WebConfigSettings.UseRelatedSiteMode) && (WebConfigSettings.RelatedSiteModeHideRoleManagerInChildSites))
            {
                if (siteSettings.SiteId != WebConfigSettings.RelatedSiteID)
                {
                    liRoleAdmin.Visible = false;
                }
            }


            //
            // File Manager Link
            //
            //liFileManager.Visible = IsAdminOrContentAdmin;

            //if ((!siteSettings.IsServerAdminSite) && (!WebConfigSettings.AllowFileManagerInChildSites))
            //{
            //	liFileManager.Visible = false;
            //}

            //if (WebConfigSettings.DisableFileManager)
            //{
            //	liFileManager.Visible = false;
            //}

            //lnkFileManager.Text = Resource.AdminMenuFileManagerLink;
            //lnkFileManager.NavigateUrl = SiteRoot + "/FileManager";


            //
            // Member List
            //
            lnkMemberList.Text        = Resource.MemberListLink;
            lnkMemberList.NavigateUrl = SiteRoot + WebConfigSettings.MemberListUrl;
            lnkMemberList.Visible     = ((WebUser.IsInRoles(siteSettings.RolesThatCanViewMemberList)) || (WebUser.IsInRoles(siteSettings.RolesThatCanLookupUsers)));

            liAddUser.Visible      = ((WebUser.IsInRoles(siteSettings.RolesThatCanCreateUsers)) || (WebUser.IsInRoles(siteSettings.RolesThatCanManageUsers)) || (WebUser.IsInRoles(siteSettings.RolesThatCanLookupUsers)));
            lnkAddUser.Text        = Resource.MemberListAddUserLabel;
            lnkAddUser.NavigateUrl = SiteRoot + "/Admin/ManageUsers.aspx?userId=-1";

            if (WebConfigSettings.EnableNewsletter)
            {
                liNewsletter.Visible      = (IsAdmin || isSiteEditor || WebUser.IsNewsletterAdmin);
                lnkNewsletter.Text        = Resource.AdminMenuNewsletterAdminLabel;
                lnkNewsletter.NavigateUrl = SiteRoot + "/eletter/Admin.aspx";

                //liTaskQueue.Visible = IsAdmin || WebUser.IsNewsletterAdmin;
                //lnkTaskQueue.Text = Resource.TaskQueueMonitorHeading;
                //lnkTaskQueue.NavigateUrl = SiteRoot + "/Admin/TaskQueueMonitor.aspx";
            }
            else
            {
                liNewsletter.Visible = false;
                //liTaskQueue.Visible = false;
            }

            liRegistrationAgreement.Visible      = (IsAdminOrContentAdmin);
            lnkRegistrationAgreement.Text        = Resource.RegistrationAgreementLink;
            lnkRegistrationAgreement.NavigateUrl = SiteRoot + "/Admin/EditRegistrationAgreement.aspx";

            liLoginInfo.Visible      = (IsAdminOrContentAdmin) && !WebConfigSettings.DisableLoginInfo;
            lnkLoginInfo.Text        = Resource.LoginPageContent;
            lnkLoginInfo.NavigateUrl = SiteRoot + "/Admin/EditLoginInfo.aspx";



            liCoreData.Visible      = (IsAdminOrContentAdmin && siteSettings.IsServerAdminSite);
            lnkCoreData.Text        = Resource.CoreDataAdministrationLink;
            lnkCoreData.NavigateUrl = SiteRoot + "/Admin/CoreData.aspx";

            liAdvancedTools.Visible      = (IsAdminOrContentAdmin || isSiteEditor);
            lnkAdvancedTools.Text        = Resource.AdvancedToolsLink;
            lnkAdvancedTools.NavigateUrl = SiteRoot + "/Admin/AdvancedTools.aspx";


            liServerInfo.Visible      = (IsAdminOrContentAdmin || isSiteEditor) && (siteSettings.IsServerAdminSite || WebConfigSettings.ShowSystemInformationInChildSiteAdminMenu);
            lnkServerInfo.Text        = Resource.AdminMenuServerInfoLabel;
            lnkServerInfo.NavigateUrl = SiteRoot + "/Admin/ServerInformation.aspx";

            liLogViewer.Visible      = IsAdmin && siteSettings.IsServerAdminSite && WebConfigSettings.EnableLogViewer;
            lnkLogViewer.Text        = Resource.AdminMenuServerLogLabel;
            lnkLogViewer.NavigateUrl = SiteRoot + "/Admin/ServerLog.aspx";

            liDesignTools.Visible      = IsAdmin || WebUser.IsContentAdmin || WebUser.IsInRoles(siteSettings.RolesThatCanManageSkins);
            lnkDesignTools.Text        = DevTools.DesignTools;
            lnkDesignTools.NavigateUrl = SiteRoot + "/DesignTools/Default.aspx";
        }
Пример #14
0
        public FileService.ReturnObject UploadFiles()
        {
            FileSystemProvider p = FileSystemManager.Providers[WebConfigSettings.FileSystemProvider];

            if (p == null)
            {
                log.Error(string.Format(Resource.FileSystemProviderNotLoaded, WebConfigSettings.FileSystemProvider));
                return(new FileService.ReturnObject(new FileService.ReturnMessage {
                    Success = false, Error = string.Format(Resource.FileSystemProviderNotLoaded, WebConfigSettings.FileSystemProvider)
                }));
            }

            fileSystem = p.GetFileSystem();
            if (fileSystem == null)
            {
                log.Error(string.Format(Resource.FileSystemNotLoadedFromProvider, WebConfigSettings.FileSystemProvider));
                return(new FileService.ReturnObject(new FileService.ReturnMessage {
                    Success = false, Error = string.Format(Resource.FileSystemNotLoadedFromProvider, WebConfigSettings.FileSystemProvider)
                }));
            }

            virtualPath = fileSystem.VirtualRoot;
            var context = HttpContext.Current;
            HttpFileCollection files        = context.Request.Files.Count > 0 ? context.Request.Files : null;
            OpResult           results      = OpResult.Error;
            StringBuilder      errors       = new StringBuilder();
            SiteSettings       siteSettings = CacheHelper.GetCurrentSiteSettings();
            string             uploadPath   = virtualPath;
            bool canUpload = (
                WebUser.IsAdminOrContentAdmin ||
                SiteUtils.UserIsSiteEditor() ||
                WebUser.IsInRoles(siteSettings.GeneralBrowseAndUploadRoles) ||
                WebUser.IsInRoles(siteSettings.UserFilesBrowseAndUploadRoles) ||
                WebUser.IsInRoles(siteSettings.RolesThatCanDeleteFilesInEditor)
                );

            if (files.Count == 0)
            {
                log.Info(Resource.NoFileSelectedWarning);
                return(new FileService.ReturnObject(new FileService.ReturnMessage {
                    Success = false, Error = Resource.NoFileSelectedWarning
                }));
            }

            if (WebConfigSettings.DisableFileManager)
            {
                log.Info(Resource.FileManagerDisabledMessage);
                return(new FileService.ReturnObject(new FileService.ReturnMessage {
                    Success = false, Error = Resource.FileManagerDisabledMessage
                }));
            }

            if (siteSettings == null)
            {
                return(new FileService.ReturnObject(new FileService.ReturnMessage {
                    Success = false, Error = Resource.FileSystemSiteSettingsNotLoaded
                }));
            }

            if (!canUpload)
            {
                return(new FileService.ReturnObject(new FileService.ReturnMessage {
                    Success = false, Error = Resource.AccessDenied
                }));
            }

            if (context.Request.Form.Get("destination") != null)
            {
                uploadPath = FilePath(VirtualPathUtility.AppendTrailingSlash(context.Request.Form.Get("destination")));
            }

            if (files != null)
            {
                var fileUploadsRemaining = fileSystem.Permission.MaxFiles - fileSystem.CountAllFiles();

                if (fileUploadsRemaining < files.Count)
                {
                    log.Info("upload rejected due to fileSystem.Permission.MaxFiles");

                    string errorMessage;

                    if (fileUploadsRemaining == 0)
                    {
                        errorMessage = Resource.FileSystemFileLimitReached;
                    }
                    else
                    {
                        errorMessage = string.Format(Resource.FileSystemFileLimitRemainder, fileUploadsRemaining);
                    }

                    return(new FileService.ReturnObject(new FileService.ReturnMessage {
                        Success = false, Error = errorMessage
                    }));
                }

                for (int f = 0; f < files.Count; f++)
                {
                    HttpPostedFile file     = files[f];
                    bool           doUpload = true;

                    if (file.ContentLength > fileSystem.Permission.MaxSizePerFile)
                    {
                        log.Info(Resource.FileSystemFileTooLargeError);
                        errors.AppendLine(Resource.FileSystemFileTooLargeError);
                        doUpload = false;
                    }
                    else if (fileSystem.GetTotalSize() + file.ContentLength >= fileSystem.Permission.Quota)
                    {
                        log.Info(Resource.FileSystemStorageQuotaError);
                        errors.AppendLine(Resource.FileSystemStorageQuotaError);
                        doUpload = false;
                    }

                    if (!fileSystem.Permission.IsExtAllowed(VirtualPathUtility.GetExtension(file.FileName)))
                    {
                        log.Info(Resource.FileTypeNotAllowed);
                        errors.AppendLine(Resource.FileTypeNotAllowed);
                        doUpload = false;
                    }

                    string destPath = VirtualPathUtility.Combine(uploadPath, Path.GetFileName(file.FileName).ToCleanFileName(WebConfigSettings.ForceLowerCaseForUploadedFiles));

                    string ext      = Path.GetExtension(file.FileName);
                    string mimeType = file.ContentType;

                    if (doUpload)
                    {
                        using (Stream s = file.InputStream)
                        {
                            results = fileSystem.SaveFile(destPath, s, mimeType, true);
                        }

                        if (results != OpResult.Succeed)
                        {
                            errors.AppendLine(results.ToString());
                        }
                    }
                }

                if (errors.Length > 0)
                {
                    return(new FileService.ReturnObject(new FileService.ReturnMessage {
                        Success = false, Error = errors.ToString()
                    }));
                }

                return(new FileService.ReturnObject(new FileService.ReturnMessage {
                    Success = true
                }));
            }
            else
            {
                return(new FileService.ReturnObject(new FileService.ReturnMessage {
                    Success = false, Error = Resource.NoFileSelectedWarning
                }));
            }
        }
Пример #15
0
        private void RenderChildPageBreadcrumbs()
        {
            if (HttpContext.Current == null)
            {
                return;
            }

            if (currentPageNode == null)
            {
                currentPageNode = SiteUtils.GetCurrentPageSiteMapNode(siteMapDataSource.Provider.RootNode);
            }
            if (currentPageNode == null)
            {
                return;
            }

            markup = new StringBuilder();
            markup.Append(Separator);
            string childSeparator = string.Empty;

            int addedChildren = 0;

            foreach (SiteMapNode childNode in currentPageNode.ChildNodes)
            {
                if (!(childNode is mojoSiteMapNode))
                {
                    continue;
                }

                mojoSiteMapNode node = childNode as mojoSiteMapNode;

                if (!node.IncludeInMenu)
                {
                    continue;
                }

                bool remove = false;

                if (node.Roles == null)
                {
                    if ((!isAdmin) && (!isContentAdmin) && (!isSiteEditor))
                    {
                        remove = true;
                    }
                }
                else
                {
                    if ((!isAdmin) && (node.Roles.Count == 1) && (node.Roles[0].ToString() == "Admins"))
                    {
                        remove = true;
                    }

                    if ((!isAdmin) && (!isContentAdmin) && (!isSiteEditor) && (!WebUser.IsInRoles(node.Roles)))
                    {
                        remove = true;
                    }
                }

                if (!remove)
                {
                    markup.Append(childSeparator + "<a class='"
                                  + this.cssClass + "' href='"
                                  + Page.ResolveUrl(node.Url)
                                  + "'>"
                                  + node.Title + "</a>");

                    childSeparator = " - ";

                    addedChildren += 1;
                }
            }

            // this gets rid of the initial separator between bread crumbs and child crumbs if no children were rendered
            if (addedChildren == 0)
            {
                markup = null;
            }
        }
Пример #16
0
        private bool ShouldRender()
        {
            if (basePage == null)
            {
                return(false);
            }

            if (!Page.Request.IsAuthenticated)
            {
                return(false);
            }

            if (!WebConfigSettings.ShowFileManagerLink)
            {
                return(false);
            }

            if (WebConfigSettings.DisableFileManager)
            {
                return(false);
            }

            if (basePage.SiteInfo == null)
            {
                return(false);
            }

            if ((!CacheHelper.GetCurrentSiteSettings().IsServerAdminSite) && (!WebConfigSettings.AllowFileManagerInChildSites))
            {
                return(false);
            }

            if (SiteUtils.UserIsSiteEditor())
            {
                return(true);
            }

            // Only roles that can delete can use File Manager
            if (!WebUser.IsInRoles(basePage.SiteInfo.RolesThatCanDeleteFilesInEditor))
            {
                return(false);
            }

            if (WebUser.IsInRoles(basePage.SiteInfo.UserFilesBrowseAndUploadRoles) || WebUser.IsInRoles(basePage.SiteInfo.GeneralBrowseAndUploadRoles))
            {
                return(true);
            }

            return(false);
        }
Пример #17
0
        private void LoadPage()
        {
            EnsurePageAndSite();
            if (CurrentPage == null)
            {
                return;
            }
            LoadSettings();
            EnforceSecuritySettings();
            bool redirected = RedirectIfNeeded();

            if (redirected)
            {
                return;
            }
            SetupAdminLinks();
            if (CurrentPage.PageId == -1)
            {
                return;
            }

            if ((CurrentPage.ShowChildPageMenu) ||
                (CurrentPage.ShowBreadcrumbs) ||
                (CurrentPage.ShowChildPageBreadcrumbs)
                )
            {
                // this is needed to override some hide logic in
                // layout.Master.cs
                this.MPContent.Visible        = true;
                this.MPContent.Parent.Visible = true;
            }


            if (CurrentPage.PageTitle.Length > 0)
            {
                Title = Server.HtmlEncode(CurrentPage.PageTitle);
            }
            else
            {
                Title = SiteUtils.FormatPageTitle(siteSettings, CurrentPage.PageName);
            }

            if (CurrentPage.PageMetaKeyWords.Length > 0)
            {
                MetaKeywordCsv = CurrentPage.PageMetaKeyWords;
            }


            if (CurrentPage.PageMetaDescription.Length > 0)
            {
                MetaDescription = CurrentPage.PageMetaDescription;
            }


            if (CurrentPage.CompiledMeta.Length > 0)
            {
                AdditionalMetaMarkup = CurrentPage.CompiledMeta;
            }

            if ((Page.Header != null) && (CurrentPage.UseUrl) && (CurrentPage.Url.Length > 0))
            {
                string urlToUse = SiteRoot + CurrentPage.Url.Replace("~/", "/");
                if (CurrentPage.CanonicalOverride.Length > 0)
                {
                    urlToUse = CurrentPage.CanonicalOverride;
                }
                using (Literal link = new Literal {
                    ID = "pageurl", Text = String.Format("\n<link rel='canonical' href='{0}' />", urlToUse)
                })
                {
                    Page.Header.Controls.Add(link);
                }
            }

            if (CurrentPage.Modules.Count == 0)
            {
                return;
            }

            foreach (Module module in CurrentPage.Modules)
            {
                if (!ModuleIsVisible(module))
                {
                    continue;
                }
                if (!WebUser.IsInRoles(module.ViewRoles))
                {
                    continue;
                }

                Control parent = this.MPContent;

                if (StringHelper.IsCaseInsensitiveMatch(module.PaneName, "leftpane"))
                {
                    parent = this.MPLeftPane;
                }

                if (StringHelper.IsCaseInsensitiveMatch(module.PaneName, "rightpane"))
                {
                    parent = this.MPRightPane;
                }

                if (StringHelper.IsCaseInsensitiveMatch(module.PaneName, "altcontent1"))
                {
                    if (AltPane1 != null)
                    {
                        parent = this.AltPane1;
                    }
                    else
                    {
                        log.Error("Content is assigned to altcontent1 placeholder but it does not exist in layout.master so using center.");
                        parent = this.MPContent;
                    }
                }

                if (StringHelper.IsCaseInsensitiveMatch(module.PaneName, "altcontent2"))
                {
                    if (AltPane2 != null)
                    {
                        parent = this.AltPane2;
                    }
                    else
                    {
                        log.Error("Content is assigned to altcontent2 placeholder but it does not exist in layout.master so using center.");
                        parent = this.MPContent;
                    }
                }

                // 2008-10-04 since more an more of our features use postback via ajax
                // its not feasible to use output caching as this breaks postback,
                // so I changed the default the use of WebConfigSettings.DisableContentCache to true
                // this also reduces the memory consumption footprint

                if ((module.CacheTime == 0) || (WebConfigSettings.DisableContentCache))
                {
                    //2008-10-16 in ulu's blog post:http://dotfresh.blogspot.com/2008/10/in-search-of-developer-friendly-cms.html
                    // he complains about having to inherit from a base class (SiteModuleControl) to make a plugin.
                    // he wishes he could just use a UserControl
                    // While SiteModuleControl "is a" UserControl that provides additional functionality
                    // Its easy enough to support using
                    // a plain UserControl so I'm making the needed change here now.
                    // The drawback of a plain UserControl is that is not reusable in the same way as SiteModuleControl.
                    // If you use a plain UserControl, its going to be exactly the same on any page you use it on.
                    // It has no instance specific properties.
                    // SiteModuleControl gives you instance specific ids and internal tracking of which instance this is so
                    // that you can have different instances.
                    // For example the Blog is instance specific, if you put a blog on one page and then put a blog on another page
                    // those are 2 different blogs with different content.
                    // However, if you don't need a re-usable feature with instance specific properties
                    // you are now free to use a plain old UserControl and I think freedom is a good thing
                    // so this was valuable feedback from ulu.
                    // Those who do need instance specific features should read my developer Guidelines for building one:
                    //http://www.vivasky.com/addingfeatures.aspx

                    Control c = Page.LoadControl("~/" + module.ControlSource);
                    if (c == null)
                    {
                        continue;
                    }

                    if (c is SiteModuleControl)
                    {
                        SiteModuleControl siteModule = (SiteModuleControl)c;
                        siteModule.SiteId = siteSettings.SiteId;
                        siteModule.ModuleConfiguration = module;

                        if (siteModule is IWorkflow)
                        {
                            countOfIWorkflow += 1;
                        }
                    }



                    parent.Controls.Add(c);
                }
                else
                {
                    using (CachedSiteModuleControl siteModule = new CachedSiteModuleControl {
                        SiteId = siteSettings.SiteId, ModuleConfiguration = module
                    })
                    {
                        parent.Controls.Add(siteModule);
                    }
                }

                parent.Visible        = true;
                parent.Parent.Visible = true;
            } //end foreach

            if ((!WebConfigSettings.DisableExternalCommentSystems) && (siteSettings != null) && (CurrentPage != null) && (CurrentPage.EnableComments))
            {
                switch (siteSettings.CommentProvider)
                {
                case "disqus":

                    if (siteSettings.DisqusSiteShortName.Length > 0)
                    {
                        using (DisqusWidget disqus = new DisqusWidget())
                        {
                            disqus.SiteShortName = siteSettings.DisqusSiteShortName;
                            disqus.WidgetPageUrl = SiteUtils.GetCurrentPageUrl();
                            disqus.RenderWidget  = true;
                            MPContent.Controls.Add(disqus);
                        }
                    }

                    break;

                case "intensedebate":

                    if (siteSettings.IntenseDebateAccountId.Length > 0)
                    {
                        using (IntenseDebateDiscussion d = new IntenseDebateDiscussion())
                        {
                            d.AccountId = siteSettings.IntenseDebateAccountId;
                            d.PostUrl   = SiteUtils.GetCurrentPageUrl();
                            MPContent.Controls.Add(d);
                        }
                    }

                    break;
                }
            }

            if (WebConfigSettings.HidePageViewModeIfNoWorkflowItems && (countOfIWorkflow == 0))
            {
                HideViewSelector();
            }

            // (to show the last mnodified time of a page we may have this control in layout.master, but I set it invisible by default
            // because we only want to show it on content pages not edit pages
            // since Default.aspx.cs is the handler for content pages, we look for it here and make it visible.
            Control pageLastMod = Master.FindControl("pageLastMod");

            if (pageLastMod != null)
            {
                pageLastMod.Visible = true;
            }
        }
Пример #18
0
        private void PopulateControls()
        {
            if (forum == null)
            {
                return;
            }
            if (thread == null)
            {
                return;
            }

            if ((thread.TotalReplies + 1) == forum.PostsPerPage)
            {
                nextPageNumber = PageNumber + 1;
            }
            else
            {
                nextPageNumber = PageNumber;
            }

            string pageUrl;
            string viewAllUrl = string.Empty;

            if (ForumConfiguration.CombineUrlParams)
            {
                pageUrl = SiteRoot
                          + "/Forums/Thread.aspx?pageid=" + PageId.ToInvariantString()
                          + "&amp;t=" + threadId.ToInvariantString()
                          + "~{0}";

                viewAllUrl = SiteRoot
                             + "/Forums/Thread.aspx?pageid=" + PageId.ToInvariantString()
                             + "&amp;t=" + threadId.ToInvariantString()
                             + "~-1";
            }
            else
            {
                pageUrl = SiteRoot
                          + "/Forums/Thread.aspx?pageid="
                          + PageId.ToInvariantString()
                          + "&amp;mid=" + moduleId.ToInvariantString()
                          + "&amp;ItemID=" + ItemId.ToInvariantString()
                          + "&amp;thread=" + threadId.ToInvariantString()
                          + "&amp;pagenumber={0}";
            }



            pgrTop.PageURLFormat = pageUrl;
            pgrTop.ShowFirstLast = true;
            pgrTop.CurrentIndex  = PageNumber;
            pgrTop.PageSize      = forum.ThreadsPerPage;
            pgrTop.PageCount     = thread.TotalPages;
            pgrTop.Visible       = (pgrTop.PageCount > 1);

            pgrBottom.PageURLFormat = pageUrl;
            pgrBottom.ShowFirstLast = true;
            pgrBottom.CurrentIndex  = PageNumber;
            pgrBottom.PageSize      = forum.ThreadsPerPage;
            pgrBottom.PageCount     = thread.TotalPages;
            pgrBottom.Visible       = (pgrBottom.PageCount > 1);

            if (ForumConfiguration.ShowPagerViewAllLink)
            {
                pgrTop.ViewAllUrl    = viewAllUrl;
                pgrBottom.ViewAllUrl = viewAllUrl;
            }


            lnkNewPost.InnerHtml = ForumResources.ForumThreadViewReplyLabel;

            lnkNewPost.HRef = SiteRoot
                              + "/Forums/EditPost.aspx?"
                              + "thread=" + threadId.ToString()
                              + "&amp;forumid=" + forum.ItemId.ToInvariantString()
                              + "&amp;mid=" + moduleId.ToInvariantString()
                              + "&amp;pageid=" + PageId.ToString()
                              + "&amp;pagenumber=" + nextPageNumber.ToInvariantString();

            lnkNewPost.Visible         = WebUser.IsInRoles(forum.RolesThatCanPost) && !forum.Closed;
            lnkNewPostBottom.Visible   = lnkNewPost.Visible;
            lnkNewPostBottom.InnerHtml = ForumResources.ForumThreadViewReplyLabel;
            lnkNewPostBottom.HRef      = lnkNewPost.HRef;

            lnkLogin.Visible       = !lnkNewPost.Visible && !Request.IsAuthenticated;
            lnkLoginBottom.Visible = lnkLogin.Visible;


            if ((thread.IsLocked || forum.Closed || thread.IsClosed(config.CloseThreadsOlderThanDays)) && (!isEditable))
            {
                lnkNewPost.Visible       = false;
                lnkNewPostBottom.Visible = false;
                lblClosedTop.Visible     = true;
                lblClosedBottom.Visible  = true;
            }

            //lnkLogin.NavigateUrl = SiteRoot + "/Secure/Login.aspx?returnurl=" + Server.UrlEncode(Request.RawUrl);
            lnkLogin.Text = ForumResources.ForumsLoginRequiredLink;

            //lnkLoginBottom.NavigateUrl = SiteRoot + "/Secure/Login.aspx?returnurl=" + Server.UrlEncode(Request.RawUrl);
            lnkLoginBottom.Text = ForumResources.ForumsLoginRequiredLink;

            if (useReverseSort)
            {
                using (IDataReader reader = thread.GetPostsReverseSorted())
                {
                    this.rptMessages.DataSource = reader;
                    this.rptMessages.DataBind();
                }

                pgrTop.Visible           = false;
                pgrBottom.Visible        = false;
                lnkNewPost.Visible       = false;
                lnkNewPostBottom.Visible = false;
            }
            else
            {
                if (PageNumber == -1)
                {
                    using (IDataReader reader = thread.GetPosts())
                    {
                        rptMessages.DataSource = reader;
                        rptMessages.DataBind();
                    }

                    if (thread.TotalPages <= 1)
                    {
                        pgrTop.Visible    = false;
                        pgrBottom.Visible = false;
                    }
                }
                else
                {
                    using (IDataReader reader = thread.GetPosts(PageNumber))
                    {
                        rptMessages.DataSource = reader;
                        rptMessages.DataBind();
                    }
                }

                if (
                    (rptMessages.Items.Count == 0) &&
                    (ItemId > -1)
                    )
                {
                    // when the last post in a thread is deleted
                    // the ForumPostEditPage redirects to this page
                    // but it will hit this code and go back to the forum instead of showing
                    // the empty thread
                    string redirectUrl;
                    if (ForumConfiguration.CombineUrlParams)
                    {
                        if (pageNumber > 1)
                        {   // try going back to page 1
                            redirectUrl = SiteRoot
                                          + "/Forums/Thread.aspx?pageid=" + PageId.ToInvariantString()
                                          + "&t=" + threadId.ToInvariantString() + "~1";
                        }
                        else
                        {
                            redirectUrl = SiteRoot
                                          + "/Forums/ForumView.aspx?pageid=" + PageId.ToInvariantString()
                                          + "&f=" + ItemId.ToInvariantString() + "~1";
                        }
                    }
                    else
                    {
                        redirectUrl = SiteRoot
                                      + "/Forums/ForumView.aspx?"
                                      + "ItemID=" + ItemId.ToInvariantString()
                                      + "&pageid=" + PageId.ToInvariantString()
                                      + "&mid=" + moduleId.ToInvariantString();
                    }

                    WebUtils.SetupRedirect(this, redirectUrl);
                }
                else
                {
                    thread.UpdateThreadViewStats();
                }
            }
        }
Пример #19
0
        protected override void Render(HtmlTextWriter writer)
        {
            if (HttpContext.Current == null)
            {
                writer.Write("[" + this.ID + "]");
                return;
            }


#if !MONO
            if (HttpContext.Current == null)
            {
                return;
            }

            siteSettings = CacheHelper.GetCurrentSiteSettings();
            if (siteSettings == null)
            {
                return;
            }
            if (!siteSettings.EnableMyPageFeature)
            {
                return;
            }

            if (WebUser.IsInRoles(siteSettings.RolesThatCanViewMyPage))
            {
                if (renderAsListItem)
                {
                    //writer.Write("<li class='" + listItemCSS + "'>");
                    writer.WriteBeginTag("li");
                    writer.WriteAttribute("class", listItemCSS);
                    writer.Write(HtmlTextWriter.TagRightChar);
                }

                if (leftSeparatorImageUrl.Length > 0)
                {
                    writer.Write("<img class='accent' src='" + Page.ResolveUrl(leftSeparatorImageUrl) + "' border='0' /> ");
                }
                else
                {
                    if (UseLeftSeparator)
                    {
                        writer.Write("<span class='accent'>|</span>");
                    }
                }

                string urlToUse;
                if (WebConfigSettings.UseSslForMyPage)
                {
                    urlToUse = SiteUtils.GetSecureNavigationSiteRoot() + "/MyPage.aspx";
                }
                else
                {
                    urlToUse = SiteUtils.GetNavigationSiteRoot() + "/MyPage.aspx";
                    if ((Page.Request.IsSecureConnection) && (!siteSettings.UseSslOnAllPages))
                    {
                        urlToUse = urlToUse.Replace("https", "http");
                    }
                }

                if (CssClass.Length == 0)
                {
                    CssClass = "sitelink";
                }


                writer.WriteBeginTag("a");
                writer.WriteAttribute("class", CssClass);
                //writer.WriteAttribute("title", Resource.MyPageLink);
                writer.WriteAttribute("href", Page.ResolveUrl(urlToUse));
                writer.Write(HtmlTextWriter.TagRightChar);
                writer.WriteEncodedText(Resource.MyPageLink);
                writer.WriteEndTag("a");



                if (renderAsListItem)
                {
                    writer.WriteEndTag("li");
                }
            }
#endif
        }
Пример #20
0
        private void LoadSettings()
        {
            if (siteSettings == null)
            {
                return;
            }

            TimeOffset      = SiteUtils.GetUserTimeOffset();
            timeZone        = SiteUtils.GetUserTimeZone();
            showUserRevenue = (WebConfigSettings.ShowRevenueInForums && isCommerceReportViewer);
            currencyCulture = ResourceHelper.GetCurrencyCulture(siteSettings.GetCurrency().Code);
            filterContentFromTrustedUsers = ForumConfiguration.FilterContentFromTrustedUsers;
            if (ForumConfiguration.AllowExternalImages)
            {
                allowedImageUrlRegexPattern = SecurityHelper.RegexAnyImageUrlPatern;
            }

            IsModerator = isEditable;

            if (forum != null)
            {
                if (WebUser.IsInRoles(forum.RolesThatCanModerate))
                {
                    IsModerator = true;
                }
            }

            switch (siteSettings.AvatarSystem)
            {
            case "gravatar":
                allowGravatars = true;
                disableAvatars = false;
                break;

            case "internal":
                allowGravatars = false;
                disableAvatars = false;
                break;

            case "none":
            default:
                allowGravatars = false;
                disableAvatars = true;
                break;
            }

            notificationUrl = SiteRoot + "/Forums/EditSubscriptions.aspx?mid="
                              + moduleId.ToInvariantString()
                              + "&pageid=" + PageId.ToInvariantString() + "#forum" + ItemId.ToInvariantString();

            pnlNotify.Visible = (!isSubscribedToForum) && !displaySettings.HideNotificationLinkOnPostList;
            if (!Request.IsAuthenticated)
            {
                pnlNotify.Visible = false;
            }

            if (WebConfigSettings.LoginPageRelativeUrl.Length > 0)
            {
                lnkLogin.NavigateUrl       = SiteRoot + WebConfigSettings.LoginPageRelativeUrl + "?returnurl=" + Server.UrlEncode(Request.RawUrl);
                lnkLoginBottom.NavigateUrl = SiteRoot + WebConfigSettings.LoginPageRelativeUrl + "?returnurl=" + Server.UrlEncode(Request.RawUrl);
            }
            else
            {
                lnkLogin.NavigateUrl       = SiteRoot + "/Secure/Login.aspx?returnurl=" + Server.UrlEncode(Request.RawUrl);
                lnkLoginBottom.NavigateUrl = SiteRoot + "/Secure/Login.aspx?returnurl=" + Server.UrlEncode(Request.RawUrl);
            }
        }
Пример #21
0
        private void btnUpdate_Click(object sender, EventArgs e)
        {
            if (group == null)
            {
                group = new Group(groupId);
            }

            if (!group.AllowAnonymousPosts)
            {
                captcha.Enabled     = false;
                pnlAntiSpam.Visible = false;
                pnlEdit.Controls.Remove(pnlAntiSpam);
            }

            Page.Validate();
            if (!Page.IsValid)
            {
                PopulateControls();
                return;
            }
            else
            {
                if ((useSpamBlockingForAnonymous) && (pnlAntiSpam.Visible))
                {
                    if (!captcha.IsValid)
                    {
                        PopulateControls();
                        return;
                    }
                }

                GroupTopic topic;
                bool       userIsAllowedToUpdateThisPost = false;
                if (topicId == -1)
                {
                    topic         = new GroupTopic();
                    topic.GroupId = groupId;
                }
                else
                {
                    if (postId > -1)
                    {
                        topic = new GroupTopic(topicId, postId);
                        if (WebUser.IsAdmin ||
                            WebUser.IsInRoles(CurrentPage.EditRoles) ||
                            (this.theUser.UserId == topic.PostUserId)
                            )
                        {
                            userIsAllowedToUpdateThisPost = true;
                        }
                    }
                    else
                    {
                        topic = new GroupTopic(topicId);
                    }
                    groupId = topic.GroupId;
                }

                topic.ContentChanged += new ContentChangedEventHandler(topic_ContentChanged);
                topic.PostSubject     = this.txtSubject.Text;
                topic.PostMessage     = edMessage.Text;

                if (Request.IsAuthenticated)
                {
                    SiteUser siteUser = SiteUtils.GetCurrentSiteUser();
                    if (siteUser != null)
                    {
                        topic.PostUserId = siteUser.UserId;
                    }
                    if (chkSubscribeToGroup.Checked)
                    {
                        group.Subscribe(siteUser.UserId);
                    }
                    else
                    {
                        topic.SubscribeUserToTopic = this.chkNotifyOnReply.Checked;
                    }
                }
                else
                {
                    topic.PostUserId = 0;                     //guest
                }

                string topicViewUrl = SiteRoot + "/Groups/Topic.aspx?topic="
                                      + topic.TopicId.ToInvariantString()
                                      + "&mid=" + moduleId.ToInvariantString()
                                      + "&pageid=" + pageId.ToInvariantString()
                                      + "&ItemID=" + groupId.ToInvariantString()
                                      + "&pagenumber=" + this.pageNumber.ToInvariantString();

                if ((topic.PostId == -1) || (userIsAllowedToUpdateThisPost))
                {
                    topic.Post();
                    CurrentPage.UpdateLastModifiedTime();

                    topicViewUrl = SiteRoot + "/Groups/Topic.aspx?topic="
                                   + topic.TopicId.ToInvariantString()
                                   + "&mid=" + moduleId.ToInvariantString()
                                   + "&pageid=" + pageId.ToInvariantString()
                                   + "&ItemID=" + groupId.ToInvariantString()
                                   + "&pagenumber=" + this.pageNumber.ToInvariantString()
                                   + "#post" + topic.PostId.ToInvariantString();

                    // Send notification to subscribers
                    // this doesn't make sense it only gets topic subscribers not group subscribers and yet I get the emails
                    DataSet dsTopicSubscribers = topic.GetTopicSubscribers();

                    //ConfigurationManager.AppSettings["DefaultEmailFrom"]
                    GroupNotificationInfo notificationInfo = new GroupNotificationInfo();

                    CultureInfo defaultCulture = SiteUtils.GetDefaultCulture();

                    notificationInfo.SubjectTemplate
                        = ResourceHelper.GetMessageTemplate(defaultCulture,
                                                            "GroupNotificationEmailSubject.config");

                    if (includePostBodyInNotification)
                    {
                        notificationInfo.BodyTemplate = Server.HtmlDecode(SecurityHelper.RemoveMarkup(topic.PostMessage)) + "\n\n\n";
                    }

                    notificationInfo.BodyTemplate
                        += ResourceHelper.GetMessageTemplate(defaultCulture,
                                                             "GroupNotificationEmail.config");

                    notificationInfo.FromEmail   = siteSettings.DefaultEmailFromAddress;
                    notificationInfo.SiteName    = siteSettings.SiteName;
                    notificationInfo.ModuleName  = new Module(moduleId).ModuleTitle;
                    notificationInfo.GroupName   = new Group(groupId).Title;
                    notificationInfo.Subject     = topic.PostSubject;
                    notificationInfo.Subscribers = dsTopicSubscribers;
                    notificationInfo.MessageLink = topicViewUrl;
                    notificationInfo.UnsubscribeGroupTopicLink = SiteRoot + "/Groups/UnsubscribeTopic.aspx?topicid=" + topic.TopicId;
                    notificationInfo.UnsubscribeGroupLink      = SiteRoot + "/Groups/UnsubscribeGroup.aspx?mid=" + moduleId + "&itemid=" + topic.GroupId;
                    notificationInfo.SmtpSettings = SiteUtils.GetSmtpSettings();

                    ThreadPool.QueueUserWorkItem(new WaitCallback(Notification.SendGroupNotificationEmail), notificationInfo);


                    String cacheDependencyKey = "Module-" + moduleId.ToInvariantString();
                    CacheHelper.TouchCacheDependencyFile(cacheDependencyKey);
                    SiteUtils.QueueIndexing();
                }

                //WebUtils.SetupRedirect(this, topicViewUrl);
                Response.Redirect(topicViewUrl);
            }
        }
Пример #22
0
        protected override void OnInit(EventArgs e)
        {
            // Alexander Yushchenko: workaround to make old custom modules work
            // Before 03.19.2007 this method was "new" and called from descendant classes
            // To avoid multiple self-calls a boolean flag is used
            if (IsOnInitExecuted)
            {
                return;
            }
            IsOnInitExecuted = true;

            base.OnInit(e);

            if (HttpContext.Current == null)
            {
                return;
            }

            siteSettings = CacheHelper.GetCurrentSiteSettings();

            currentPage      = CacheHelper.GetCurrentPage();
            ScriptController = (ScriptManager)Page.Master.FindControl("ScriptManager1");

            if (siteSettings != null)
            {
                this.siteID = siteSettings.SiteId;
                if (!WebUser.IsAdminOrContentAdmin)
                {
                    forbidModuleSettings = WebUser.IsInRoles(siteSettings.RolesNotAllowedToEditModuleSettings);
                }
            }

            if (Page.Request.IsAuthenticated)
            {
                isSiteEditor = SiteUtils.UserIsSiteEditor();

                //if (WebUser.IsAdminOrContentAdmin || isSiteEditor || WebUser.IsInRoles(currentPage.EditRoles)
                //    || ((moduleConfiguration != null)
                //           && (WebUser.IsInRoles(moduleConfiguration.AuthorizedEditRoles))
                //       )
                //   )
                //{
                //    isEditable = true;
                //}

                isEditable = ShouldAllowEdit();

                if ((moduleConfiguration != null) && (!moduleConfiguration.IsGlobal))
                {
                    if (WebConfigSettings.EnableContentWorkflow && siteSettings.EnableContentWorkflow && (this is IWorkflow))
                    {
                        enableWorkflow = true;

                        use3LevelWorkflow = WebConfigSettings.Use3LevelContentWorkflow; //joe davis

                        if (!isEditable)
                        {
                            if (
                                (WebUser.IsInRoles(currentPage.DraftEditOnlyRoles)) ||
                                (WebUser.IsInRoles(moduleConfiguration.DraftEditRoles)) ||
                                (use3LevelWorkflow && WebUser.IsInRoles(moduleConfiguration.DraftApprovalRoles))
                                )
                            {
                                isEditable = true;
                            }
                        }
                    }
                }

                if (!isEditable && (moduleConfiguration != null) && (moduleConfiguration.EditUserId > 0))
                {
                    SiteUser siteUser = SiteUtils.GetCurrentSiteUser();
                    if (
                        (siteUser != null) &&
                        (moduleConfiguration.EditUserId == siteUser.UserId)
                        )
                    {
                        isEditable = true;
                    }
                }
            }

            if (moduleConfiguration != null)
            {
                this.m_title       = moduleConfiguration.ModuleTitle;
                this.m_description = moduleConfiguration.FeatureName;
            }
        }
Пример #23
0
        /// <summary>
        /// this overload is preferred because it checks if the module represents an instance of the feature
        /// </summary>
        /// <param name="moduleId"></param>
        /// <param name="featureGuid"></param>
        /// <returns></returns>
        public bool UserCanEditModule(int moduleId, Guid featureGuid)
        {
            if (!Request.IsAuthenticated)
            {
                return(false);
            }

            if (WebUser.IsAdminOrContentAdmin)
            {
                return(true);
            }

            if (SiteUtils.UserIsSiteEditor())
            {
                return(true);
            }

            if (CurrentPage == null)
            {
                return(false);
            }

            bool moduleFoundOnPage = false;

            foreach (Module m in CurrentPage.Modules)
            {
                if (
                    (m.ModuleId == moduleId) &&
                    ((featureGuid == Guid.Empty) || (m.FeatureGuid == featureGuid))
                    )
                {
                    moduleFoundOnPage = true;
                }
            }

            if (!moduleFoundOnPage)
            {
                return(false);
            }

            if (WebUser.IsInRoles(CurrentPage.EditRoles))
            {
                return(true);
            }

            SiteUser currentUser = SiteUtils.GetCurrentSiteUser();

            if (currentUser == null)
            {
                return(false);
            }

            foreach (Module m in CurrentPage.Modules)
            {
                if (m.ModuleId == moduleId)
                {
                    if (m.EditUserId == currentUser.UserId)
                    {
                        return(true);
                    }
                    if (WebUser.IsInRoles(m.AuthorizedEditRoles))
                    {
                        return(true);
                    }
                }
            }

            return(false);
        }
Пример #24
0
        private bool ShouldRender(mojoSiteMapNode mapNode)
        {
            if (mapNode == null)
            {
                return(false);
            }

            bool remove = false;

            if (mapNode.Roles == null)
            {
                if ((!isAdmin) && (!isContentAdmin) && (!isSiteEditor))
                {
                    remove = true;
                }
            }
            else
            {
                if ((!isAdmin) && (mapNode.Roles.Count == 1) && (mapNode.Roles[0].ToString() == "Admins"))
                {
                    remove = true;
                }

                if ((!isAdmin) && (!isContentAdmin) && (!isSiteEditor) && (!WebUser.IsInRoles(mapNode.Roles)))
                {
                    remove = true;
                }
            }

            if ((!isAdmin) && (!isContentAdmin) && (!isSiteEditor) && (!WebUser.IsInRoles(mapNode.ViewRoles)))
            {
                remove = true;
            }


            if (!mapNode.IncludeInMenu)
            {
                remove = true;
            }

            if (mapNode.IsPending && !WebUser.IsAdminOrContentAdminOrContentPublisherOrContentAuthor)
            {
                remove = true;
            }

            if ((mapNode.HideAfterLogin) && (Page.Request.IsAuthenticated))
            {
                remove = true;
            }

            if ((!IsMobileSkin) && (mapNode.PublishMode == mobileOnly))
            {
                remove = true;
            }

            if ((IsMobileSkin) && (mapNode.PublishMode == webOnly))
            {
                remove = true;
            }

            if ((MaxDataRenderDepth > -1) && (mapNode.Depth > MaxDataRenderDepth))
            {
                remove = true;
            }

            { return(!remove); }
        }
Пример #25
0
        private void PopulateControls()
        {
            if (forum == null)
            {
                return;
            }

            string pageUrl;

            if (ForumConfiguration.CombineUrlParams)
            {
                pageUrl = SiteRoot
                          + "/Forums/ForumView.aspx?pageid=" + PageId.ToInvariantString()
                          + "&amp;f=" + forum.ItemId.ToInvariantString()
                          + "~{0}";
            }
            else
            {
                pageUrl = SiteRoot
                          + "/Forums/ForumView.aspx?"
                          + "ItemID=" + forum.ItemId.ToInvariantString()
                          + "&amp;mid=" + ModuleId.ToInvariantString()
                          + "&amp;pageid=" + PageId.ToInvariantString()
                          + "&amp;pagenumber={0}";
            }

            pgrTop.PageURLFormat = pageUrl;
            pgrTop.ShowFirstLast = true;
            pgrTop.CurrentIndex  = pageNumber;
            pgrTop.PageSize      = forum.ThreadsPerPage;
            pgrTop.PageCount     = forum.TotalPages;
            pgrTop.Visible       = (pgrTop.PageCount > 1);
            divPagerTop.Visible  = pgrTop.Visible;

            pgrBottom.PageURLFormat = pageUrl;
            pgrBottom.ShowFirstLast = true;
            pgrBottom.CurrentIndex  = pageNumber;
            pgrBottom.PageSize      = forum.ThreadsPerPage;
            pgrBottom.PageCount     = forum.TotalPages;
            pgrBottom.Visible       = (pgrBottom.PageCount > 1);
            divPagerBottom.Visible  = pgrBottom.Visible;

            lnkNewThread.HRef = SiteRoot
                                + "/Forums/EditPost.aspx?forumid=" + ItemId.ToInvariantString()
                                + "&amp;pageid=" + PageId.ToInvariantString()
                                + "&amp;mid=" + ModuleId.ToInvariantString();

            lnkNewThreadBottom.HRef = lnkNewThread.HRef;

            lnkNewThread.Visible       = WebUser.IsInRoles(forum.RolesThatCanPost) && !forum.Closed;
            lnkNewThreadBottom.Visible = lnkNewThread.Visible;

            lnkLogin.Visible = !lnkNewThread.Visible && !Request.IsAuthenticated;



            using (IDataReader reader = forum.GetThreads(pageNumber))
            {
                rptForums.DataSource = reader;

#if MONO
                this.rptForums.DataBind();
#else
                this.DataBind();
#endif
            }
        }
Пример #26
0
        private void SetupInternalCommentSystem()
        {
            divCommentService.Visible = false;
            disqus.Disable            = true;
            intenseDebate.Visible     = false;
            fbComments.Visible        = false;

            repository = new CommentRepository();
            timeZone   = SiteUtils.GetUserTimeZone();
            if (allowExternalImages)
            {
                AllowedImageUrlRegexPatern = SecurityHelper.RegexAnyImageUrlPatern;
            }
            CanManageUsers = WebUser.IsInRoles(siteSettings.RolesThatCanManageUsers);

            switch (siteSettings.AvatarSystem)
            {
            case "gravatar":
                allowGravatars = true;
                disableAvatars = false;
                break;

            case "internal":
                allowGravatars = false;
                disableAvatars = false;
                break;

            case "none":
            default:
                allowGravatars = false;
                disableAvatars = true;
                break;
            }

            if (forceDisableAvatar)
            {
                allowGravatars = false;
                disableAvatars = true;
            }

            showUserRevenue = (WebConfigSettings.ShowRevenueInForums && WebUser.IsInRoles(siteSettings.CommerceReportViewRoles));

            //CommentEditor editor
            commentEditor.SiteGuid                       = siteSettings.SiteGuid;
            commentEditor.SiteId                         = siteSettings.SiteId;
            commentEditor.SiteRoot                       = siteRoot;
            commentEditor.CommentsClosed                 = commentsClosed;
            commentEditor.CommentUrl                     = commentUrl;
            commentEditor.ContentGuid                    = contentGuid;
            commentEditor.DefaultCommentTitle            = defaultCommentTitle;
            commentEditor.FeatureGuid                    = featureGuid;
            commentEditor.ModuleGuid                     = moduleGuid;
            commentEditor.NotificationAddresses          = notificationAddresses;
            commentEditor.NotificationTemplateName       = notificationTemplateName;
            commentEditor.RequireCaptcha                 = requireCaptcha;
            commentEditor.RequireModeration              = requireModeration;
            commentEditor.UserCanModerate                = userCanModerate;
            commentEditor.Visible                        = !commentsClosed;
            commentEditor.CurrentUser                    = currentUser;
            commentEditor.IncludeIpAddressInNotification = includeIpAddressInNotification;
            commentEditor.ContainerControl               = this;
            commentEditor.UpdateContainerControl         = this;
            commentEditor.UseCommentTitle                = useCommentTitle;
            commentEditor.ShowUserUrl                    = showUserUrl;

            pnlCommentsClosed.Visible = commentsClosed;
            if (!commentsClosed && requireAuthenticationToPost && !Request.IsAuthenticated)
            {
                pnlCommentsRequireAuthentication.Visible = true;
                commentEditor.Visible = false;
            }

            if (!commentsClosed && alwaysShowSignInPromptIfNotAuthenticated && !Request.IsAuthenticated)
            {
                pnlCommentsRequireAuthentication.Visible = true;
            }



            SetupScript();

            if (!IsPostBack)
            {
                BindComments();
            }
        }
Пример #27
0
        private void LoadSettings()
        {
            pageID       = WebUtils.ParseInt32FromQueryString("pageid", -1);
            moduleId     = WebUtils.ParseInt32FromQueryString("mid", -1);
            categoryId   = WebUtils.ParseInt32FromQueryString("cat", categoryId);
            siteSettings = CacheHelper.GetCurrentSiteSettings();

            // newer implementation combines params as p=pageid~moduleid~categoryid
            string f = WebUtils.ParseStringFromQueryString("p", string.Empty);

            if ((f.Length > 0) && (f.Contains("~")))
            {
                List <string> parms = f.SplitOnCharAndTrim('~');

                if (parms.Count >= 1)
                {
                    int.TryParse(parms[0], NumberStyles.Integer, CultureInfo.InvariantCulture, out pageID);
                }

                if (parms.Count >= 2)
                {
                    int.TryParse(parms[1], NumberStyles.Integer, CultureInfo.InvariantCulture, out moduleId);
                }

                if (parms.Count >= 3)
                {
                    int.TryParse(parms[2], NumberStyles.Integer, CultureInfo.InvariantCulture, out categoryId);
                }
            }


            securityBypassGuid = WebUtils.ParseGuidFromQueryString("g", securityBypassGuid);
            attachmentBaseUrl  = SiteUtils.GetFileAttachmentUploadPath();
            pageSettings       = CacheHelper.GetPage(pageID);
            module             = GetModule();

            if ((moduleId == -1) || (module == null))
            {
                return;
            }

            bool bypassPageSecurity = false;

            if ((securityBypassGuid != Guid.Empty) && (securityBypassGuid == WebConfigSettings.InternalFeedSecurityBypassKey))
            {
                bypassPageSecurity = true;
            }

            if (
                (bypassPageSecurity) ||
                (WebUser.IsInRoles(pageSettings.AuthorizedRoles)) ||
                (WebUser.IsInRoles(module.ViewRoles))
                )
            {
                canView = true;
            }

            if (!canView)
            {
                return;
            }

            if (WebConfigSettings.UseFoldersInsteadOfHostnamesForMultipleSites)
            {
                navigationSiteRoot = SiteUtils.GetNavigationSiteRoot();
                blogBaseUrl        = navigationSiteRoot;
                imageSiteRoot      = WebUtils.GetSiteRoot();
                cssBaseUrl         = imageSiteRoot;
            }
            else
            {
                navigationSiteRoot = WebUtils.GetHostRoot();
                blogBaseUrl        = SiteUtils.GetNavigationSiteRoot();
                imageSiteRoot      = navigationSiteRoot;
                cssBaseUrl         = WebUtils.GetSiteRoot();
            }

            moduleSettings = ModuleSettings.GetModuleSettings(moduleId);
            config         = new BlogConfiguration(moduleSettings);

            if (config.FeedIsDisabled)
            {
                canView = false;
            }

            if ((config.FeedburnerFeedUrl.Length > 0) && (config.FeedburnerFeedUrl.StartsWith("http")) && (BlogConfiguration.UseRedirectForFeedburner))
            {
                shouldRedirectToFeedburner = true;
                if ((Request.UserAgent != null) && (Request.UserAgent.Contains("FeedBurner")))
                {
                    shouldRedirectToFeedburner = false; // don't redirect if the feedburner bot is reading the feed
                }

                Guid redirectBypassToken = WebUtils.ParseGuidFromQueryString("r", Guid.Empty);
                if (redirectBypassToken == Global.FeedRedirectBypassToken)
                {
                    shouldRedirectToFeedburner = false; // allows time for user to subscribe to autodiscovery links without redirecting
                }
            }
        }
Пример #28
0
        private void RenderNodesToSiteMap(
            HttpContext context,
            Page page,
            XmlTextWriter xmlTextWriter,
            ArrayList alreadyAddedUrls,
            SiteMapNode siteMapNode)
        {
            mojoSiteMapNode mojoNode = (mojoSiteMapNode)siteMapNode;

            if (!mojoNode.IsRootNode)
            {
                //if (
                //    ((mojoNode.Roles == null)||(WebUser.IsInRoles(mojoNode.Roles)))
                //    &&(mojoNode.IncludeInSearchMap)
                //    &&(!mojoNode.IsPending)
                //    )
                if (
                    (WebUser.IsInRoles(mojoNode.ViewRoles)) &&
                    (mojoNode.IncludeInSearchMap) &&
                    (!mojoNode.IsPending)
                    )
                {
                    // must use unique urls, google site maps can't have
                    // multiple urls like"
                    // http://SomeSite/Default.aspx?pageid=1
                    // http://SomeSite/Default.aspx?pageid=2
                    // where it only differs by query string
                    // google may stop crawling if it encounters this
                    // in a site map


                    if (IsValidUrl(mojoNode))
                    {
                        string url;
                        if (mojoNode.Url.StartsWith("http"))
                        {
                            url = mojoNode.Url;
                        }
                        else
                        {
                            if ((mojoNode.UseSsl) || (siteSettings.UseSslOnAllPages))
                            {
                                url = secureSiteRoot + mojoNode.Url.Replace("~/", "/");
                            }
                            else
                            {
                                url = insecureSiteRoot + mojoNode.Url.Replace("~/", "/");
                            }
                        }

                        // no duplicate urls allowed in a google site map
                        if (!alreadyAddedUrls.Contains(url))
                        {
                            alreadyAddedUrls.Add(url);

                            xmlTextWriter.WriteStartElement("url");
                            xmlTextWriter.WriteElementString("loc", url);

                            // this if is only needed because this is a new datapoint
                            // after it has been implemented in the db
                            // this if could be removed
                            if (mojoNode.LastModifiedUtc > DateTime.MinValue)
                            {
                                xmlTextWriter.WriteElementString(
                                    "lastmod",
                                    mojoNode.LastModifiedUtc.ToString("u", CultureInfo.InvariantCulture).Replace(" ", "T"));
                            }

                            xmlTextWriter.WriteElementString(
                                "changefreq",
                                mojoNode.ChangeFrequency.ToString().ToLower());

                            xmlTextWriter.WriteElementString(
                                "priority",
                                mojoNode.SiteMapPriority);

                            xmlTextWriter.WriteEndElement(); //url
                        }
                    }
                }
            }

            foreach (SiteMapNode childNode in mojoNode.ChildNodes)
            {
                RenderNodesToSiteMap(
                    context,
                    page,
                    xmlTextWriter,
                    alreadyAddedUrls,
                    childNode);
            }
        }
Пример #29
0
        private void PopulateControls()
        {
            string featuredImageUrl = string.Empty;
            string markupTop        = string.Empty;
            string markupBottom     = string.Empty;

            featuredImageUrl = String.IsNullOrWhiteSpace(config.InstanceFeaturedImage) ? featuredImageUrl : WebUtils.GetRelativeSiteRoot() + config.InstanceFeaturedImage;
            markupTop        = displaySettings.ModuleInstanceMarkupTop;
            markupBottom     = displaySettings.ModuleInstanceMarkupBottom;

            strOutput.Append(markupTop);

            if (config.UseHeader && config.HeaderLocation == "InnerBodyPanel" && !String.IsNullOrWhiteSpace(config.HeaderContent) && !String.Equals(config.HeaderContent, "<p>&nbsp;</p>"))
            {
                try
                {
                    strOutput.Append(string.Format(displaySettings.HeaderContentFormat, config.HeaderContent));
                }
                catch (FormatException ex)
                {
                    log.ErrorFormat(markupErrorFormat, "HeaderContentFormat", moduleTitle, ex);
                }
            }
            StringBuilder  jsonString   = new StringBuilder();
            StringWriter   stringWriter = new StringWriter(jsonString);
            JsonTextWriter jsonWriter   = new JsonTextWriter(stringWriter);

            // http://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_DateTimeZoneHandling.htm
            jsonWriter.DateTimeZoneHandling = DateTimeZoneHandling.Utc;
            // http://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_DateFormatHandling.htm
            jsonWriter.DateFormatHandling = DateFormatHandling.IsoDateFormat;

            string jsonObjName = "sflexi" + module.ModuleId.ToString() + (config.IsGlobalView ? "Modules" : "Items");

            if (config.RenderJSONOfData)
            {
                jsonWriter.WriteRaw("var " + jsonObjName + " = ");
                if (config.JsonLabelObjects || config.IsGlobalView)
                {
                    jsonWriter.WriteStartObject();
                }
                else
                {
                    jsonWriter.WriteStartArray();
                }
            }

            List <IndexedStringBuilder> itemsMarkup = new List <IndexedStringBuilder>();
            //List<Item> categorizedItems = new List<Item>();
            bool usingGlobalViewMarkup = !String.IsNullOrWhiteSpace(displaySettings.GlobalViewMarkup);
            int  currentModuleID       = -1;

            foreach (Item item in items)
            {
                bool itemIsEditable = isEditable || WebUser.IsInRoles(item.EditRoles);
                bool itemIsViewable = WebUser.IsInRoles(item.ViewRoles) || itemIsEditable;
                if (!itemIsViewable)
                {
                    continue;
                }

                //int itemCount = 0;
                //StringBuilder content = new StringBuilder();
                IndexedStringBuilder content = new IndexedStringBuilder();

                ModuleConfiguration itemModuleConfig = new ModuleConfiguration(module);
                item.ModuleFriendlyName = itemModuleConfig.ModuleFriendlyName;
                if (String.IsNullOrWhiteSpace(itemModuleConfig.ModuleFriendlyName))
                {
                    Module itemModule = new Module(item.ModuleGuid);
                    if (itemModule != null)
                    {
                        item.ModuleFriendlyName = itemModule.ModuleTitle;
                    }
                }

                if (config.IsGlobalView)
                {
                    content.SortOrder1 = itemModuleConfig.GlobalViewSortOrder;
                    content.SortOrder2 = item.SortOrder;
                }
                else
                {
                    content.SortOrder1 = item.SortOrder;
                }


                List <ItemFieldValue> fieldValues = ItemFieldValue.GetItemValues(item.ItemGuid);

                //using item.ModuleID here because if we are using a 'global view' we need to be sure the item edit link uses the correct module id.
                string itemEditUrl  = WebUtils.GetSiteRoot() + "/SuperFlexi/Edit.aspx?pageid=" + pageId + "&mid=" + item.ModuleID + "&itemid=" + item.ItemID;
                string itemEditLink = itemIsEditable ? String.Format(displaySettings.ItemEditLinkFormat, itemEditUrl) : string.Empty;

                if (config.RenderJSONOfData)
                {
                    if (config.IsGlobalView)
                    {
                        if (currentModuleID != item.ModuleID)
                        {
                            if (currentModuleID != -1)
                            {
                                jsonWriter.WriteEndObject();
                                jsonWriter.WriteEndObject();
                            }

                            currentModuleID = item.ModuleID;

                            //always label objects in globalview
                            jsonWriter.WritePropertyName("m" + currentModuleID.ToString());
                            jsonWriter.WriteStartObject();
                            jsonWriter.WritePropertyName("Module");
                            jsonWriter.WriteValue(item.ModuleFriendlyName);
                            jsonWriter.WritePropertyName("Items");
                            jsonWriter.WriteStartObject();
                        }
                    }
                    if (config.JsonLabelObjects || config.IsGlobalView)
                    {
                        jsonWriter.WritePropertyName("i" + item.ItemID.ToString());
                    }
                    jsonWriter.WriteStartObject();
                    jsonWriter.WritePropertyName("ItemId");
                    jsonWriter.WriteValue(item.ItemID.ToString());
                    jsonWriter.WritePropertyName("SortOrder");
                    jsonWriter.WriteValue(item.SortOrder.ToString());
                    if (IsEditable)
                    {
                        jsonWriter.WritePropertyName("EditUrl");
                        jsonWriter.WriteValue(itemEditUrl);
                    }
                }
                content.Append(displaySettings.ItemMarkup);

                foreach (Field field in fields)
                {
                    if (String.IsNullOrWhiteSpace(field.Token))
                    {
                        field.Token = "$_NONE_$";                                         //just in case someone has loaded the database with fields without using a source file.
                    }
                    bool fieldValueFound = false;

                    foreach (ItemFieldValue fieldValue in fieldValues)
                    {
                        if (field.FieldGuid == fieldValue.FieldGuid)
                        {
                            fieldValueFound = true;

                            if (String.IsNullOrWhiteSpace(fieldValue.FieldValue) ||
                                fieldValue.FieldValue.StartsWith("&deleted&") ||
                                fieldValue.FieldValue.StartsWith("&amp;deleted&amp;") ||
                                fieldValue.FieldValue.StartsWith("<p>&deleted&</p>") ||
                                fieldValue.FieldValue.StartsWith("<p>&amp;deleted&amp;</p>"))
                            {
                                content.Replace("^" + field.Token + "^", string.Empty);
                                content.Replace("^" + field.Token, string.Empty);
                                content.Replace(field.Token + "^", string.Empty);
                                content.Replace(field.Token, string.Empty);
                            }
                            else
                            {
                                if (IsDateField(field))
                                {
                                    DateTime dateTime = new DateTime();
                                    if (DateTime.TryParse(fieldValue.FieldValue, out dateTime))
                                    {
                                        /// ^field.Token is used when we don't want the preTokenString and postTokenString to be used
                                        content.Replace("^" + field.Token + "^", dateTime.ToString(field.DateFormat));
                                        content.Replace("^" + field.Token, dateTime.ToString(field.DateFormat) + field.PostTokenString);
                                        content.Replace(field.Token + "^", field.PreTokenString + dateTime.ToString(field.DateFormat));
                                        content.Replace(field.Token, field.PreTokenString + dateTime.ToString(field.DateFormat) + field.PostTokenString);
                                    }
                                }

                                if (IsCheckBoxListField(field) || IsRadioButtonListField(field))
                                {
                                    foreach (CheckBoxListMarkup cblm in config.CheckBoxListMarkups)
                                    {
                                        if (cblm.Field == field.Name)
                                        {
                                            StringBuilder cblmContent = new StringBuilder();

                                            List <string> values = fieldValue.FieldValue.SplitOnCharAndTrim(';');
                                            if (values.Count > 0)
                                            {
                                                foreach (string value in values)
                                                {
                                                    //why did we use _ValueItemID_ here instead of _ItemID_?
                                                    cblmContent.Append(cblm.Markup.Replace(field.Token, value).Replace("$_ValueItemID_$", item.ItemID.ToString()) + cblm.Separator);
                                                    cblm.SelectedValues.Add(new CheckBoxListMarkup.SelectedValue {
                                                        Value = value, ItemID = item.ItemID
                                                    });
                                                    //cblm.SelectedValues.Add(fieldValue);
                                                }
                                            }
                                            cblmContent.Length -= cblm.Separator.Length;
                                            content.Replace(cblm.Token, cblmContent.ToString());
                                        }
                                    }
                                }
                                //else
                                //{
                                /// ^field.Token is used when we don't want the preTokenString and postTokenString to be used


                                content.Replace("^" + field.Token + "^", fieldValue.FieldValue);
                                content.Replace("^" + field.Token, fieldValue.FieldValue + field.PostTokenString);
                                content.Replace(field.Token + "^", field.PreTokenString + fieldValue.FieldValue);
                                content.Replace(field.Token, field.PreTokenString + fieldValue.FieldValue + field.PostTokenString);
                                //}
                            }
                            //if (!String.IsNullOrWhiteSpace(field.LinkedField))
                            //{
                            //    Field linkedField = fields.Find(delegate(Field f) { return f.Name == field.LinkedField; });
                            //    if (linkedField != null)
                            //    {
                            //        ItemFieldValue linkedValue = fieldValues.Find(delegate(ItemFieldValue fv) { return fv.FieldGuid == linkedField.FieldGuid; });
                            //        content.Replace(linkedField.Token, linkedValue.FieldValue);
                            //    }
                            //}

                            if (config.RenderJSONOfData)
                            {
                                jsonWriter.WritePropertyName(field.Name);
                                //if (IsDateField(field))
                                //{
                                //    DateTime dateTime = new DateTime();
                                //    if (DateTime.TryParse(fieldValue.FieldValue, out dateTime))
                                //    {
                                //        jsonWriter.WriteValue(dateTime);
                                //    }

                                //}
                                //else
                                //{
                                jsonWriter.WriteValue(fieldValue.FieldValue);
                                //}
                            }
                        }
                    }

                    if (!fieldValueFound)
                    {
                        content.Replace(field.Token, field.DefaultValue);
                    }
                }

                if (config.RenderJSONOfData)
                {
                    //if (config.IsGlobalView)
                    //{
                    //    jsonWriter.WriteEndObject();
                    //}
                    jsonWriter.WriteEndObject();
                }

                content.Replace("$_EditLink_$", itemEditLink);
                content.Replace("$_ItemID_$", item.ItemID.ToString());
                content.Replace("$_SortOrder_$", item.SortOrder.ToString());

                if (!String.IsNullOrWhiteSpace(content))
                {
                    itemsMarkup.Add(content);
                }
            }
            if (config.DescendingSort)
            {
                itemsMarkup.Sort(delegate(IndexedStringBuilder a, IndexedStringBuilder b)
                {
                    int xdiff = b.SortOrder1.CompareTo(a.SortOrder1);
                    if (xdiff != 0)
                    {
                        return(xdiff);
                    }
                    else
                    {
                        return(b.SortOrder2.CompareTo(a.SortOrder2));
                    }
                });
            }
            else
            {
                itemsMarkup.Sort(delegate(IndexedStringBuilder a, IndexedStringBuilder b)
                {
                    int xdiff = a.SortOrder1.CompareTo(b.SortOrder1);
                    if (xdiff != 0)
                    {
                        return(xdiff);
                    }
                    else
                    {
                        return(a.SortOrder2.CompareTo(b.SortOrder2));
                    }
                });
            }
            StringBuilder allItems = new StringBuilder();

            if (displaySettings.ItemsPerGroup == -1)
            {
                foreach (IndexedStringBuilder sb in itemsMarkup)
                {
                    //allItems.Append(displaySettings.GlobalViewModuleGroupMarkup.Replace("$_ModuleGroupName_$", sb.GroupName));
                    allItems.Append(sb.ToString());
                }
                if (usingGlobalViewMarkup)
                {
                    strOutput.AppendFormat(displaySettings.ItemsWrapperFormat, displaySettings.GlobalViewMarkup.Replace("$_ModuleGroups_$", allItems.ToString()));
                }
                else
                {
                    strOutput.AppendFormat(displaySettings.ItemsWrapperFormat, allItems.ToString());
                }
            }
            else
            {
                int itemIndex = 0;

                decimal totalGroupCount = Math.Ceiling(itemsMarkup.Count / Convert.ToDecimal(displaySettings.ItemsPerGroup));

                if (totalGroupCount < 1 && itemsMarkup.Count > 0)
                {
                    totalGroupCount = 1;
                }

                int currentGroup            = 1;
                List <StringBuilder> groups = new List <StringBuilder>();
                while (currentGroup <= totalGroupCount && itemIndex < itemsMarkup.Count)
                {
                    StringBuilder group = new StringBuilder();
                    group.Append(displaySettings.ItemsRepeaterMarkup);
                    //group.SortOrder1 = itemsMarkup[itemIndex].SortOrder1;
                    //group.SortOrder2 = itemsMarkup[itemIndex].SortOrder2;
                    //group.GroupName = itemsMarkup[itemIndex].GroupName;
                    for (int i = 0; i < displaySettings.ItemsPerGroup; i++)
                    {
                        if (itemIndex < itemsMarkup.Count)
                        {
                            group.Replace("$_Items[" + i.ToString() + "]_$", itemsMarkup[itemIndex].ToString());
                            itemIndex++;
                        }
                        else
                        {
                            break;
                        }
                    }
                    groups.Add(group);
                    currentGroup++;
                }

                //groups.Sort(delegate (IndexedStringBuilder a, IndexedStringBuilder b) {
                //    int xdiff = a.SortOrder1.CompareTo(b.SortOrder1);
                //    if (xdiff != 0) return xdiff;
                //    else return a.SortOrder2.CompareTo(b.SortOrder2);
                //});

                foreach (StringBuilder group in groups)
                {
                    allItems.Append(group.ToString());
                }

                strOutput.AppendFormat(displaySettings.ItemsWrapperFormat, Regex.Replace(allItems.ToString(), @"(\$_Items\[[0-9]+\]_\$)", string.Empty, RegexOptions.Multiline));
            }



            //strOutput.Append(displaySettings.ItemListMarkupBottom);
            if (config.RenderJSONOfData)
            {
                if (config.JsonLabelObjects || config.IsGlobalView)
                {
                    jsonWriter.WriteEndObject();

                    if (config.IsGlobalView)
                    {
                        jsonWriter.WriteEndObject();
                        jsonWriter.WriteEnd();
                    }
                }
                else
                {
                    jsonWriter.WriteEndArray();
                }

                MarkupScript jsonScript = new MarkupScript();

                jsonWriter.Close();
                stringWriter.Close();

                jsonScript.RawScript  = stringWriter.ToString();
                jsonScript.Position   = config.JsonRenderLocation;
                jsonScript.ScriptName = "sflexi" + module.ModuleId.ToString() + config.MarkupDefinitionName.ToCleanFileName() + "-JSON";

                List <MarkupScript> scripts = new List <MarkupScript>();
                scripts.Add(jsonScript);

                SuperFlexiHelpers.SetupScripts(scripts, config, displaySettings, IsEditable, IsPostBack, ClientID, ModuleId, PageId, Page, this);
            }

            if (config.UseFooter && config.FooterLocation == "InnerBodyPanel" && !String.IsNullOrWhiteSpace(config.FooterContent) && !String.Equals(config.FooterContent, "<p>&nbsp;</p>"))
            {
                try
                {
                    strOutput.AppendFormat(displaySettings.FooterContentFormat, config.FooterContent);
                }
                catch (System.FormatException ex)
                {
                    log.ErrorFormat(markupErrorFormat, "FooterContentFormat", moduleTitle, ex);
                }
            }

            strOutput.Append(markupBottom);

            SuperFlexiHelpers.ReplaceStaticTokens(strOutput, config, isEditable, displaySettings, module.ModuleId, pageSettings, siteSettings, out strOutput);

            //this is for displaying all of the selected values from the items outside of the items themselves
            foreach (CheckBoxListMarkup cblm in config.CheckBoxListMarkups)
            {
                StringBuilder cblmContent = new StringBuilder();

                if (fields.Count > 0 && cblm.SelectedValues.Count > 0)
                {
                    Field theField = fields.Where(field => field.Name == cblm.Field).Single();
                    if (theField != null)
                    {
                        List <CheckBoxListMarkup.SelectedValue> distinctSelectedValues = new List <CheckBoxListMarkup.SelectedValue>();
                        foreach (CheckBoxListMarkup.SelectedValue selectedValue in cblm.SelectedValues)
                        {
                            CheckBoxListMarkup.SelectedValue match = distinctSelectedValues.Find(i => i.Value == selectedValue.Value);
                            if (match == null)
                            {
                                distinctSelectedValues.Add(selectedValue);
                            }
                            else
                            {
                                match.Count++;
                            }
                        }
                        //var selectedValues = cblm.SelectedValues.GroupBy(selectedValue => selectedValue.Value)
                        //    .Select(distinctSelectedValue => new { Value = distinctSelectedValue.Key, Count = distinctSelectedValue.Count(), ItemID = distinctSelectedValue.ItemID })
                        //    .OrderBy(x => x.Value);
                        foreach (CheckBoxListMarkup.SelectedValue value in distinctSelectedValues)
                        {
                            cblmContent.Append(cblm.Markup.Replace(theField.Token, value.Value).Replace("$_ValueItemID_$", value.ItemID.ToString()) + cblm.Separator);
                            cblmContent.Replace("$_CBLValueCount_$", value.Count.ToString());
                        }
                    }

                    if (cblmContent.Length >= cblm.Separator.Length)
                    {
                        cblmContent.Length -= cblm.Separator.Length;
                    }

                    strOutput.Replace(cblm.Token, cblmContent.ToString());
                }

                strOutput.Replace(cblm.Token, string.Empty);
            }
            theLit.Text = strOutput.ToString();
        }
Пример #30
0
        void SiteMap2_TreeNodeDataBound(object sender, TreeNodeEventArgs e)
        {
            if (sender == null)
            {
                return;
            }
            if (e == null)
            {
                return;
            }

            TreeView        menu    = (TreeView)sender;
            mojoSiteMapNode mapNode = (mojoSiteMapNode)e.Node.DataItem;

            if (e.Node is mojoTreeNode)
            {
                mojoTreeNode tn = e.Node as mojoTreeNode;
                tn.HasVisibleChildren = mapNode.HasVisibleChildren();
            }

            e.Node.Value = mapNode.PageGuid.ToString();

            bool remove = false;

            if (mapNode.Roles == null)
            {
                if ((!isAdmin) && (!isContentAdmin) && (!isSiteEditor))
                {
                    remove = true;
                }
            }
            else
            {
                if ((!isAdmin) && (mapNode.Roles.Count == 1) && (mapNode.Roles[0].ToString() == "Admins"))
                {
                    remove = true;
                }

                if ((!isAdmin) && (!isContentAdmin) && (!isSiteEditor) && (!WebUser.IsInRoles(mapNode.Roles)))
                {
                    remove = true;
                }
            }

            //if (!mapNode.IncludeInMenu) remove = true;
            if (!mapNode.IncludeInChildSiteMap)
            {
                remove = true;
            }
            //if (mapNode.IsPending && !WebUser.IsAdminOrContentAdminOrContentPublisherOrContentAuthor) remove = true;
            if (mapNode.IsPending)
            {
                if (
                    (!isAdmin) &&
                    (!isContentAdmin) &&
                    (!isSiteEditor) &&
                    (!WebUser.IsInRoles(mapNode.EditRoles)) &&
                    (!WebUser.IsInRoles(mapNode.DraftEditRoles))
                    )
                {
                    remove = true;
                }
            }


            if ((mapNode.HideAfterLogin) && (Request.IsAuthenticated))
            {
                remove = true;
            }

            if (isMobileSkin)
            {
                if (mapNode.PublishMode == webOnly)
                {
                    remove = true;
                }
            }
            else
            {
                if (mapNode.PublishMode == mobileOnly)
                {
                    remove = true;
                }
            }

            if (maxRenderDepth > -1)
            {
                if (e.Node.Depth > maxRenderDepth)
                {
                    remove = true;
                }
            }

            if (remove)
            {
                if (e.Node.Depth == 0)
                {
                    menu.Nodes.Remove(e.Node);
                }
                else
                {
                    TreeNode parent = e.Node.Parent;
                    if (parent != null)
                    {
                        parent.ChildNodes.Remove(e.Node);
                    }
                }
            }
            else
            {
                if (honorSiteMapExpandSettings && menu.ShowExpandCollapse)
                {
                    e.Node.Expanded = mapNode.ExpandOnSiteMap;
                }
            }
        }