protected void Page_Load(object sender, EventArgs e)
    {
        // Register script for pendingCallbacks repair
        ScriptHelper.FixPendingCallbacks(Page);

        // If languages on site not ok, redirect
        if (!CultureSiteInfoProvider.LicenseVersionCheck())
        {
            URLHelper.Redirect(ResolveUrl("~/CMSMessages/LicenseLimit.aspx"));
        }

        userId = QueryHelper.GetInteger("userid", 0);
        siteID = SiteID;

        if (userId > 0)
        {
            ui = UserInfoProvider.GetUserInfo(userId);
            CheckUserAvaibleOnSite(ui);
            EditedObject = ui;

            if (!CheckGlobalAdminEdit(ui))
            {
                pnlLanguages.Visible = false;
                ShowError(GetString("Administration-User_List.ErrorGlobalAdmin"));
                return;
            }

            // Set site selector
            siteSelector.DropDownSingleSelect.AutoPostBack = true;
            siteSelector.AllowAll         = false;
            siteSelector.OnlyRunningSites = false;
            siteSelector.UserId           = ui.UserID;
            siteSelector.UniSelector.OnSelectionChanged += UniSelector_OnSelectionChanged;

            if (!RequestHelper.IsPostBack())
            {
                // Initialize radio buttons
                radAllLanguages.Checked      = !ui.UserHasAllowedCultures;
                radSelectedLanguages.Checked = ui.UserHasAllowedCultures;

                // Load the site selector with the data in order to preselect current site (if available in the list)
                siteSelector.UniSelector.SelectionMode = SelectionModeEnum.SingleDropDownList;
                siteSelector.UniSelector.AllowEmpty    = false;
                siteSelector.Reload(true);

                // Select the current site if it is in the list, otherwise select the first site in the list
                if (siteSelector.DropDownSingleSelect.Items.FindByValue(SiteContext.CurrentSiteID.ToString()) != null)
                {
                    siteSelector.Value = SiteContext.CurrentSiteID;
                }
                else if (siteSelector.DropDownSingleSelect.Items.Count > 0)
                {
                    siteSelector.Value = siteSelector.DropDownSingleSelect.Items[0].Value;
                }
                siteSelector.DropDownSingleSelect.SelectedValue = siteSelector.Value.ToString();
            }


            // Show site selection in administration only for global administrator
            if ((SiteID > 0) && (!MembershipContext.AuthenticatedUser.CheckPrivilegeLevel(UserPrivilegeLevelEnum.Admin)))
            {
                plcSite.Visible = false;
            }
            else
            {
                plcSite.Visible = radSelectedLanguages.Checked;
                siteID          = siteSelector.SiteID;
            }

            // Set grid visibility
            plcCultures.Visible = radSelectedLanguages.Checked;

            // Load user cultures
            DataTable dt = UserCultureInfoProvider.GetUserCultures(userId, siteID);
            currentValues = TextHelper.Join(";", DataHelper.GetStringValues(dt, "CultureID"));

            if (!RequestHelper.IsPostBack())
            {
                uniSelector.Value = currentValues;
                uniSelector.Reload(true);
            }
        }

        uniSelector.WhereCondition      = "CultureID IN (SELECT CultureID FROM CMS_SiteCulture WHERE SiteID = " + siteID + ")";
        uniSelector.OnSelectionChanged += uniSelector_OnSelectionChanged;

        radAllLanguages.CheckedChanged      += radAllLanguages_CheckedChanged;
        radSelectedLanguages.CheckedChanged += radSelectedLanguages_CheckedChanged;
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!RequestHelper.IsPostBack())
        {
            string preferredCultureCode = LocalizationContext.PreferredCultureCode;
            string currentSiteName      = SiteContext.CurrentSiteName;
            var    documentCultures     = Node.GetTranslatedCultures();

            // Get site cultures
            DataSet siteCultures = CultureSiteInfoProvider.GetSiteCultures(currentSiteName);
            if (!DataHelper.DataSourceIsEmpty(siteCultures) && (documentCultures.Count > 0))
            {
                string suffixNotTranslated = GetString("SplitMode.NotTranslated");

                foreach (DataRow row in siteCultures.Tables[0].Rows)
                {
                    string cultureCode = ValidationHelper.GetString(row["CultureCode"], null);
                    string cultureName = ResHelper.LocalizeString(ValidationHelper.GetString(row["CultureName"], null));

                    string suffix = string.Empty;

                    // Compare with preferred culture
                    if (CMSString.Compare(preferredCultureCode, cultureCode, true) == 0)
                    {
                        suffix = GetString("SplitMode.Current");
                    }
                    else if (!documentCultures.Contains(cultureCode))
                    {
                        suffix = suffixNotTranslated;
                    }

                    // Add new item
                    var item = new ListItem(cultureName + " " + suffix, cultureCode);
                    drpCultures.Items.Add(item);
                }
            }

            drpCultures.SelectedValue = PortalUIHelper.SplitModeCultureCode;
            drpCultures.Attributes.Add("onchange", "if (parent.CheckChanges('frame2')) { parent.FSP_ChangeCulture(this); }");
        }

        buttons.Actions.Add(new CMSButtonGroupAction {
            Name = "close", UseIconButton = true, OnClientClick = "FSP_Close();return false;", IconCssClass = "icon-l-list-titles", ToolTip = GetString("splitmode.closelayout")
        });
        buttons.Actions.Add(new CMSButtonGroupAction {
            Name = "vertical", UseIconButton = true, OnClientClick = "FSP_Layout('true','frame1','Vertical');return false;", IconCssClass = "icon-l-cols-2 js-split-vertical", ToolTip = GetString("splitmode.verticallayout")
        });
        buttons.Actions.Add(new CMSButtonGroupAction {
            Name = "horizontal", UseIconButton = true, OnClientClick = "FSP_Layout(false,'frame1Vertical','Horizontal');;return false;", IconCssClass = "icon-l-rows-2 js-split-horizontal", ToolTip = GetString("splitmode.horizontallayout")
        });

        // Set css class
        switch (PortalUIHelper.SplitMode)
        {
        case SplitModeEnum.Horizontal:
            buttons.SelectedActionName = "horizontal";
            break;

        case SplitModeEnum.Vertical:
            buttons.SelectedActionName = "vertical";
            break;

        default:
            buttons.SelectedActionName = "close";
            break;
        }

        // Synchronize image
        chckScroll.Checked = PortalUIHelper.SplitModeSyncScrollbars;

        StringBuilder script = new StringBuilder();

        script.Append(
            @"
function FSP_Layout(vertical, frameName, cssClassName)
{
    if ((frameName != null) && parent.CheckChanges(frameName)) {
        if (cssClassName != null) {
            var element = document.getElementById('", pnlMain.ClientID, @"');
            if (element != null) {
                element.setAttribute(""class"", 'SplitToolbar ' + cssClassName);
                element.setAttribute(""className"", 'SplitToolbar ' + cssClassName);
            }
        }
        var divRight = document.getElementById('", divRight.ClientID, @"');
        if (vertical) {
            divRight.setAttribute(""class"", 'RightAlign');
            parent.FSP_VerticalLayout();
        }
        else {
            divRight.setAttribute(""class"", '');
            parent.FSP_HorizontalLayout();
        }
    }
}

function FSP_Close() { 
    if (parent.CheckChanges()) { 
        parent.FSP_CloseSplitMode(); 
    }
}
");

        ScriptHelper.RegisterClientScriptBlock(Page, typeof(string), "toolbarScript_" + ClientID, ScriptHelper.GetScript(script.ToString()));

        chckScroll.Attributes.Add("onchange", "javascript:parent.FSP_SynchronizeToolbar()");

        // Set layout
        if (PortalUIHelper.SplitMode == SplitModeEnum.Horizontal)
        {
            pnlMain.CssClass             = "SplitToolbar Horizontal";
            divRight.Attributes["class"] = null;
        }
        else if (PortalUIHelper.SplitMode == SplitModeEnum.Vertical)
        {
            pnlMain.CssClass = "SplitToolbar Vertical";
        }

        // Register Init script - FSP_ToolbarInit(selectorId, checkboxId)
        StringBuilder initScript = new StringBuilder();

        initScript.Append("parent.FSP_ToolbarInit('", drpCultures.ClientID, "','", chckScroll.ClientID, "');");

        // Register js scripts
        ScriptHelper.RegisterJQuery(Page);
        ScriptHelper.RegisterStartupScript(Page, typeof(string), "FSP_initToolbar", ScriptHelper.GetScript(initScript.ToString()));
    }
Exemple #3
0
    /// <summary>
    /// Creates default mass actions. Has to be called on Page_Init before MassActions extenders are initialized, so default actions will be at athe beginning.
    /// </summary>
    private void CreateMassActionItems()
    {
        var urlBuilder = new DocumentListMassActionsUrlGenerator();

        // Converts functions with signature as in DocumentListMassActionsUrlGenerator to CreateUrlDelegate as MassActionItem expects
        Func <Func <List <int>, DocumentListMassActionsParameters, string>, CreateUrlDelegate> functionConverter = generateActionFunction =>
        {
            return((scope, selectedNodeIDs, parameters) =>
            {
                return generateActionFunction(scope == MassActionScopeEnum.AllItems ? null : selectedNodeIDs, (DocumentListMassActionsParameters)parameters);
            });
        };

        ctrlMassActions.AddMassActions(
            new MassActionItem
        {
            CodeName = "action|move",
            DisplayNameResourceString = "general.move",
            CreateUrl  = functionConverter(urlBuilder.GetMoveActionUrl),
            ActionType = MassActionTypeEnum.OpenModal,
        },
            new MassActionItem
        {
            CodeName = "action|copy",
            DisplayNameResourceString = "general.copy",
            CreateUrl  = functionConverter(urlBuilder.GetCopyActionUrl),
            ActionType = MassActionTypeEnum.OpenModal,
        });

        // It's not allowed to link pages for content only sites
        if (!SiteContext.CurrentSite.SiteIsContentOnly)
        {
            ctrlMassActions.AddMassActions(new MassActionItem
            {
                CodeName = "action|link",
                DisplayNameResourceString = "general.link",
                CreateUrl  = functionConverter(urlBuilder.GetLinkActionUrl),
                ActionType = MassActionTypeEnum.OpenModal,
            });
        }

        ctrlMassActions.AddMassActions(new MassActionItem
        {
            CodeName = "action|delete",
            DisplayNameResourceString = "general.delete",
            CreateUrl  = functionConverter(urlBuilder.GetDeleteActionUrl),
            ActionType = MassActionTypeEnum.Redirect,
        });

        if (CultureSiteInfoProvider.IsSiteMultilingual(currentSiteName) &&
            LicenseHelper.CheckFeature(RequestContext.CurrentDomain, FeatureEnum.TranslationServices) &&
            TranslationServiceHelper.IsTranslationAllowed(currentSiteName) &&
            TranslationServiceHelper.AnyServiceAvailable(currentSiteName))
        {
            ctrlMassActions.AddMassActions(new MassActionItem
            {
                CodeName = "action|translate",
                DisplayNameResourceString = "general.translate",
                CreateUrl  = functionConverter(urlBuilder.GetTranslateActionUrl),
                ActionType = MassActionTypeEnum.Redirect,
            });
        }

        if (currentUserInfo.CheckPrivilegeLevel(UserPrivilegeLevelEnum.Admin) || currentUserInfo.IsAuthorizedPerResource("CMS.Content", "ManageWorkflow"))
        {
            ctrlMassActions.AddMassActions(
                new MassActionItem
            {
                CodeName = "action|publish",
                DisplayNameResourceString = "general.publish",
                CreateUrl  = functionConverter(urlBuilder.GetPublishActionUrl),
                ActionType = MassActionTypeEnum.Redirect,
            },
                new MassActionItem
            {
                CodeName = "action|archive",
                DisplayNameResourceString = "general.archive",
                CreateUrl  = functionConverter(urlBuilder.GetArchiveActionUrl),
                ActionType = MassActionTypeEnum.Redirect,
            });
        }
    }
Exemple #4
0
        private void Begin_Execute(object sender, EventArgs e)
        {
            string url     = RequestContext.CurrentRelativePath + RequestContext.CurrentQueryString;
            string handler = url.Split('/')[1].ToLower();

            string[] notwanted = { "cmspages", "cmsmodules", "cmsformcontrols", "cmsadmincontrols", "admin", "getattachment", "getfile", "getmedia", "getmetafile", "app_themes", "cmsapi", "socialmediaapi", "searchapi", "formsapi", "api" };

            // only run this code if we need to perform a redirect
            if (!notwanted.Contains(handler) && SiteContext.CurrentSite != null)
            {
                var currentSite      = SiteContext.CurrentSite;
                var dictCultureAlias = CacheHelper.GetItem($"RedirectionHandler_CultureAliasDictionary_{currentSite.SiteName}") as Dictionary <string, string>;

                if (dictCultureAlias == null)
                {
                    dictCultureAlias = new Dictionary <string, string>();
                    var domainAliasDict = new Dictionary <string, string>();

                    var primaryAliasInfo = new SiteDomainAliasInfo();
                    primaryAliasInfo.SiteDomainAliasName       = currentSite.DomainName;
                    primaryAliasInfo.SiteDefaultVisitorCulture = currentSite.DefaultVisitorCulture;

                    var domainAliases = SiteDomainAliasInfoProvider.GetDomainAliases().Columns("SiteID", "SiteDomainAliasName", "SiteDefaultVisitorCulture").Where(x => x.SiteID == currentSite.SiteID).ToList();
                    if (domainAliases != null)
                    {
                        domainAliases.Add(primaryAliasInfo);
                        var cultureBindings = CultureSiteInfoProvider.GetCultureSites().WhereEquals("SiteID", SiteContext.CurrentSiteID);
                        foreach (var cultureBinding in cultureBindings)
                        {
                            var culture = CultureInfoProvider.GetCultureInfo(cultureBinding.CultureID);
                            if (culture != null)
                            {
                                if (String.IsNullOrEmpty(culture.CultureAlias))
                                {
                                    var domainAlias = domainAliases.Where(x => x.SiteDefaultVisitorCulture == culture.CultureCode).FirstOrDefault();
                                    if (domainAlias != null)
                                    {
                                        dictCultureAlias.Add(culture.CultureCode, "domain");
                                    }
                                }
                                else
                                {
                                    dictCultureAlias.Add(culture.CultureCode, culture.CultureAlias);
                                }
                            }
                        }
                    }
                    CacheHelper.Add("RedirectionHandler_CultureAliasDictionary", dictCultureAlias, null, DateTime.Now.AddHours(72), System.Web.Caching.Cache.NoSlidingExpiration);
                }

                var currentCulture = LocalizationContext.CurrentCulture.CultureCode;

                //Not sure if this is a Kentico bug or not, but LocalizationContext.CurrentCulture.CultureCode sometimes does not actually show the current user's culture
                //This usually happens if this is the first request by a user on a new culture. Comparing it to the cookie value of the user always shows the correct culture
                if (!String.IsNullOrEmpty(CookieHelper.GetValue("CMSPreferredCulture")) && CookieHelper.GetValue("CMSPreferredCulture") != currentCulture)
                {
                    currentCulture = CookieHelper.GetValue("CMSPreferredCulture");
                }

                if (dictCultureAlias.ContainsKey(currentCulture))
                {
                    //Handle Redirect
                    try
                    {
                        int site         = SiteContext.CurrentSiteID;
                        var cultureCode  = currentCulture;
                        var cultureAlias = dictCultureAlias[cultureCode];

                        // make sure the culture has been set for the site
                        URLRedirectionMethods.Redirect(url, site, cultureCode, cultureAlias);
                    }
                    catch (ThreadAbortException threadEx)
                    {
                        //Do nothing: this exception is thrown by Response.Redirect() in the redirect method. We only want to log other kinds of exceptions
                    }
                    catch (Exception ex)
                    {
                        EventLogProvider.LogException("RedirectionMethods.Redirect", "REDIRECT_FAILED", ex, additionalMessage: "An exception occurred during the redirect process");
                    }
                }
                else
                {
                    EventLogProvider.LogInformation("UrlRedirection.RedirectionHandler.Begin_Execute", "REDIRECT_FAILED", $"The culture code: {LocalizationContext.CurrentCulture.CultureCode} was not assigned to the site. Unable to redirect URL: {RequestContext.RawURL}");
                }
            }
        }
    /// <summary>
    /// Reloads control.
    /// </summary>
    /// <param name="forceReload">Forces nested CMSForm to reload if true</param>
    public void ReloadData(bool forceReload)
    {
        if (StopProcessing)
        {
            return;
        }

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

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

                ScriptHelper.RegisterDialogScript(Page);

                titleElem.TitleText = String.Empty;

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

                // If node found, init the form

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

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

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

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

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

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

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

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

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

                                ArrayList deleteRows = new ArrayList();

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                            // Allow the CMSForm
                            formElem.StopProcessing = false;

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

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

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

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

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

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

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

                            DataSet nodes = TreeProvider.SelectNodes(si.SiteName, Node.NodeAliasPath, TreeProvider.ALL_CULTURES, false, null, null, null, 1, false);
                            foreach (DataRow nodeCulture in nodes.Tables[0].Rows)
                            {
                                ListItem li = new ListItem();
                                li.Text  = CultureInfoProvider.GetCultureInfo(nodeCulture["DocumentCulture"].ToString()).CultureName;
                                li.Value = nodeCulture["DocumentID"].ToString();
                                lstCultures.Items.Add(li);
                            }
                            if (lstCultures.Items.Count > 0)
                            {
                                lstCultures.SelectedIndex = 0;
                            }
                        }
                    }
                    else
                    {
                        pnlInfo.Visible  = true;
                        lblFormInfo.Text = GetString("EditForm.DocumentNotFound");
                    }
                }
            }
            // Set flag that the form is loaded
            mFormLoaded = true;
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        ScriptHelper.RegisterJQuery(Page);
        ScriptHelper.RegisterModule(Page, "CMS.Content/LanguageMenu");

        CSSHelper.RegisterCSSLink(Page, "~/CMSScripts/jquery/jquery-jscrollpane.css");

        string currentSiteName = (SiteID != 0) ? SiteInfoProvider.GetSiteName(SiteID) : SiteContext.CurrentSiteName;
        var    cultures        = CultureSiteInfoProvider.GetSiteCultures(currentSiteName).Items;

        if (cultures.Count > 1)
        {
            string      defaultCulture = CultureHelper.GetDefaultCultureCode(currentSiteName);
            CultureInfo ci             = CultureInfoProvider.GetCultureInfo(SelectedCulture);

            imgLanguage.ImageUrl      = GetFlagIconUrl(SelectedCulture, "16x16");
            imgLanguage.AlternateText = imgLanguage.ToolTip = GetString(ci.CultureName);
            lblLanguageName.Text      = ci.CultureShortName;

            // Generate sub-menu only if more cultures to choose from
            StringBuilder sb = new StringBuilder();
            foreach (var culture in cultures)
            {
                string cultureCode = culture.CultureCode;
                string cultureName = HTMLHelper.HTMLEncode(culture.CultureName);

                if (CMSString.Compare(cultureCode, defaultCulture, true) == 0)
                {
                    cultureName += " " + GetString("general.defaultchoice");
                }

                string flagUrl = GetFlagIconUrl(cultureCode, "16x16");

                var click = String.Format("ChangeLanguage({0}); return false;", ScriptHelper.GetString(cultureCode));

                sb.AppendFormat("<li><a href=\"#\" onclick=\"{0}\"><img src=\"{1}\" alt=\"\" class=\"language-flag\"><span class=\"language-name\">{2}</span></a></li>", click, flagUrl, cultureName);
            }

            ltlLanguages.Text = sb.ToString();

            // Split view button
            if (DisplayCompare)
            {
                btnCompare.ToolTip = GetString("SplitMode.CompareLangVersions");
                btnCompare.Text    = GetString("SplitMode.Compare");
                if (UIContext.DisplaySplitMode)
                {
                    btnCompare.AddCssClass("active");
                }
                else
                {
                    btnCompare.RemoveCssClass("active");
                }
            }
        }
        else
        {
            // Hide language menu for one assigned culture on site
            Visible = false;
        }
    }
    private void Control_OnSelectionChanged(object sender, EventArgs e)
    {
        int         cultureId = QueryHelper.GetInteger("objectid", 0);
        CultureInfo culture   = GetSafeCulture(cultureId);

        // Get the current sites
        string currentValues = GetCultureSites(cultureId);
        // Get sites from selector
        string newValues = ValidationHelper.GetString(Control.Value, null);

        bool     somethingChanged = false;
        bool     hasErrors        = false;
        int      siteId;
        SiteInfo si;
        DataSet  nodes;

        string[] newItems;

        // Remove old items
        string items = DataHelper.GetNewItemsInList(newValues, currentValues);

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

                    si = SiteInfoProvider.GetSiteInfo(siteId);
                    if ((si != null) && (culture != null))
                    {
                        // Check if site does not contain document from this culture
                        nodes = tree.SelectNodes(si.SiteName, "/%", culture.CultureCode, false, null, null, null, -1, false, 1, "NodeID");
                        if (DataHelper.DataSourceIsEmpty(nodes))
                        {
                            CultureSiteInfoProvider.RemoveCultureFromSite(culture.CultureID, siteId);
                            somethingChanged = true;
                        }
                        else
                        {
                            hasErrors = true;
                            Control.ShowError(string.Format(Control.GetString("culture.ErrorRemoveSiteFromCulture"), si.DisplayName));
                            continue;
                        }
                    }
                }
            }
        }

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

                    // Add cullture to site
                    si = SiteInfoProvider.GetSiteInfo(siteId);
                    if (si != null)
                    {
                        if (CultureSiteInfoProvider.LicenseVersionCheck(si.DomainName, FeatureEnum.Multilingual, ObjectActionEnum.Insert))
                        {
                            CultureSiteInfoProvider.AddCultureToSite(culture.CultureID, siteId);
                            somethingChanged = true;
                        }
                        else
                        {
                            hasErrors = true;
                            Control.ShowError(Control.GetString("licenselimitation.siteculturesexceeded"));
                            break;
                        }
                    }
                }
            }
        }

        // If there were some errors, reload uniselector
        if (hasErrors)
        {
            Control.Value = GetCultureSites(cultureId);
            Control.Reload(true);
        }

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

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

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

        try
        {
            bool newGroup = false;

            // Update existing item
            if (groupInfo == null)
            {
                groupInfo = new GroupInfo();
                newGroup  = true;
            }

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

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

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

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

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

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

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

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

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

                                    // Update stylesheet id if set
                                    if (selectedSheetID == 0)
                                    {
                                        node.DocumentStylesheetID       = 0;
                                        node.DocumentInheritsStylesheet = true;
                                    }
                                    else
                                    {
                                        node.DocumentStylesheetID = selectedSheetID;
                                    }

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

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

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

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

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

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

            // Display information on success
            ShowChangesSaved();

            // If new group was created
            if (newGroup)
            {
                GroupID = groupInfo.GroupID;
                RaiseOnSaved();
            }
        }
        catch (Exception ex)
        {
            // Display error message
            ShowError(GetString("general.saveerror"), ex.Message, null);
        }
    }
Exemple #9
0
    protected void Page_Load(object sender, EventArgs e)
    {
        // Register script files
        ScriptHelper.RegisterCMS(this);
        ScriptHelper.RegisterScriptFile(this, "~/CMSModules/Content/CMSDesk/Operation.js");

        // Set current UI culture
        currentCulture = CultureHelper.PreferredUICultureCode;
        // Initialize current user
        currentUser = MembershipContext.AuthenticatedUser;
        // Initialize current site
        currentSite = SiteContext.CurrentSite;

        // Initialize events
        ctlAsyncLog.OnFinished += ctlAsyncLog_OnFinished;
        ctlAsyncLog.OnError    += ctlAsyncLog_OnError;
        ctlAsyncLog.OnCancel   += ctlAsyncLog_OnCancel;

        if (!RequestHelper.IsCallback())
        {
            DataSet      allDocs = null;
            TreeProvider tree    = new TreeProvider(currentUser);

            // Current Node ID to delete
            string parentAliasPath = string.Empty;
            if (Parameters != null)
            {
                parentAliasPath = ValidationHelper.GetString(Parameters["parentaliaspath"], string.Empty);
            }
            if (string.IsNullOrEmpty(parentAliasPath))
            {
                nodeIdsArr = QueryHelper.GetString("nodeid", string.Empty).Trim('|').Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
                foreach (string nodeId in nodeIdsArr)
                {
                    int id = ValidationHelper.GetInteger(nodeId, 0);
                    if (id != 0)
                    {
                        nodeIds.Add(id);
                    }
                }
            }
            else
            {
                var where = new WhereCondition(WhereCondition)
                            .WhereNotEquals("ClassName", SystemDocumentTypes.Root);
                allDocs = tree.SelectNodes(currentSite.SiteName, parentAliasPath.TrimEnd(new[] { '/' }) + "/%",
                                           TreeProvider.ALL_CULTURES, true, ClassID > 0 ? DataClassInfoProvider.GetClassName(ClassID) : TreeProvider.ALL_CLASSNAMES, where.ToString(true),
                                           "DocumentName", TreeProvider.ALL_LEVELS, false, 0,
                                           DocumentColumnLists.SELECTNODES_REQUIRED_COLUMNS + ",DocumentName,NodeParentID,NodeSiteID,NodeAliasPath,NodeSKUID");

                if (!DataHelper.DataSourceIsEmpty(allDocs))
                {
                    foreach (DataTable table in allDocs.Tables)
                    {
                        foreach (DataRow row in table.Rows)
                        {
                            nodeIds.Add(ValidationHelper.GetInteger(row["NodeID"], 0));
                        }
                    }
                }
            }

            // Setup page title text and image
            PageTitle.TitleText = GetString("Content.DeleteTitle");
            EnsureDocumentBreadcrumbs(PageBreadcrumbs, action: PageTitle.TitleText);

            // Register the dialog script
            ScriptHelper.RegisterDialogScript(this);

            ctlAsyncLog.TitleText = GetString("ContentDelete.DeletingDocuments");
            // Set visibility of panels
            pnlContent.Visible = true;
            pnlLog.Visible     = false;

            bool isMultilingual = CultureSiteInfoProvider.IsSiteMultilingual(currentSite.SiteName);
            if (!isMultilingual)
            {
                // Set all cultures checkbox
                chkAllCultures.Checked = true;
                pnlAllCultures.Visible = false;
            }

            if (nodeIds.Count > 0)
            {
                if (nodeIds.Count == 1)
                {
                    // Single document deletion
                    int      nodeId = ValidationHelper.GetInteger(nodeIds[0], 0);
                    TreeNode node   = null;

                    if (string.IsNullOrEmpty(parentAliasPath))
                    {
                        // Get any culture if current not found
                        node = tree.SelectSingleNode(nodeId, CultureCode) ?? tree.SelectSingleNode(nodeId, TreeProvider.ALL_CULTURES);
                    }
                    else
                    {
                        if (allDocs != null)
                        {
                            DataRow dr = allDocs.Tables[0].Rows[0];
                            node = TreeNode.New(ValidationHelper.GetString(dr["ClassName"], string.Empty), dr, tree);
                        }
                    }

                    if (node != null)
                    {
                        bool rootDeleteDisabled = false;

                        if (IsProductsMode)
                        {
                            string startingPath = SettingsKeyInfoProvider.GetValue(CurrentSiteName + ".CMSStoreProductsStartingPath");
                            if (node.NodeAliasPath.CompareToCSafe(startingPath) == 0)
                            {
                                string closeLink = "<a href=\"#\"><span style=\"cursor: pointer;\" " +
                                                   "onclick=\"SelectNode(" + node.NodeID + "); return false;\">" + GetString("general.back") +
                                                   "</span></a>";

                                ShowError(string.Format(GetString("com.productsection.deleteroot"), closeLink, ""));
                                pnlDelete.Visible  = false;
                                rootDeleteDisabled = true;
                            }
                        }

                        if (node.IsRoot() && isMultilingual)
                        {
                            // Hide 'Delete all cultures' checkbox
                            pnlAllCultures.Visible = false;

                            if (!RequestHelper.IsPostBack())
                            {
                                // Check if there are any documents in another culture or current culture has some documents
                                pnlDeleteRoot.Visible = IsAnyDocumentInAnotherCulture(node) && (tree.SelectNodesCount(SiteContext.CurrentSiteName, "/%", LocalizationContext.PreferredCultureCode, false, null, null, null, TreeProvider.ALL_LEVELS, false) > 0);

                                if (pnlDeleteRoot.Visible)
                                {
                                    // Insert 'Delete current root' option if current root node is translated to current culture
                                    if (node.DocumentCulture == LocalizationContext.PreferredCultureCode)
                                    {
                                        rblRoot.Items.Add(new ListItem(GetString("rootdeletion.currentroot"), "current"));
                                    }

                                    rblRoot.Items.Add(new ListItem(GetString("rootdeletion.currentculture"), "allculturepages"));
                                    rblRoot.Items.Add(new ListItem(GetString("rootdeletion.allpages"), "allpages"));
                                }
                                else
                                {
                                    rblRoot.Items.Add(new ListItem(GetString("rootdeletion.allpages"), "allpages"));
                                }

                                if (rblRoot.SelectedIndex < 0)
                                {
                                    rblRoot.SelectedIndex = 0;
                                }
                            }
                        }

                        // Display warning for root node
                        if (!rootDeleteDisabled && node.IsRoot())
                        {
                            if (!currentUser.CheckPrivilegeLevel(UserPrivilegeLevelEnum.Admin))
                            {
                                pnlDelete.Visible = false;

                                ShowInformation(GetString("delete.rootonlyglobaladmin"));
                            }
                            else
                            {
                                if ((rblRoot.SelectedValue == "allpages") || !isMultilingual || ((rblRoot.SelectedValue == "allculturepages") && !IsAnyDocumentInAnotherCulture(node)))
                                {
                                    messagesPlaceholder.ShowWarning(GetString("Delete.RootWarning"));

                                    plcDeleteRoot.Visible = true;
                                }
                                else
                                {
                                    plcDeleteRoot.Visible = false;
                                }
                            }
                        }

                        hasChildren = node.NodeHasChildren;

                        bool authorizedToDeleteSKU = !node.HasSKU || IsUserAuthorizedToModifySKU(node);
                        if (!RequestHelper.IsPostBack())
                        {
                            bool authorizedToDeleteDocument = IsUserAuthorizedToDeleteDocument(node);
                            if (!authorizedToDeleteDocument || !authorizedToDeleteSKU)
                            {
                                pnlDelete.Visible = false;
                                RedirectToAccessDenied(String.Format(GetString("cmsdesk.notauthorizedtodeletedocument"), HTMLHelper.HTMLEncode(node.NodeAliasPath)));
                            }
                        }

                        if (node.IsLink)
                        {
                            PageTitle.TitleText    = GetString("Content.DeleteTitleLink") + " \"" + HTMLHelper.HTMLEncode(ResHelper.LocalizeString(node.GetDocumentName())) + "\"";
                            headQuestion.Text      = GetString("ContentDelete.QuestionLink");
                            chkAllCultures.Checked = true;
                            plcCheck.Visible       = false;
                        }
                        else
                        {
                            string nodeName = HTMLHelper.HTMLEncode(node.GetDocumentName());
                            // Get name for root document
                            if (node.IsRoot())
                            {
                                nodeName = HTMLHelper.HTMLEncode(currentSite.DisplayName);
                            }
                            PageTitle.TitleText = GetString("Content.DeleteTitle") + " \"" + HTMLHelper.HTMLEncode(ResHelper.LocalizeString(nodeName)) + "\"";
                        }

                        // Show or hide checkbox
                        pnlDestroy.Visible = CanDestroy(node);

                        cancelNodeId = IsMultipleAction ? node.NodeParentID : node.NodeID;

                        lblDocuments.Text = HTMLHelper.HTMLEncode(node.GetDocumentName());

                        SetSeoPanelVisibility(node);
                    }
                    else
                    {
                        if (!RequestHelper.IsPostBack())
                        {
                            URLHelper.Redirect(AdministrationUrlHelper.GetInformationUrl("editeddocument.notexists"));
                        }
                        else
                        {
                            // Hide everything
                            pnlContent.Visible = false;
                        }
                    }

                    headQuestion.Text       = GetString("ContentDelete.Question");
                    lblAllCultures.Text     = GetString("ContentDelete.AllCultures");
                    lblDestroy.Text         = GetString("ContentDelete.Destroy");
                    headDeleteDocument.Text = GetString("ContentDelete.Document");
                }
                else if (nodeIds.Count > 1)
                {
                    string where = "NodeID IN (";
                    foreach (int nodeID in nodeIds)
                    {
                        where += nodeID + ",";
                    }

                    where = where.TrimEnd(',') + ")";
                    DataSet ds = allDocs ?? tree.SelectNodes(currentSite.SiteName, "/%", TreeProvider.ALL_CULTURES, true, null, where, "DocumentName", -1, false);

                    if (!DataHelper.DataSourceIsEmpty(ds))
                    {
                        string docList = null;

                        if (string.IsNullOrEmpty(parentAliasPath))
                        {
                            cancelNodeId = DataHelper.GetIntValue(ds.Tables[0].Rows[0], "NodeParentID");
                        }
                        else
                        {
                            cancelNodeId = TreePathUtils.GetNodeIdByAliasPath(currentSite.SiteName, parentAliasPath);
                        }

                        bool canDestroy  = true;
                        bool permissions = true;

                        foreach (DataTable table in ds.Tables)
                        {
                            foreach (DataRow dr in table.Rows)
                            {
                                bool   isLink = (dr["NodeLinkedNodeID"] != DBNull.Value);
                                string name   = (string)dr["DocumentName"];
                                docList += HTMLHelper.HTMLEncode(name);
                                if (isLink)
                                {
                                    docList += DocumentUIHelper.GetDocumentMarkImage(Page, DocumentMarkEnum.Link);
                                }
                                docList          += "<br />";
                                lblDocuments.Text = docList;

                                // Set visibility of checkboxes
                                TreeNode node = TreeNode.New(ValidationHelper.GetString(dr["ClassName"], string.Empty), dr);

                                SetSeoPanelVisibility(node);

                                if (!IsUserAuthorizedToDeleteDocument(node))
                                {
                                    permissions = false;
                                    AddError(String.Format(
                                                 GetString("cmsdesk.notauthorizedtodeletedocument"),
                                                 HTMLHelper.HTMLEncode(node.NodeAliasPath)), null);
                                }

                                // Can destroy if "can destroy all previous AND current"
                                canDestroy = CanDestroy(node) && canDestroy;

                                if (!hasChildren)
                                {
                                    hasChildren = node.NodeHasChildren;
                                }
                            }
                        }

                        pnlDelete.Visible  = permissions;
                        pnlDestroy.Visible = canDestroy;
                    }
                    else
                    {
                        if (!RequestHelper.IsPostBack())
                        {
                            URLHelper.Redirect(AdministrationUrlHelper.GetInformationUrl("editeddocument.notexists"));
                        }
                        else
                        {
                            // Hide everything
                            pnlContent.Visible = false;
                        }
                    }

                    headQuestion.Text       = GetString("ContentDelete.QuestionMultiple");
                    PageTitle.TitleText     = GetString("Content.DeleteTitleMultiple");
                    lblAllCultures.Text     = GetString("ContentDelete.AllCulturesMultiple");
                    lblDestroy.Text         = GetString("ContentDelete.DestroyMultiple");
                    headDeleteDocument.Text = GetString("global.pages");
                }

                lblAltPath.AssociatedControlClientID = selAltPath.PathTextBox.ClientID;

                selAltPath.SiteID = currentSite.SiteID;

                chkUseDeletedPath.CheckedChanged += chkUseDeletedPath_CheckedChanged;
                if (!RequestHelper.IsPostBack())
                {
                    selAltPath.Enabled     = false;
                    chkAltSubNodes.Enabled = false;
                    chkAltAliases.Enabled  = false;

                    // Set default path if is defined
                    selAltPath.Value = SettingsKeyInfoProvider.GetValue(CurrentSiteName + ".CMSDefaultDeletedNodePath");

                    if (!hasChildren)
                    {
                        chkAltSubNodes.Checked = false;
                        chkAltSubNodes.Enabled = false;
                    }
                }

                // If user has allowed cultures specified
                if (currentUser.UserHasAllowedCultures)
                {
                    // Get all site cultures
                    DataSet siteCultures            = CultureSiteInfoProvider.GetSiteCultures(currentSite.SiteName);
                    bool    denyAllCulturesDeletion = false;
                    // Check that user can edit all site cultures
                    foreach (DataRow culture in siteCultures.Tables[0].Rows)
                    {
                        string cultureCode = DataHelper.GetStringValue(culture, "CultureCode");
                        if (!currentUser.IsCultureAllowed(cultureCode, currentSite.SiteName))
                        {
                            denyAllCulturesDeletion = true;
                        }
                    }
                    // If user can't edit all site cultures
                    if (denyAllCulturesDeletion)
                    {
                        // Hide all cultures selector
                        pnlAllCultures.Visible = false;
                        chkAllCultures.Checked = false;
                    }
                }
                pnlDeleteDocument.Visible = pnlAllCultures.Visible || pnlDestroy.Visible;
            }
            else
            {
                // Hide everything
                pnlContent.Visible = false;
            }
        }

        // Initialize header action
        InitializeActionMenu();
    }
Exemple #10
0
    protected void OnTabCreated(object sender, TabCreatedEventArgs e)
    {
        if (e.Tab == null)
        {
            return;
        }

        var tab     = e.Tab;
        var element = e.UIElement;

        var manager = DocumentManager;
        var node    = manager.Node;

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

        string elementName = element.ElementName.ToLowerCSafe();

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

        switch (elementName)
        {
        case "properties.languages":
            splitViewSupported = false;
            if (!CultureSiteInfoProvider.IsSiteMultilingual(SiteContext.CurrentSiteName) || !CultureSiteInfoProvider.LicenseVersionCheck())
            {
                e.Tab = null;
                return;
            }
            break;

        case "properties.security":
        case "properties.relateddocs":
        case "properties.linkeddocs":
            splitViewSupported = false;
            break;

        case "properties.variants":

            if (DataHelper.GetNotEmpty(RequestContext.CurrentDomain, "") != "")
            {
                // Check license and whether content personalization is enabled and whether exists at least one variant for current template
                if ((node == null) ||
                    !LicenseHelper.IsFeatureAvailableInUI(FeatureEnum.ContentPersonalization, ModuleName.ONLINEMARKETING) ||
                    !ResourceSiteInfoProvider.IsResourceOnSite("CMS.ContentPersonalization", SiteContext.CurrentSiteName) ||
                    !PortalContext.ContentPersonalizationEnabled ||
                    (VariantHelper.GetVariantID(VariantModeEnum.ContentPersonalization, node.GetUsedPageTemplateId(), String.Empty) <= 0))
                {
                    e.Tab = null;
                    return;
                }
            }
            break;

        case "properties.workflow":
        case "properties.versions":
            if (manager.Workflow == null)
            {
                e.Tab = null;
                return;
            }
            break;

        case "properties.personas":
            tab.RedirectUrl = URLHelper.AddParameterToUrl(tab.RedirectUrl, "objectid", manager.NodeID.ToString(CultureInfo.InvariantCulture));
            break;
        }

        // UI elements could have a different display name if content only document is selected
        tab.Text = DocumentUIHelper.GetUIElementDisplayName(element, node);

        // Ensure split view mode
        if (splitViewSupported && UIContext.DisplaySplitMode)
        {
            tab.RedirectUrl = DocumentUIHelper.GetSplitViewUrl(tab.RedirectUrl);
        }
    }
    /// <summary>
    /// Initializes the control properties.
    /// </summary>
    protected void SetupControl()
    {
        if (StopProcessing)
        {
            // Do nothing
        }
        else
        {
            // If there is only one culture on site and hiding is enabled hide webpart
            if (HideIfOneCulture && !CultureSiteInfoProvider.IsSiteMultilingual(SiteContext.CurrentSiteName))
            {
                Visible = false;
                return;
            }

            // Get list of cultures
            List <string[]> cultures = GetCultures();

            // Check whether exists more than one culture
            if ((cultures != null) && ((cultures.Count > 1) || (HideCurrentCulture && (cultures.Count > 0))))
            {
                // Add CSS Stylesheet
                CSSHelper.RegisterCSSLink(Page, URLHelper.ResolveUrl("~/CMSWebparts/Localization/languageselectiondropdown_files/langselector.css"));

                string imgFlagIcon = String.Empty;

                StringBuilder result = new StringBuilder();
                result.Append("<ul class=\"langselector\">");

                // Set first item to the current language
                CultureInfo ci = CultureInfoProvider.GetCultureInfo(CultureHelper.GetPreferredCulture());
                if (ci != null)
                {
                    // Drop down imitating icon
                    string dropIcon = ResolveUrl("~/CMSWebparts/Localization/languageselectiondropdown_files/dd_arrow.gif");

                    // Current language
                    imgFlagIcon = GetImageUrl("Flags/16x16/" + HTMLHelper.HTMLEncode(ci.CultureCode) + ".png");

                    string currentCultureShortName = String.Empty;
                    if (ShowCultureNames)
                    {
                        currentCultureShortName = HTMLHelper.HTMLEncode(ci.CultureShortName);
                    }

                    result.AppendFormat("<li class=\"lifirst\" style=\"background-image:url('{0}'); background-repeat: no-repeat\"><a class=\"first\" style=\"background-image:url({1}); background-repeat: no-repeat\" href=\"{2}\">{3}</a>",
                                        dropIcon, imgFlagIcon, "#", currentCultureShortName);
                }

                result.Append("<ul>");

                // Loop thru all cultures
                foreach (string[] data in cultures)
                {
                    string url  = data[0];
                    string code = data[1];
                    string name = HTMLHelper.HTMLEncode(data[2]);

                    // Language icon
                    imgFlagIcon = GetImageUrl("Flags/16x16/" + HTMLHelper.HTMLEncode(code) + ".png");
                    if (!ShowCultureNames)
                    {
                        name = string.Empty;
                    }

                    result.AppendFormat("<li><a style=\"background-image:url({0}); background-repeat: no-repeat\" href=\"{1}\">{2}</a></li>\r\n",
                                        imgFlagIcon, HTMLHelper.EncodeForHtmlAttribute(URLHelper.ResolveUrl(url)), name);
                }

                result.Append("</ul></li></ul>");
                ltlLanguages.Text = result.ToString();
            }
            else if (HideIfOneCulture)
            {
                Visible = false;
            }
        }
    }
    protected void ContextMenu_OnReloadData(object sender, EventArgs e)
    {
        int nodeId = ValidationHelper.GetInteger(ContextMenu.Parameter, 0);

        // Get the node
        var tree = new TreeProvider(MembershipContext.AuthenticatedUser);
        var node = tree.SelectSingleNode(nodeId);

        if (node != null)
        {
            if (plcProperties.Visible)
            {
                // Properties menu
                var elements = UIElementInfoProvider.GetChildUIElements("CMS.Content", "Properties");
                if (!DataHelper.DataSourceIsEmpty(elements))
                {
                    var      index = 0;
                    UserInfo user  = MembershipContext.AuthenticatedUser;

                    foreach (var element in elements)
                    {
                        // Skip elements not relevant for given node
                        if (DocumentUIHelper.IsElementHiddenForNode(element, node))
                        {
                            continue;
                        }

                        var elementName = element.ElementName.ToLowerInvariant();

                        // If UI element is available and user has permission to show it then add it
                        if (UIContextHelper.CheckElementAvailabilityInUI(element) && user.IsAuthorizedPerUIElement(element.ElementResourceID, elementName))
                        {
                            switch (elementName)
                            {
                            case "properties.languages":
                                if (!CultureSiteInfoProvider.IsSiteMultilingual(SiteContext.CurrentSiteName) || !CultureSiteInfoProvider.LicenseVersionCheck())
                                {
                                    continue;
                                }
                                break;

                            case "properties.variants":
                                if (!LicenseHelper.IsFeatureAvailableInUI(FeatureEnum.ContentPersonalization, ModuleName.ONLINEMARKETING) ||
                                    !ResourceSiteInfoProvider.IsResourceOnSite("CMS.ContentPersonalization", SiteContext.CurrentSiteName) ||
                                    !PortalContext.ContentPersonalizationEnabled ||
                                    (VariantHelper.GetVariantID(VariantModeEnum.ContentPersonalization, node.GetUsedPageTemplateId(), String.Empty) <= 0))
                                {
                                    continue;
                                }
                                break;

                            case "properties.workflow":
                            case "properties.versions":
                                if (node.GetWorkflow() == null)
                                {
                                    continue;
                                }
                                break;
                            }

                            var item = new ContextMenuItem();
                            item.ID = "p" + index;
                            item.Attributes.Add("onclick", String.Format("Properties(GetContextMenuParameter('nodeMenu'), '{0}');", elementName));

                            // UI elements could have a different display name if content only document is selected
                            item.Text = DocumentUIHelper.GetUIElementDisplayName(element, node);

                            pnlPropertiesMenu.Controls.Add(item);

                            index++;
                        }
                    }

                    if (index == 0)
                    {
                        // Hide 'Properties' menu if user has no permission for at least one properties section
                        plcProperties.Visible = false;
                    }
                }
            }
        }
        else
        {
            iNoNode.Visible = true;
            plcFirstLevelContainer.Visible = false;
        }
    }
Exemple #13
0
    /// <summary>
    /// Assigns another culture to the current site, then creates the document structure and workflow scope needed for this example. Called when the "Create example objects" button is pressed.
    /// </summary>
    private bool CreateExampleObjects()
    {
        // Add a new culture to the current site
        CultureInfo culture = CultureInfoProvider.GetCultureInfo("de-de");

        CultureSiteInfoProvider.AddCultureToSite(culture.CultureID, SiteContext.CurrentSiteID);

        // Create a new tree provider
        TreeProvider tree = new TreeProvider(MembershipContext.AuthenticatedUser);

        // Get the root node
        TreeNode parent = tree.SelectSingleNode(SiteContext.CurrentSiteName, "/", "en-us");

        if (parent != null)
        {
            // Create the API example folder
            TreeNode node = TreeNode.New("CMS.Folder", tree);

            node.DocumentName    = "API Example";
            node.DocumentCulture = "en-us";

            // Insert it to database
            DocumentHelper.InsertDocument(node, parent, tree);

            parent = node;

            // Create the Source folder for moving
            node = TreeNode.New("CMS.Folder", tree);

            node.DocumentName    = "Source";
            node.DocumentCulture = "en-us";

            DocumentHelper.InsertDocument(node, parent, tree);

            // Create the Target folder for moving
            node = TreeNode.New("CMS.Folder", tree);

            node.DocumentName    = "Target";
            node.DocumentCulture = "en-us";

            DocumentHelper.InsertDocument(node, parent, tree);

            // Get the default workflow
            WorkflowInfo workflow = WorkflowInfoProvider.GetWorkflowInfo("default");

            if (workflow != null)
            {
                // Get the example folder data
                node = DocumentHelper.GetDocument(parent, tree);

                // Create new workflow scope
                WorkflowScopeInfo scope = new WorkflowScopeInfo();

                // Assign to the default workflow and current site and set starting alias path to the example document
                scope.ScopeWorkflowID   = workflow.WorkflowID;
                scope.ScopeStartingPath = node.NodeAliasPath;
                scope.ScopeSiteID       = SiteContext.CurrentSiteID;

                // Save the scope into the database
                WorkflowScopeInfoProvider.SetWorkflowScopeInfo(scope);

                return(true);
            }
            else
            {
                apiCreateExampleObjects.ErrorMessage = "The default workflow was not found.";
            }
        }

        return(false);
    }
    protected DataSet gridDocuments_OnDataReload(string completeWhere, string currentOrder, int currentTopN, string columns, int currentOffset, int currentPageSize, ref int totalRecords)
    {
        if (Node == null)
        {
            return(null);
        }

        // Get documents
        string currentSiteName = SiteContext.CurrentSiteName;
        int    topN            = gridLanguages.GridView.PageSize * (gridLanguages.GridView.PageIndex + 1 + gridLanguages.GridView.PagerSettings.PageButtonCount);

        columns = SqlHelper.MergeColumns(SqlHelper.MergeColumns(DocumentColumnLists.SELECTNODES_REQUIRED_COLUMNS, columns), "DocumentModifiedWhen, DocumentLastVersionNumber, DocumentLastPublished, DocumentIsWaitingForTranslation");

        var query =
            DocumentHelper.GetDocuments()
            .OnSite(currentSiteName)
            .Path(Node.NodeAliasPath)
            .AllCultures()
            .Published(false)
            .TopN(topN)
            .Columns(columns);

        // Do not apply published from / to columns to make sure the published information is correctly evaluated
        query.Properties.ExcludedVersionedColumns = new[] { "DocumentPublishFrom", "DocumentPublishTo" };

        var data = query.Result;

        if (DataHelper.DataSourceIsEmpty(data))
        {
            return(null);
        }

        var documents = data.Tables[0];

        // Get site cultures
        var allSiteCultures = CultureSiteInfoProvider.GetSiteCultures(currentSiteName).Copy();

        // Rename culture column to enable row transfer
        allSiteCultures.Tables[0].Columns[2].ColumnName = "DocumentCulture";

        // Create where condition for row transfer
        string where = documents.Rows.Cast <DataRow>().Aggregate("DocumentCulture NOT IN (", (current, row) => current + ("'" + SqlHelper.EscapeQuotes(ValidationHelper.GetString(row["DocumentCulture"], string.Empty)) + "',"));
        where        = where.TrimEnd(',') + ")";

        // Transfer missing cultures, keep original list of site cultures
        DataHelper.TransferTableRows(documents, allSiteCultures.Copy().Tables[0], where, null);
        DataHelper.EnsureColumn(documents, "DocumentCultureDisplayName", typeof(string));

        // Ensure culture names
        foreach (DataRow cultDR in documents.Rows)
        {
            string    cultureCode = cultDR["DocumentCulture"].ToString();
            DataRow[] cultureRow  = allSiteCultures.Tables[0].Select("DocumentCulture='" + cultureCode + "'");
            if (cultureRow.Length > 0)
            {
                cultDR["DocumentCultureDisplayName"] = cultureRow[0]["CultureName"].ToString();
            }
        }

        // Ensure default culture to be first
        DataRow[] cultureDRs = documents.Select("DocumentCulture='" + DefaultSiteCulture + "'");
        if (cultureDRs.Length <= 0)
        {
            throw new Exception("[ReloadData]: Default site culture '" + DefaultSiteCulture + "' is not assigned to the current site.");
        }

        DataRow defaultCultureRow = cultureDRs[0];

        DataRow dr = documents.NewRow();

        dr.ItemArray = defaultCultureRow.ItemArray;
        documents.Rows.InsertAt(dr, 0);
        documents.Rows.Remove(defaultCultureRow);

        // Get last modification date of default culture
        defaultCultureRow       = documents.Select("DocumentCulture='" + DefaultSiteCulture + "'")[0];
        defaultLastModification = ValidationHelper.GetDateTime(defaultCultureRow["DocumentModifiedWhen"], DateTimeHelper.ZERO_TIME);
        defaultLastPublished    = ValidationHelper.GetDateTime(defaultCultureRow["DocumentLastPublished"], DateTimeHelper.ZERO_TIME);

        // Add column containing translation status
        documents.Columns.Add("TranslationStatus", typeof(TranslationStatusEnum));

        // Get proper translation status and store it to datatable
        foreach (DataRow document in documents.Rows)
        {
            TranslationStatusEnum status;
            int documentId = ValidationHelper.GetInteger(document["DocumentID"], 0);
            if (documentId == 0)
            {
                status = TranslationStatusEnum.NotAvailable;
            }
            else
            {
                string versionNumber = DataHelper.GetStringValue(document, "DocumentLastVersionNumber", null);

                if (ValidationHelper.GetBoolean(document["DocumentIsWaitingForTranslation"], false))
                {
                    status = TranslationStatusEnum.WaitingForTranslation;
                }
                else
                {
                    DateTime lastModification;

                    // Check if document is outdated
                    if (versionNumber != null)
                    {
                        lastModification = ValidationHelper.GetDateTime(document["DocumentLastPublished"], DateTimeHelper.ZERO_TIME);
                        status           = (lastModification < defaultLastPublished) ? TranslationStatusEnum.Outdated : TranslationStatusEnum.Translated;
                    }
                    else
                    {
                        lastModification = ValidationHelper.GetDateTime(document["DocumentModifiedWhen"], DateTimeHelper.ZERO_TIME);
                        status           = (lastModification < defaultLastModification) ? TranslationStatusEnum.Outdated : TranslationStatusEnum.Translated;
                    }
                }
            }
            document["TranslationStatus"] = status;
        }

        // Bind datasource
        DataSet filteredDocuments = data.Clone();

        DataRow[] filteredDocs = documents.Select(gridLanguages.GetFilter());

        foreach (DataRow row in filteredDocs)
        {
            filteredDocuments.Tables[0].ImportRow(row);
        }

        return(filteredDocuments);
    }
 private int GetNumberOfCurrentSiteCultures()
 {
     return(CultureSiteInfoProvider.GetSiteCultures(SiteContext.CurrentSiteName).Tables[0].Rows.Count);
 }
    /// <summary>
    /// Handles the Load event of the Page control.
    /// </summary>
    protected void Page_Load(object sender, EventArgs e)
    {
        string preferredCultureCode            = LocalizationContext.PreferredCultureCode;
        InfoDataSet <CultureInfo> siteCultures = CultureSiteInfoProvider.GetSiteCultures(SiteContext.CurrentSiteName);

        pi = DocumentContext.CurrentPageInfo ?? DocumentContext.CurrentCultureInvariantPageInfo ?? new PageInfo();

        // Cultures button
        MenuItem cultureItem = new MenuItem();

        cultureItem.CssClass     = "BigButton";
        cultureItem.ImageAlign   = ImageAlign.Top;
        cultureItem.ImagePath    = URLHelper.UnResolveUrl(UIHelper.GetFlagIconUrl(Page, preferredCultureCode, "16x16"), SystemContext.ApplicationPath);
        cultureItem.Text         = GetString("general.cultures");
        cultureItem.Tooltip      = GetString("onsiteedit.languageselector");
        cultureItem.ImageAltText = GetString("general.cultures");

        // Add all cultures to the sub menu
        foreach (CultureInfo culture in siteCultures)
        {
            string iconUrl     = UIHelper.GetFlagIconUrl(Page, culture.CultureCode, "16x16");
            string cultureName = culture.CultureName;
            string cultureCode = culture.CultureCode;

            if (cultureCode != preferredCultureCode)
            {
                SubMenuItem menuItem = new SubMenuItem
                {
                    Text         = cultureName,
                    Tooltip      = cultureName,
                    ImagePath    = iconUrl,
                    ImageAltText = cultureName
                };

                // Build the web part image html
                bool translationExists = NodeCultures.ContainsKey(cultureCode);

                if (translationExists)
                {
                    // Assign click action which changes the document culture
                    menuItem.OnClientClick = "document.location.replace(" + ScriptHelper.GetString(URLHelper.UpdateParameterInUrl(RequestContext.CurrentURL, URLHelper.LanguageParameterName, cultureCode)) + ");";
                }
                else
                {
                    // Display the "Not translated" image
                    menuItem.RightImageIconClass = "icon-ban-sign";
                    menuItem.RightImageAltText   = GetString("onsitedit.culturenotavailable");

                    // Assign click action -> Create new document culture
                    menuItem.OnClientClick = "NewDocumentCulture(" + pi.NodeID + ",'" + cultureCode + "');";
                }

                cultureItem.SubItems.Add(menuItem);
            }
            else
            {
                // Current culture
                cultureItem.Text         = culture.CultureShortName;
                cultureItem.Tooltip      = cultureName;
                cultureItem.ImagePath    = iconUrl;
                cultureItem.ImageAltText = cultureName;
            }
        }

        btnCulture.Buttons.Add(cultureItem);
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        // Register main CMS script file
        ScriptHelper.RegisterCMS(this);

        if (QueryHelper.ValidateHash("hash") && (Parameters != null))
        {
            // Initialize current user
            currentUser = MembershipContext.AuthenticatedUser;

            // Check permissions
            if (!currentUser.CheckPrivilegeLevel(UserPrivilegeLevelEnum.Admin) &&
                !currentUser.IsAuthorizedPerResource("CMS.Content", "manageworkflow"))
            {
                RedirectToAccessDenied("CMS.Content", "manageworkflow");
            }

            // Set current UI culture
            currentCulture = CultureHelper.PreferredUICultureCode;

            // Initialize current site
            currentSiteName = SiteContext.CurrentSiteName;
            currentSiteId   = SiteContext.CurrentSiteID;

            // Initialize events
            ctlAsyncLog.OnFinished += ctlAsyncLog_OnFinished;
            ctlAsyncLog.OnError    += ctlAsyncLog_OnError;
            ctlAsyncLog.OnCancel   += ctlAsyncLog_OnCancel;

            if (!RequestHelper.IsCallback())
            {
                DataSet      allDocs = null;
                TreeProvider tree    = new TreeProvider(currentUser);

                // Current Node ID to delete
                string parentAliasPath = ValidationHelper.GetString(Parameters["parentaliaspath"], string.Empty);
                if (string.IsNullOrEmpty(parentAliasPath))
                {
                    // Get IDs of nodes
                    string   nodeIdsString = ValidationHelper.GetString(Parameters["nodeids"], string.Empty);
                    string[] nodeIdsArr    = nodeIdsString.Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
                    foreach (string nodeId in nodeIdsArr)
                    {
                        int id = ValidationHelper.GetInteger(nodeId, 0);
                        if (id != 0)
                        {
                            nodeIds.Add(id);
                        }
                    }
                }
                else
                {
                    var where = new WhereCondition(WhereCondition)
                                .WhereNotEquals("ClassName", SystemDocumentTypes.Root);
                    string columns = SqlHelper.MergeColumns(DocumentColumnLists.SELECTNODES_REQUIRED_COLUMNS,
                                                            "NodeParentID, DocumentName,DocumentCheckedOutByUserID");
                    allDocs = tree.SelectNodes(currentSiteName, parentAliasPath.TrimEnd('/') + "/%",
                                               TreeProvider.ALL_CULTURES, true, DataClassInfoProvider.GetClassName(ClassID), where.ToString(true), "DocumentName", 1, false, 0,
                                               columns);

                    if (!DataHelper.DataSourceIsEmpty(allDocs))
                    {
                        foreach (DataRow row in allDocs.Tables[0].Rows)
                        {
                            nodeIds.Add(ValidationHelper.GetInteger(row["NodeID"], 0));
                        }
                    }
                }

                // Initialize strings based on current action
                string titleText = null;

                switch (CurrentAction)
                {
                case WorkflowAction.Archive:
                    headQuestion.ResourceString   = "content.archivequestion";
                    chkAllCultures.ResourceString = "content.archiveallcultures";
                    chkUnderlying.ResourceString  = "content.archiveunderlying";
                    canceledString = GetString("content.archivecanceled");

                    // Setup title of log
                    ctlAsyncLog.TitleText = GetString("content.archivingdocuments");
                    // Setup page title text and image
                    titleText = GetString("Content.ArchiveTitle");
                    break;

                case WorkflowAction.Publish:
                    headQuestion.ResourceString   = "content.publishquestion";
                    chkAllCultures.ResourceString = "content.publishallcultures";
                    chkUnderlying.ResourceString  = "content.publishunderlying";
                    canceledString = GetString("content.publishcanceled");

                    // Setup title of log
                    ctlAsyncLog.TitleText = GetString("content.publishingdocuments");
                    // Setup page title text and image
                    titleText = GetString("Content.PublishTitle");
                    break;
                }

                PageTitle.TitleText = titleText;
                EnsureDocumentBreadcrumbs(PageBreadcrumbs, action: PageTitle.TitleText);

                if (nodeIds.Count == 0)
                {
                    // Hide if no node was specified
                    pnlContent.Visible = false;
                    return;
                }

                // Register the dialog script
                ScriptHelper.RegisterDialogScript(this);

                // Set visibility of panels
                pnlContent.Visible = true;
                pnlLog.Visible     = false;

                // Set all cultures checkbox
                DataSet culturesDS = CultureSiteInfoProvider.GetSiteCultures(currentSiteName);
                if ((DataHelper.DataSourceIsEmpty(culturesDS)) || (culturesDS.Tables[0].Rows.Count <= 1))
                {
                    chkAllCultures.Checked = true;
                    plcAllCultures.Visible = false;
                }

                if (nodeIds.Count > 0)
                {
                    pnlDocList.Visible = true;

                    // Create where condition
                    string where = new WhereCondition().WhereIn("NodeID", nodeIds).ToString(true);
                    string columns = SqlHelper.MergeColumns(DocumentColumnLists.SELECTNODES_REQUIRED_COLUMNS, "NodeParentID, DocumentName,DocumentCheckedOutByUserID");

                    // Select nodes
                    DataSet ds = allDocs ?? tree.SelectNodes(currentSiteName, "/%", TreeProvider.ALL_CULTURES, true, null, where, "DocumentName", TreeProvider.ALL_LEVELS, false, 0, columns);

                    // Enumerate selected documents
                    if (!DataHelper.DataSourceIsEmpty(ds))
                    {
                        cancelNodeId = DataHelper.GetIntValue(ds.Tables[0].Rows[0], "NodeParentID");

                        foreach (DataRow dr in ds.Tables[0].Rows)
                        {
                            AddToList(dr);
                        }

                        // Display enumeration of documents
                        foreach (KeyValuePair <int, string> line in list)
                        {
                            lblDocuments.Text += line.Value;
                        }
                    }
                }
            }

            // Set title for dialog mode
            string title = GetString("general.publish");

            if (CurrentAction == WorkflowAction.Archive)
            {
                title = GetString("general.archive");
            }

            SetTitle(title);
        }
        else
        {
            pnlPublish.Visible = false;
            ShowError(GetString("dialogs.badhashtext"));
        }
    }