Exemplo n.º 1
0
    public override bool LoadData(ActivityInfo ai)
    {
        if ((ai == null) || (ai.ActivityType != PredefinedActivityType.NEWSLETTER_OPEN))
        {
            return(false);
        }

        // Get newsletter name
        int            newsletterId   = ai.ActivityItemID;
        NewsletterInfo newsletterInfo = NewsletterInfoProvider.GetNewsletterInfo(newsletterId);

        if (newsletterInfo != null)
        {
            string subject = ValidationHelper.GetString(newsletterInfo.NewsletterDisplayName, null);
            ucDetails.AddRow("om.activitydetails.newsletter", subject);
        }

        // Get issue subject
        int       issueId   = ai.ActivityItemDetailID;
        IssueInfo issueInfo = IssueInfoProvider.GetIssueInfo(issueId);

        if (issueInfo != null)
        {
            string subject = ValidationHelper.GetString(issueInfo.IssueSubject, null);
            ucDetails.AddRow("om.activitydetails.newsletterissue", MacroSecurityProcessor.RemoveSecurityParameters(subject, true, null));
        }

        return(ucDetails.IsDataLoaded);
    }
    private static MacroExpr GetMacroExpr(string originalExpression, string processedExpression)
    {
        var macroExpr = new MacroExpr();

        try
        {
            // Handle security
            macroExpr.Expression     = MacroSecurityProcessor.RemoveMacroSecurityParams(originalExpression, out macroExpr.SignedBy);
            macroExpr.SignatureValid = MacroSecurityProcessor.CheckMacroIntegrity(originalExpression, macroExpr.SignedBy);

            // Parse rule text
            macroExpr.RuleText   = MacroRuleTree.GetRuleText(macroExpr.Expression, true, true);
            macroExpr.Expression = MacroRuleTree.GetRuleCondition(macroExpr.Expression, true);

            // Macro expression does not support anonymous signature, remove the flag
            if (processedExpression.EndsWith("@", StringComparison.Ordinal))
            {
                processedExpression = processedExpression.Substring(0, processedExpression.Length - 1);
            }

            // Check syntax
            MacroExpression.ParseExpression(processedExpression);
        }
        catch (Exception ex)
        {
            macroExpr.Error        = true;
            macroExpr.ErrorMessage = ex.Message + "\r\n\r\n" + ex.StackTrace;
        }
        return(macroExpr);
    }
Exemplo n.º 3
0
    /// <summary>
    /// Removes the macro signatures from the input text
    /// </summary>
    /// <param name="input">Input text</param>
    private static string RemoveMacroSignatures(string input)
    {
        if (!string.IsNullOrEmpty(input) && QueryHelper.GetBoolean("processMacroSecurity", false))
        {
            bool containsMacro;

            var valueIsMacro = QueryHelper.GetBoolean("valueIsMacro", false);

            // If value is macro, convert to full macro expression
            if (valueIsMacro)
            {
                input         = "{%" + input + "%}";
                containsMacro = true;
            }
            else
            {
                containsMacro = input.Contains("{");
            }

            // Remove the signatures
            if (containsMacro)
            {
                input = MacroSecurityProcessor.RemoveSecurityParameters(input, true, null);
            }

            // If value is macro, trim back the full expression
            if (valueIsMacro)
            {
                input = input.Substring(2, input.Length - 4);
            }
        }

        return(input);
    }
    public override bool LoadData(ActivityInfo ai)
    {
        if ((ai == null) || (ai.ActivityType != PredefinedActivityType.NEWSLETTER_UNSUBSCRIBING_FROM_ALL))
        {
            return(false);
        }

        // Get issue subject
        int issueId   = ai.ActivityItemID;
        var issueInfo = IssueInfoProvider.GetIssueInfo(issueId);

        if (issueInfo != null)
        {
            // Get newsletter name
            var newsletterInfo = NewsletterInfoProvider.GetNewsletterInfo(issueInfo.IssueNewsletterID);
            if (newsletterInfo != null)
            {
                ucDetails.AddRow("om.activitydetails.newsletter", newsletterInfo.NewsletterDisplayName);
            }

            var issueSubject = MacroSecurityProcessor.RemoveSecurityParameters(issueInfo.IssueSubject, true, null);
            ucDetails.AddRow("om.activitydetails.newsletterissue", issueSubject);
        }

        return(ucDetails.IsDataLoaded);
    }
        private string GetFormConsentMacroRule()
        {
            var rule = $@"{{%Rule(""(Contact.AgreedWithConsent(""{FormConsentGenerator.CONSENT_NAME}""))"", "" <rules><r pos =\""0\"" par=\""\"" op=\""and\"" n=\""CMSContactHasAgreedWithConsent\"" >
                        <p n=\""consent\""><t>{FormConsentGenerator.CONSENT_DISPLAY_NAME}</t><v>{FormConsentGenerator.CONSENT_NAME}</v><r>0</r><d>select consent</d><vt>text</vt><tv>0</tv></p>
                        <p n=\""_perfectum\""><t>has</t><v></v><r>0</r><d>select operation</d><vt>text</vt><tv>0</tv></p></r></rules>"")%}}";

            return(MacroSecurityProcessor.AddSecurityParameters(rule, MacroIdentityOption.FromUserInfo(UserInfoProvider.AdministratorUser), null));
        }
Exemplo n.º 6
0
    private void RefreshText()
    {
        string hdnValueTrim = hdnValue.Value.Trim();

        if (hdnValueTrim.StartsWithCSafe("rule(", true))
        {
            // Empty rule designer condition is not considered as rule conditions
            if (hdnValueTrim.EqualsCSafe("Rule(\"\", \"<rules></rules>\")", true))
            {
                hdnValue.Value = "";
            }
            else
            {
                try
                {
                    string ruleText = MacroRuleTree.GetRuleText(hdnValueTrim, true, true, TimeZoneTransformation);

                    // Display rule text
                    ltlMacro.Text    = ruleText;
                    txtMacro.Visible = false;
                    pnlRule.Visible  = true;

                    pnlUpdate.Update();

                    return;
                }
                catch
                {
                    // If failed to parse the rule, extract the condition
                    MacroExpression xml = MacroExpression.ExtractParameter(hdnValueTrim, "rule", 0);
                    if (xml != null)
                    {
                        string user;
                        hdnValue.Value = MacroSecurityProcessor.RemoveMacroSecurityParams(ValidationHelper.GetString(xml.Value, ""), out user);
                    }
                }
            }
        }


        if (string.IsNullOrEmpty(hdnValue.Value) && !string.IsNullOrEmpty(DefaultConditionText))
        {
            ltlMacro.Text    = DefaultConditionText;
            txtMacro.Text    = "";
            txtMacro.Visible = false;
            pnlRule.Visible  = true;
        }
        else
        {
            txtMacro.Text    = hdnValue.Value;
            hdnValue.Value   = null;
            txtMacro.Visible = true;
            pnlRule.Visible  = false;
        }

        pnlUpdate.Update();
    }
Exemplo n.º 7
0
    /// <summary>
    /// Creates new or updates existing newsletter issue.
    /// </summary>
    public bool Save()
    {
        if (validated || IsValid())
        {
            IssueInfo issue = null;

            if (IssueID == 0)
            {
                // Initialize new issue
                issue = new IssueInfo();
                issue.IssueUnsubscribed = 0;
                issue.IssueSentEmails   = 0;
                issue.IssueNewsletterID = NewsletterID;
                issue.IssueSiteID       = SiteContext.CurrentSiteID;
            }
            else
            {
                issue = IssueInfoProvider.GetIssueInfo(IssueID);
            }

            if (issue != null)
            {
                issue.IssueTemplateID = TemplateID;
                issue.IssueShowInNewsletterArchive = chkShowInArchive.Checked;
                issue.IssueSenderName  = txtSenderName.Text.Trim();
                issue.IssueSenderEmail = txtSenderEmail.Text.Trim();

                // Saves content of editable region(s)
                // Get content from hidden field
                string   content = hdnIssueContent.Value;
                string[] regions = null;
                if (!string.IsNullOrEmpty(content))
                {
                    // Split content for each region, separator is '#|#'
                    regions = content.Split(new string[] { "#|#" }, StringSplitOptions.RemoveEmptyEntries);
                }
                issue.IssueText = IssueHelper.GetContentXML(regions);

                // Remove '#' from macros if included
                txtSubject.Text = txtSubject.Text.Trim().Replace("#%}", "%}");

                // Sign macros if included in the subject
                issue.IssueSubject = MacroSecurityProcessor.AddSecurityParameters(txtSubject.Text, MembershipContext.AuthenticatedUser.UserName, null);

                // Save issue
                IssueInfoProvider.SetIssueInfo(issue);

                // Update IssueID
                IssueID = issue.IssueID;

                return(true);
            }
        }

        return(false);
    }
Exemplo n.º 8
0
    /// <summary>
    /// Handles the UniGrid's OnExternalDataBound event.
    /// </summary>
    /// <param name="sender">The sender</param>
    /// <param name="sourceName">Name of the source</param>
    /// <param name="parameter">The data row</param>
    /// <returns>Formatted value to be used in the UniGrid</returns>
    protected object UniGrid_OnExternalDataBound(object sender, string sourceName, object parameter)
    {
        switch (sourceName.ToLowerCSafe())
        {
        case "issuesubject":
            return(HTMLHelper.HTMLEncode(MacroSecurityProcessor.RemoveSecurityParameters(parameter.ToString(), true, null)));

        case "issueopenedemails":
            return(GetOpenedEmails(parameter as DataRowView));

        case "issuestatus":
            IssueStatusEnum status = IssueStatusEnum.Idle;
            if ((parameter != DBNull.Value) && (parameter != null))
            {
                status = (IssueStatusEnum)parameter;
            }
            return(GetString(String.Format("newsletterissuestatus." + Convert.ToString(status))));

        case "viewclickedlinks":
            if (sender is CMSGridActionButton)
            {
                // Hide 'view clicked links' action if tracking is not available or if the issue has no tracked links
                CMSGridActionButton imageButton = sender as CMSGridActionButton;
                if (!mTrackingEnabled)
                {
                    imageButton.Visible = false;
                }
                else
                {
                    GridViewRow gvr = parameter as GridViewRow;
                    if (gvr != null)
                    {
                        DataRowView drv = gvr.DataItem as DataRowView;
                        if (drv != null)
                        {
                            int issueId = ValidationHelper.GetInteger(drv["IssueID"], 0);
                            // Try to get one tracked link (only ID) of the issue
                            var links = LinkInfoProvider.GetLinks().WhereEquals("LinkIssueID", issueId).TopN(1).Column("LinkID");
                            if (!links.Any())
                            {
                                imageButton.Visible = false;
                            }
                        }
                    }
                }
            }
            return(sender);

        default:
            return(parameter);
        }
    }
    /// <summary>
    /// Returns a subject of an issue. A/B test icon is added to the subject if the issue is an A/B test.
    /// </summary>
    /// <param name="rowView">A <see cref="DataRowView" /> that represents one row from UniGrid's source</param>
    private string GetIssueSubject(DataRowView rowView)
    {
        var isABTest = DataHelper.GetBoolValue(rowView.Row, "IssueIsABTest");
        var subject  = HTMLHelper.HTMLEncode(MacroSecurityProcessor.RemoveSecurityParameters(DataHelper.GetStringValue(rowView.Row, "IssueSubject"), true, null));

        // Add the icon for A/B tests
        if (isABTest)
        {
            subject += UIHelper.GetAccessibleIconTag("NodeLink icon-two-squares-line tn", GetString("unigrid.newsletter_issue.abtesticontooltip"));
        }

        return(subject);
    }
Exemplo n.º 10
0
    /// <summary>
    /// Creates new or updates existing newsletter issue.
    /// </summary>
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        if (IsValid())
        {
            IssueInfo issue = IssueInfoProvider.GetIssueInfo(IssueID);
            if ((issue != null) && Enabled)
            {
                if (IsDisplayNameFieldEnabled(issue))
                {
                    issue.IssueDisplayName = txtDisplayName.Text.Trim();
                }

                issue.IssueTemplateID  = TemplateID;
                issue.IssueSenderName  = txtSenderName.Text.Trim();
                issue.IssueSenderEmail = txtSenderEmail.Text.Trim();
                issue.IssuePreheader   = txtPreheader.Text.Trim();
                issue.IssueUseUTM      = chkIssueUseUTM.Checked;
                issue.IssueUTMSource   = Normalize(txtIssueUTMSource.Text.Trim());

                if (radUTMCampaignNew.Checked)
                {
                    var normalizedUtmCampaign = Normalize(mUTMCampaignTextBox.Text.Trim());
                    if (string.IsNullOrEmpty(normalizedUtmCampaign))
                    {
                        normalizedUtmCampaign = Normalize(Newsletter.NewsletterName);
                    }
                    mUTMCampaignTextBox.Text = issue.IssueUTMCampaign = normalizedUtmCampaign;
                }
                else
                {
                    issue.IssueUTMCampaign = selectorUTMCampaign.Value.ToString().ToLower(CultureInfo.CurrentCulture);
                }

                PostProcessVariants(issue);

                // Remove '#' from macros if included
                txtSubject.Text = txtSubject.Text.Trim().Replace("#%}", "%}");

                // Sign macros if included in the subject
                issue.IssueSubject = MacroSecurityProcessor.AddSecurityParameters(txtSubject.Text, MacroIdentityOption.FromUserInfo(MembershipContext.AuthenticatedUser), null);

                // Save issue
                IssueInfoProvider.SetIssueInfo(issue);

                // Update IssueID
                IssueID = issue.IssueID;

                OnSave(new EmailBuilderEventArgs(NewsletterID, IssueID));
            }
        }
    }
    /// <summary>
    /// Refreshes macro signatures in all object which can contain macros.
    /// </summary>
    private static void RefreshMacroSignatures()
    {
        // Get object types
        var objectTypes = new List <string> {
            TransformationInfo.OBJECT_TYPE,
            UIElementInfo.OBJECT_TYPE,
            FormUserControlInfo.OBJECT_TYPE,
            SettingsKeyInfo.OBJECT_TYPE,
            AlternativeFormInfo.OBJECT_TYPE,
            DataClassInfo.OBJECT_TYPE,
            DataClassInfo.OBJECT_TYPE_SYSTEMTABLE,
            DataClassInfo.OBJECT_TYPE_CUSTOMTABLE,
            DataClassInfo.OBJECT_TYPE_DOCUMENTTYPE,
            PageTemplateInfo.OBJECT_TYPE,
            LayoutInfo.OBJECT_TYPE,
            CssStylesheetInfo.OBJECT_TYPE,
            WorkflowActionInfo.OBJECT_TYPE,
        };

        foreach (string type in objectTypes)
        {
            try
            {
                using (var context = new CMSActionContext())
                {
                    context.DisableLogging();
                    context.CreateVersion  = false;
                    context.LogIntegration = false;

                    var infos = new InfoObjectCollection(type);
                    foreach (var info in infos)
                    {
                        MacroSecurityProcessor.RefreshSecurityParameters(info, "administrator", true);
                    }
                }
            }
            catch (Exception ex)
            {
                EventLogProvider.LogException(EventLogSource, "REFRESHMACROSIGNATURES", ex, 0, "Type: " + type);
            }
        }
    }
Exemplo n.º 12
0
        private void GenerateBannerPersonalizationVariantsMacrosAndEnableVariants()
        {
            var personalizationVariant1 =
                ContentPersonalizationVariantInfoProvider.GetContentPersonalizationVariant(
                    "TheCafeOwnerBannerVariant_dd20f145-3779-4748-9bc8-d383eecfbd15");
            var personalizationVariant2 =
                ContentPersonalizationVariantInfoProvider.GetContentPersonalizationVariant(
                    "TheCoffeeGeekBannerVariant_d862b458-e5a5-432f-a3fe-60f495acad9f");

            if (personalizationVariant1 == null || personalizationVariant2 == null ||
                personalizationVariant1.VariantEnabled || personalizationVariant2.VariantEnabled ||
                personalizationVariant1.VariantDisplayCondition != "{%// Macro will be added by generator%}" ||
                personalizationVariant2.VariantDisplayCondition != "{%// Macro will be added by generator%}")
            {
                return;
            }

            var personaInfoByCodeName1 = PersonaInfoProvider.GetPersonaInfoByCodeName(PERSONA_CAFE_OWNER);
            var personaInfoByCodeName2 = PersonaInfoProvider.GetPersonaInfoByCodeName(PERSONA_COFEE_GEEK);

            if (personaInfoByCodeName1 == null || personaInfoByCodeName2 == null)
            {
                return;
            }

            var identityOption = MacroIdentityOption.FromUserInfo(UserInfoProvider.AdministratorUser);

            personalizationVariant1.VariantDisplayCondition = MacroSecurityProcessor.AddSecurityParameters(
                string.Format(
                    "{{%Rule(\"(Contact.IsInPersona(\\\"{0}\\\"))\", \"<rules><r pos=\\\"0\\\" par=\\\"\\\" op=\\\"and\\\" n=\\\"ContactIsInPersona\\\" ><p n=\\\"_is\\\"><t>is</t><v></v><r>0</r><d>select operation</d><vt>text</vt><tv>0</tv></p><p n=\\\"personaguid\\\"><t>{1}</t><v>{0}</v><r>1</r><d>select persona</d><vt>text</vt><tv>0</tv></p></r></rules>\")%}}",
                    personaInfoByCodeName1.PersonaGUID, personaInfoByCodeName1.PersonaDisplayName),
                identityOption, null);
            personalizationVariant2.VariantDisplayCondition = MacroSecurityProcessor.AddSecurityParameters(
                string.Format(
                    "{{%Rule(\"(Contact.IsInPersona(\\\"{0}\\\"))\", \"<rules><r pos=\\\"0\\\" par=\\\"\\\" op=\\\"and\\\" n=\\\"ContactIsInPersona\\\" ><p n=\\\"_is\\\"><t>is</t><v></v><r>0</r><d>select operation</d><vt>text</vt><tv>0</tv></p><p n=\\\"personaguid\\\"><t>{1}</t><v>{0}</v><r>1</r><d>select persona</d><vt>text</vt><tv>0</tv></p></r></rules>\")%}}",
                    personaInfoByCodeName2.PersonaGUID, personaInfoByCodeName2.PersonaDisplayName),
                identityOption, null);
            personalizationVariant1.VariantEnabled = true;
            personalizationVariant2.VariantEnabled = true;
            ContentPersonalizationVariantInfoProvider.SetContentPersonalizationVariant(personalizationVariant1);
            ContentPersonalizationVariantInfoProvider.SetContentPersonalizationVariant(personalizationVariant2);
        }
Exemplo n.º 13
0
    protected object gridStrings_OnExternalDataBound(object sender, string sourceName, object parameter)
    {
        switch (sourceName.ToLowerInvariant())
        {
        case "culturetext":
        case "defaulttext":
        {
            var text = ValidationHelper.GetString(parameter, String.Empty);

            if (text.IndexOf('{') >= 0)
            {
                text = MacroSecurityProcessor.RemoveSecurityParameters(text, true, null);
            }

            return(text);
        }
        }

        return(parameter);
    }
Exemplo n.º 14
0
    /// <summary>
    /// Refreshes macro signatures in all object which can contain macros.
    /// </summary>
    private static void RefreshMacroSignatures()
    {
        // Get object types
        var objectTypes = new List <string> {
            TransformationInfo.OBJECT_TYPE,
            UIElementInfo.OBJECT_TYPE,
            FormUserControlInfo.OBJECT_TYPE,
            SettingsKeyInfo.OBJECT_TYPE,
            AlternativeFormInfo.OBJECT_TYPE,
            DataClassInfo.OBJECT_TYPE, // Process all data classes just through general object type to avoid duplicities
            PageTemplateInfo.OBJECT_TYPE,
            LayoutInfo.OBJECT_TYPE,
            CssStylesheetInfo.OBJECT_TYPE,
            WorkflowActionInfo.OBJECT_TYPE,
        };

        var adminIdentityOption = MacroIdentityOption.FromUserInfo(UserInfoProvider.AdministratorUser);

        foreach (string type in objectTypes)
        {
            try
            {
                using (var context = new CMSActionContext())
                {
                    context.DisableLogging();
                    context.CreateVersion  = false;
                    context.LogIntegration = false;

                    var infos = new InfoObjectCollection(type);
                    foreach (var info in infos)
                    {
                        MacroSecurityProcessor.RefreshSecurityParameters(info, adminIdentityOption, true);
                    }
                }
            }
            catch (Exception ex)
            {
                EventLogProvider.LogException(EventLogSource, "REFRESHMACROSIGNATURES", ex, 0, "Type: " + type);
            }
        }
    }
    /// <summary>
    /// Loads data from textboxes and store them to data collection
    /// </summary>
    private void LoadData()
    {
        data.Clear();
        var authenticatedUserIdentityOption = MacroIdentityOption.FromUserInfo(MembershipContext.AuthenticatedUser);

        foreach (String key in Request.Form.AllKeys)
        {
            if ((key != null) && key.StartsWithCSafe(UniqueID + "$tk"))
            {
                String value = Request.Form[key.Replace(UniqueID + "$tk", UniqueID + "$tv")];

                // Sign the macro
                value = MacroSecurityProcessor.AddSecurityParameters(value, authenticatedUserIdentityOption, null);
                String k = Request.Form[key];
                if (!IsValidKey(k))
                {
                    invalidKey = k;
                    k          = INVALIDTOKEN;
                }

                data.SetValue(k, value);
            }
        }

        // Add data from new field
        String newValue = Request.Form[UniqueID + "$utv_newvalue"];
        String newKey   = Request.Form[UniqueID + "$utk_newkey"];

        if (!String.IsNullOrEmpty(newValue) || !String.IsNullOrEmpty(newKey))
        {
            if (!IsValidKey(newKey))
            {
                isNewValid = false;
                return;
            }

            // Sign the macro
            newValue = MacroSecurityProcessor.AddSecurityParameters(newValue, authenticatedUserIdentityOption, null);
            data.SetValue(newKey, newValue);
        }
    }
Exemplo n.º 16
0
    /// <summary>
    /// Gets the macro expression from the given object
    /// </summary>
    /// <param name="expression">Expression</param>
    private static MacroExpr GetMacroExpr(string expression)
    {
        var macroExpr = new MacroExpr();

        try
        {
            // Handle security
            macroExpr.Expression     = MacroSecurityProcessor.RemoveMacroSecurityParams(expression, out macroExpr.SignedBy);
            macroExpr.SignatureValid = MacroSecurityProcessor.CheckMacroIntegrity(expression, macroExpr.SignedBy);

            // Parse rule text
            macroExpr.RuleText   = MacroRuleTree.GetRuleText(macroExpr.Expression, true, true);
            macroExpr.Expression = MacroRuleTree.GetRuleCondition(macroExpr.Expression, true);
        }
        catch (Exception ex)
        {
            macroExpr.Error        = true;
            macroExpr.ErrorMessage = ex.Message + "\r\n\r\n" + ex.StackTrace;
        }
        return(macroExpr);
    }
Exemplo n.º 17
0
    public override bool LoadData(ActivityInfo ai)
    {
        if (ai == null)
        {
            return(false);
        }

        switch (ai.ActivityType)
        {
        case PredefinedActivityType.NEWSLETTER_SUBSCRIBING:
        case PredefinedActivityType.NEWSLETTER_UNSUBSCRIBING:
            break;

        default:
            return(false);
        }

        // Get newsletter name
        NewsletterInfo newsletterInfo = NewsletterInfoProvider.GetNewsletterInfo(ai.ActivityItemID);

        if (newsletterInfo != null)
        {
            string subject = ValidationHelper.GetString(newsletterInfo.NewsletterDisplayName, null);
            ucDetails.AddRow("om.activitydetails.newsletter", subject);
        }

        // Get issue subject only for unsubscribing activity. Subscribing activity has reference to the subscriber in ItemDetailID.
        if (ai.ActivityType == PredefinedActivityType.NEWSLETTER_UNSUBSCRIBING)
        {
            IssueInfo issueInfo = IssueInfoProvider.GetIssueInfo(ai.ActivityItemDetailID);
            if (issueInfo != null)
            {
                string subject = ValidationHelper.GetString(issueInfo.IssueSubject, null);
                ucDetails.AddRow("om.activitydetails.newsletterissue", MacroSecurityProcessor.RemoveSecurityParameters(subject, true, null));
            }
        }

        return(ucDetails.IsDataLoaded);
    }
    /// <summary>
    /// Extracts the condition from Rule method.
    /// </summary>
    public string ConditionFromExpression(string expression)
    {
        MacroExpression xml = null;

        try
        {
            xml = MacroExpression.ExtractParameter(expression, "rule", 1);
        }
        catch
        {
        }

        MacroIdentityOption identityOption;

        if (xml == null)
        {
            return(MacroSecurityProcessor.RemoveMacroSecurityParams(expression, out identityOption));
        }

        // Returns first parameter of the expression
        return(MacroSecurityProcessor.RemoveMacroSecurityParams(ValidationHelper.GetString(xml.Value, ""), out identityOption));
    }
Exemplo n.º 19
0
        private static ContactGroupInfo CreateContactGroup(PersonaInfo persona)
        {
            var contactGroupInfo = ContactGroupInfoProvider.GetContactGroupInfo(CoffeeGeekPersonaContactGroupName);

            if (contactGroupInfo != null)
            {
                ContactGroupInfoProvider.DeleteContactGroupInfo(contactGroupInfo);
            }

            var groupObj = new ContactGroupInfo();

            groupObj.ContactGroupDisplayName = "Is in persona 'Martina, the Coffee Geek'";
            groupObj.ContactGroupName        = CoffeeGeekPersonaContactGroupName;
            groupObj.ContactGroupEnabled     = true;
            var str = MacroSecurityProcessor.AddSecurityParameters(
                string.Format(
                    "{{%Rule(\"(Contact.IsInPersona(\\\"{0}\\\"))\", \"<rules><r pos=\\\"0\\\" par=\\\"\\\" op=\\\"and\\\" n=\\\"ContactIsInPersona\\\" ><p n=\\\"_is\\\"><t>is</t><v></v><r>0</r><d>select operation</d><vt>text</vt><tv>0</tv></p><p n=\\\"personaguid\\\"><t>{1}</t><v>{0}</v><r>1</r><d>select persona</d><vt>text</vt><tv>0</tv></p></r></rules>\") %}}",
                    persona.PersonaGUID, persona.PersonaDisplayName),
                MacroIdentityOption.FromUserInfo(UserInfoProvider.AdministratorUser), null);

            groupObj.ContactGroupDynamicCondition = str;
            ContactGroupInfoProvider.SetContactGroupInfo(groupObj);
            return(groupObj);
        }
    protected void drpTransformationType_SelectedIndexChanged(object sender, EventArgs e)
    {
        // Get the current code
        string code = TransformationCode;

        switch (TransformationType)
        {
        case TransformationTypeEnum.Ascx:

            if (!AscxEditAllowed)
            {
                // Ignore type change and reset transformation type selector
                drpType.SelectedValue = transformationInfo.TransformationType.ToStringRepresentation();
                ShowWarning(GetString("EditCode.NotAllowed"));
                break;
            }

            // Convert to ASCX syntax
            code = MacroSecurityProcessor.RemoveSecurityParameters(code, false, null);
            code = code.Replace("{% Register", "<%@ Register").Replace("{%", "<%#").Replace("%}", "%>");
            ShowMessage();
            break;

        case TransformationTypeEnum.Xslt:
            // No transformation
            break;

        default:
            // Convert to macro syntax
            code = code.Replace("<%@", "{%").Replace("<%#", "{%").Replace("<%=", "{%").Replace("<%", "{%").Replace("%>", "%}");
            break;
        }

        // Move the content if necessary
        if (TransformationType == TransformationTypeEnum.Html)
        {
            // Move from text to WYSIWYG
            if (txtCode.Visible)
            {
                tbWysiwyg.ResolvedValue = code;
                tbWysiwyg.Visible       = true;

                txtCode.Text    = string.Empty;
                txtCode.Visible = false;
            }
        }
        else
        {
            // Move from WYSIWYG to text
            if (tbWysiwyg.Visible)
            {
                code = HttpUtility.HtmlDecode(code);

                txtCode.Text    = code;
                txtCode.Visible = true;

                tbWysiwyg.ResolvedValue = string.Empty;
                tbWysiwyg.Visible       = false;
            }
            else
            {
                txtCode.Text = code;
            }
        }

        SetEditor();
    }
Exemplo n.º 21
0
    /// <summary>
    /// Refreshes the security parameters in macros for all the objects of the specified object types.
    /// Signs all the macros with the current user if the old salt is not specified.
    /// </summary>
    /// <param name="objectTypes">Object types</param>
    /// <param name="oldSalt">Old salt </param>
    /// <param name="newSalt">New salt</param>
    private void RefreshSecurityParams(IEnumerable <string> objectTypes, string oldSalt, string newSalt)
    {
        var oldSaltSpecified = !string.IsNullOrEmpty(oldSalt) && !chkRefreshAll.Checked;
        var newSaltSpecified = !string.IsNullOrEmpty(newSalt) && !chkUseCurrentSalt.Checked;

        processedObjects.Clear();

        using (CMSActionContext context = new CMSActionContext())
        {
            context.LogEvents          = false;
            context.LogSynchronization = false;

            foreach (var objectType in objectTypes)
            {
                var objectTypeResourceKey = TypeHelper.GetObjectTypeResourceKey(objectType);
                var niceObjectType        = GetString(objectTypeResourceKey);
                if (niceObjectType == objectTypeResourceKey)
                {
                    if (objectType.StartsWithCSafe("bizformitem.bizform.", true))
                    {
                        DataClassInfo dci = DataClassInfoProvider.GetDataClassInfo(objectType.Substring("bizformitem.".Length));
                        if (dci != null)
                        {
                            niceObjectType = "on-line form " + dci.ClassDisplayName;
                        }
                    }
                    else
                    {
                        niceObjectType = objectType;
                    }
                }

                LogContext.AppendLine(string.Format(GetString("macros.refreshsecurityparams.processing"), niceObjectType));

                try
                {
                    var infos = new InfoObjectCollection(objectType);

                    foreach (var info in infos)
                    {
                        try
                        {
                            bool refreshed = false;
                            if (oldSaltSpecified)
                            {
                                refreshed = MacroSecurityProcessor.RefreshSecurityParameters(info, oldSalt, newSaltSpecified ? newSalt : ValidationHelper.HashStringSalt, true);
                            }
                            else
                            {
                                if (chkRefreshAll.Checked && newSaltSpecified)
                                {
                                    // Do not check integrity, but use new salt
                                    refreshed = MacroSecurityProcessor.RefreshSecurityParameters(info, MembershipContext.AuthenticatedUser.UserName, true, newSalt);
                                }
                                else
                                {
                                    // Do not check integrity, sign everything with current user
                                    refreshed = MacroSecurityProcessor.RefreshSecurityParameters(info, MembershipContext.AuthenticatedUser.UserName, true);
                                }
                            }

                            if (refreshed)
                            {
                                var objectName = HTMLHelper.HTMLEncode(ResHelper.LocalizeString(info.Generalized.ObjectDisplayName));
                                processedObjects.Add(niceObjectType, objectName);
                            }
                        }
                        catch (Exception ex)
                        {
                            string message = "Signing " + TypeHelper.GetNiceObjectTypeName(info.TypeInfo.ObjectType) + " " + info.Generalized.ObjectDisplayName + " failed: " + ex.Message;
                            EventLogProvider.LogEvent(EventType.ERROR, "Import", "MACROSECURITY", message);
                        }
                    }
                }
                catch (Exception e)
                {
                    LogContext.AppendLine(e.Message);
                    EventLogProvider.LogException(EVENTLOG_SOURCE_REFRESHSECURITYPARAMS, "ERROR", e);
                }
            }
        }

        EventLogProvider.LogEvent(EventType.INFORMATION, EVENTLOG_SOURCE_REFRESHSECURITYPARAMS, "PROCESSEDOBJECTS", GetProcessedObjectsForEventLog());
    }
    protected void drpTransformationType_SelectedIndexChanged(object sender, EventArgs e)
    {
        // Get the current code
        string code = TransformationCode;

        switch (drpType.SelectedValue.ToLowerCSafe())
        {
        case "ascx":
            // Convert to ASCX syntax
            if (CMSString.Equals(drpType.SelectedValue, "ascx", true))
            {
                code = MacroSecurityProcessor.RemoveSecurityParameters(code, false, null);

                code = code.Replace("{% Register", "<%@ Register").Replace("{%", "<%#").Replace("%}", "%>");
            }

            ShowMessage();
            break;

        case "xslt":
            // No transformation
            break;

        default:
            // Convert to macro syntax
            code = code.Replace("<%@", "{%").Replace("<%#", "{%").Replace("<%=", "{%").Replace("<%", "{%").Replace("%>", "%}");
            break;
        }

        // Move the content if necessary
        if (CMSString.Equals(drpType.SelectedValue, "html", true))
        {
            // Move from text to WYSIWYG
            if (txtCode.Visible)
            {
                tbWysiwyg.ResolvedValue = code;
                tbWysiwyg.Visible       = true;

                txtCode.Text    = string.Empty;
                txtCode.Visible = false;
            }
        }
        else
        {
            // Move from WYSIWYG to text
            if (tbWysiwyg.Visible)
            {
                code = HttpUtility.HtmlDecode(code);

                txtCode.Text    = code;
                txtCode.Visible = true;

                tbWysiwyg.ResolvedValue = string.Empty;
                tbWysiwyg.Visible       = false;
            }
            else
            {
                txtCode.Text = code;
            }
        }

        SetEditor();
    }
Exemplo n.º 23
0
    /// <summary>
    /// Loads content from specific newsletter template.
    /// </summary>
    private void LoadContent()
    {
        EmailTemplateInfo emailTemplate = EmailTemplateInfoProvider.GetEmailTemplateInfo(mTemplateID);

        if ((emailTemplate == null) || string.IsNullOrEmpty(emailTemplate.TemplateBody))
        {
            return;
        }

        // Remove security parameters from macros
        string templateText = MacroSecurityProcessor.RemoveSecurityParameters(emailTemplate.TemplateBody, true, null);

        if (!RequestHelper.IsPostBack() && (issue != null))
        {
            // Load content of editable regions
            IssueHelper.LoadRegionsContents(ref regionsContents, issue.IssueText);
        }

        CMSEditableRegion editableRegion = null;
        LiteralControl    before         = null;
        int    count     = 0;
        int    textStart = 0;
        string region    = null;

        string[] parts           = null;
        string   name            = null;
        string   toolbarLocation = "Out:CKEditorToolbar";
        string   toolbarSetName  = "Newsletter";

        int editRegStart = templateText.IndexOfCSafe("$$", textStart);
        int editRegEnd   = 0;

        // Apply CSS e-mail template style
        HTMLHelper.AddToHeader(Page, CSSHelper.GetCSSFileLink(EmailTemplateInfoProvider.GetStylesheetUrl(emailTemplate.TemplateName)));

        while (editRegStart >= 0)
        {
            count++;

            before = new LiteralControl();
            // Get template text surrounding editable regions - make links absolute
            before.Text = URLHelper.MakeLinksAbsolute(templateText.Substring(textStart, (editRegStart - textStart)));
            plcContent.Controls.Add(before);

            // End of region
            editRegStart += 2;
            textStart     = editRegStart;
            if (editRegStart < templateText.Length - 1)
            {
                editRegEnd = templateText.IndexOfCSafe("$$", editRegStart);
                if (editRegEnd >= 0)
                {
                    region = templateText.Substring(editRegStart, editRegEnd - editRegStart);
                    parts  = (region + ":" + ":").Split(':');

                    try
                    {
                        name = parts[0];
                        if (!string.IsNullOrEmpty(name.Trim()))
                        {
                            Regex intNumber = RegexHelper.GetRegex("^[0-9]+");
                            int   width     = ValidationHelper.GetInteger(intNumber.Match(parts[1]).Value, 0);
                            int   height    = ValidationHelper.GetInteger(intNumber.Match(parts[2]).Value, 0);

                            editableRegion            = new CMSEditableRegion();
                            editableRegion.ID         = name;
                            editableRegion.RegionType = CMSEditableRegionTypeEnum.HtmlEditor;
                            editableRegion.ViewMode   = ViewModeEnum.Edit;

                            editableRegion.DialogHeight = height;
                            editableRegion.DialogWidth  = width;

                            editableRegion.WordWrap = false;
                            editableRegion.HtmlAreaToolbarLocation = toolbarLocation;
                            editableRegion.RegionTitle             = name;
                            editableRegion.UseStylesheet           = false;
                            editableRegion.HTMLEditorCssStylesheet = EmailTemplateInfoProvider.GetStylesheetUrl(emailTemplate.TemplateName);

                            if (!mReadOnly)
                            {
                                editableRegion.HtmlAreaToolbar = toolbarSetName;
                            }
                            else
                            {
                                editableRegion.HtmlAreaToolbar = "Disabled";
                            }

                            CMSHtmlEditor editor = editableRegion.HtmlEditor;
                            editor.AddExtraPlugin("CMSPlugins");
                            editor.AddExtraPlugin("autogrow");
                            editor.AutoGrowMinHeight            = height;
                            editor.LinkDialogConfig.UseFullURL  = true;
                            editor.QuickInsertConfig.UseFullURL = true;
                            editor.ResolverName = "NewsletterResolver";

                            DialogConfiguration dialogConfig = editor.MediaDialogConfig;
                            dialogConfig.UseFullURL         = true;
                            dialogConfig.MetaFileObjectID   = (issue != null) ? issue.IssueID : 0;
                            dialogConfig.MetaFileObjectType = (issue != null) && issue.IssueIsVariant ? NewsletterObjectType.NEWSLETTERISSUEVARIANT : NewsletterObjectType.NEWSLETTERISSUE;
                            dialogConfig.MetaFileCategory   = MetaFileInfoProvider.OBJECT_CATEGORY_ISSUE;
                            dialogConfig.HideAttachments    = false;

                            editableRegion.LoadContent(ValidationHelper.GetString(regionsContents[name.ToLowerCSafe()], string.Empty));

                            plcContent.Controls.Add(editableRegion);

                            textStart = editRegEnd + 2;
                        }
                    }
                    catch
                    {
                    }
                }
            }
            editRegStart = templateText.IndexOfCSafe("$$", textStart);
        }

        before      = new LiteralControl();
        before.Text = URLHelper.MakeLinksAbsolute(templateText.Substring(textStart));

        plcContent.Controls.Add(before);
    }
Exemplo n.º 24
0
    /// <summary>
    /// Creates new or updates existing newsletter issue.
    /// </summary>
    public bool Save()
    {
        if (mValidated || IsValid())
        {
            IssueInfo issue;

            if (IssueID == 0)
            {
                // Initialize new issue
                issue = new IssueInfo();
                issue.IssueUnsubscribed = 0;
                issue.IssueSentEmails   = 0;
                issue.IssueNewsletterID = NewsletterID;
                issue.IssueSiteID       = SiteContext.CurrentSiteID;
            }
            else
            {
                issue = IssueInfoProvider.GetIssueInfo(IssueID);
            }

            if (issue != null)
            {
                issue.IssueTemplateID = TemplateID;
                issue.IssueShowInNewsletterArchive = chkShowInArchive.Checked;
                issue.IssueSenderName  = txtSenderName.Text.Trim();
                issue.IssueSenderEmail = txtSenderEmail.Text.Trim();
                issue.IssueUseUTM      = chkIssueUseUTM.Checked;

                var normalizedUtmSource = Normalize(txtIssueUTMSource.Text.Trim());
                if (string.IsNullOrEmpty(normalizedUtmSource))
                {
                    normalizedUtmSource = Normalize(Newsletter.NewsletterName + "_" + txtSubject.Text.Trim());
                }
                txtIssueUTMSource.Text = issue.IssueUTMSource = normalizedUtmSource;

                if (radUTMCampaignNew.Checked)
                {
                    var normalizedUtmCampaign = Normalize(mUTMCampaignTextBox.Text.Trim());
                    if (string.IsNullOrEmpty(normalizedUtmCampaign))
                    {
                        normalizedUtmCampaign = Normalize(Newsletter.NewsletterName);
                    }
                    mUTMCampaignTextBox.Text = issue.IssueUTMCampaign = normalizedUtmCampaign;
                }
                else
                {
                    issue.IssueUTMCampaign = selectorUTMCampaign.Value.ToString().ToLower();
                }

                if (issue.IssueIsABTest)
                {
                    SynchronizeUTMParameters(issue);
                }

                // Saves content of editable region(s)
                // Get content from hidden field
                string   content = hdnIssueContent.Value;
                string[] regions = null;
                if (!string.IsNullOrEmpty(content))
                {
                    // Split content for each region, separator is '#|#'
                    regions = content.Split(new[] { "#|#" }, StringSplitOptions.RemoveEmptyEntries);
                }
                issue.IssueText = IssueHelper.GetContentXML(regions);

                // Remove '#' from macros if included
                txtSubject.Text = txtSubject.Text.Trim().Replace("#%}", "%}");

                // Sign macros if included in the subject
                issue.IssueSubject = MacroSecurityProcessor.AddSecurityParameters(txtSubject.Text, MembershipContext.AuthenticatedUser.UserName, null);

                // Save issue
                IssueInfoProvider.SetIssueInfo(issue);

                // Update IssueID
                IssueID = issue.IssueID;

                return(true);
            }
        }

        return(false);
    }
Exemplo n.º 25
0
    /// <summary>
    /// Creates new or updates existing newsletter issue.
    /// </summary>
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        var issue = IssueInfo.Provider.Get(IssueID);

        if ((issue == null) || !Enabled || !IsValid(issue))
        {
            return;
        }

        if (IsDisplayNameFieldEnabled(issue))
        {
            issue.IssueDisplayName = txtDisplayName.Text.Trim();
        }

        issue.IssueTemplateID  = TemplateID;
        issue.IssueSenderName  = txtSenderName.Text.Trim();
        issue.IssueSenderEmail = txtSenderEmail.Text.Trim();
        issue.IssuePreheader   = txtPreheader.Text.Trim();
        issue.IssueUseUTM      = chkIssueUseUTM.Checked;
        issue.IssueUTMSource   = Normalize(txtIssueUTMSource.Text.Trim());

        var needsFullRefresh = false;

        if (chkIssueForAutomation.Visible)
        {
            // Check whether the full refresh of the Email builder (including the left tabs) is necessary
            needsFullRefresh = issue.IssueForAutomation != chkIssueForAutomation.Checked;

            issue.IssueForAutomation = chkIssueForAutomation.Checked;
        }

        if (radUTMCampaignNew.Checked)
        {
            var normalizedUtmCampaign = Normalize(mUTMCampaignTextBox.Text.Trim());
            if (string.IsNullOrEmpty(normalizedUtmCampaign))
            {
                normalizedUtmCampaign = Normalize(Newsletter.NewsletterName);
            }
            mUTMCampaignTextBox.Text = issue.IssueUTMCampaign = normalizedUtmCampaign;
        }
        else
        {
            issue.IssueUTMCampaign = selectorUTMCampaign.Value.ToString().ToLower(CultureInfo.CurrentCulture);
        }

        PostProcessVariants(issue);

        // Remove '#' from macros if included
        txtSubject.Text = txtSubject.Text.Trim().Replace("#%}", "%}");

        // Sign macros if included in the subject
        issue.IssueSubject = MacroSecurityProcessor.AddSecurityParameters(txtSubject.Text, MacroIdentityOption.FromUserInfo(MembershipContext.AuthenticatedUser), null);

        // Save issue
        IssueInfo.Provider.Set(issue);

        // Update IssueID
        IssueID = issue.IssueID;

        var builderEventArgs = needsFullRefresh ? new EmailBuilderEventArgs() : new EmailBuilderEventArgs(NewsletterID, IssueID, 1);

        OnSave(builderEventArgs);
    }
Exemplo n.º 26
0
    private void RefreshSecurityParams(IEnumerable <string> objectTypes, string oldSalt, string newSalt)
    {
        var oldSaltSpecified = !string.IsNullOrEmpty(oldSalt) && !chkRefreshAll.Checked;
        var newSaltSpecified = !string.IsNullOrEmpty(newSalt) && !chkUseCurrentSalt.Checked;

        processedObjects.Clear();

        using (var context = new CMSActionContext())
        {
            context.LogEvents          = false;
            context.LogSynchronization = false;
            var processingString = GetString("macros.refreshsecurityparams.processing");

            foreach (var objectType in objectTypes)
            {
                var niceObjectType = GetNiceObjectTypeName(objectType);

                AddLog(string.Format(processingString, niceObjectType));

                try
                {
                    var infos = new InfoObjectCollection(objectType)
                    {
                        PageSize = 1000
                    };

                    var csi          = infos.TypeInfo.ClassStructureInfo;
                    var orderByIndex = FindOrderByIndex(csi);
                    if (orderByIndex != null)
                    {
                        infos.OrderByColumns = orderByIndex.GetOrderBy();
                    }

                    // Skip object types derived from general data class object type to avoid duplicities
                    if ((infos.TypeInfo.OriginalObjectType == DataClassInfo.OBJECT_TYPE) && (infos.TypeInfo.ObjectType != DataClassInfo.OBJECT_TYPE))
                    {
                        continue;
                    }

                    foreach (var info in infos)
                    {
                        try
                        {
                            bool refreshed;
                            if (oldSaltSpecified)
                            {
                                refreshed = MacroSecurityProcessor.RefreshSecurityParameters(info, oldSalt, newSaltSpecified ? newSalt : ValidationHelper.HashStringSalt, true);
                            }
                            else
                            {
                                var identityOption = MacroIdentityOption.FromUserInfo(MembershipContext.AuthenticatedUser);
                                if (chkRefreshAll.Checked && newSaltSpecified)
                                {
                                    // Do not check integrity, but use new salt
                                    refreshed = MacroSecurityProcessor.RefreshSecurityParameters(info, identityOption, true, newSalt);
                                }
                                else
                                {
                                    // Do not check integrity, sign everything with current user
                                    refreshed = MacroSecurityProcessor.RefreshSecurityParameters(info, identityOption, true);
                                }
                            }

                            if (refreshed)
                            {
                                var objectName = HTMLHelper.HTMLEncode(ResHelper.LocalizeString(info.Generalized.ObjectDisplayName));
                                processedObjects.Add(niceObjectType, objectName);
                            }
                        }
                        catch (Exception ex)
                        {
                            string message = "Signing " + TypeHelper.GetNiceObjectTypeName(info.TypeInfo.ObjectType) + " " + info.Generalized.ObjectDisplayName + " failed: " + ex.Message;

                            using (var exceptionContext = new CMSActionContext())
                            {
                                exceptionContext.LogEvents = true;

                                EventLogProvider.LogEvent(EventType.ERROR, "Import", "MACROSECURITY", message);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    AddLog(ex.Message);

                    using (var exceptionContext = new CMSActionContext())
                    {
                        exceptionContext.LogEvents = true;

                        EventLogProvider.LogException(EVENTLOG_SOURCE_REFRESHSECURITYPARAMS, "ERROR", ex);
                    }
                }
            }
        }

        EventLogProvider.LogEvent(EventType.INFORMATION, EVENTLOG_SOURCE_REFRESHSECURITYPARAMS, "PROCESSEDOBJECTS", GetProcessedObjectsForEventLog());
    }
    /// <summary>
    /// Creates new <see cref="FieldMacroRule"/> object based on inputs.
    /// </summary>
    private FieldMacroRule CreateMacroRule()
    {
        if (!IsValid())
        {
            return(null);
        }

        MacroRuleTree  main = null;
        FieldMacroRule fmr  = null;

        MacroRuleInfo mri = MacroRuleInfoProvider.GetMacroRuleInfo(mSelectedRuleName);

        if (mri != null)
        {
            main = new MacroRuleTree();

            MacroRuleTree childern = new MacroRuleTree()
            {
                RuleText      = mri.MacroRuleText,
                RuleName      = mri.MacroRuleName,
                RuleCondition = mri.MacroRuleCondition,
                Parent        = main
            };
            main.Children.Add(childern);

            foreach (string paramName in formProperties.Fields)
            {
                // Load value from the form control
                FormEngineUserControl ctrl = formProperties.FieldControls[paramName];
                if (ctrl != null)
                {
                    // Convert value to EN culture
                    var dataType = ctrl.FieldInfo.DataType;

                    var convertedValue = DataTypeManager.ConvertToSystemType(TypeEnum.Field, dataType, ctrl.Value);

                    string value       = ValidationHelper.GetString(convertedValue, "", CultureHelper.EnglishCulture);
                    string displayName = ctrl.ValueDisplayName;

                    if (String.IsNullOrEmpty(displayName))
                    {
                        displayName = value;
                    }

                    MacroRuleParameter param = new MacroRuleParameter
                    {
                        Value     = value,
                        Text      = displayName,
                        ValueType = dataType
                    };

                    childern.Parameters.Add(paramName, param);
                }
            }

            string macroRule = string.Format("Rule(\"{0}\", \"{1}\")", MacroElement.EscapeSpecialChars(main.GetCondition()), MacroElement.EscapeSpecialChars(main.GetXML()));

            if (!MacroSecurityProcessor.IsSimpleMacro(macroRule))
            {
                // Sign complex macros
                macroRule = MacroSecurityProcessor.AddMacroSecurityParams(macroRule, MacroIdentityOption.FromUserInfo(MembershipContext.AuthenticatedUser));
            }

            fmr              = new FieldMacroRule();
            fmr.MacroRule    = string.Format("{{%{0}%}}", macroRule);
            fmr.ErrorMessage = txtErrorMsg.Text;
        }

        return(fmr);
    }
    /// <summary>
    /// Generates tables
    /// </summary>
    private void GenerateTable()
    {
        tblData.Controls.Clear();

        Hashtable ht = data.ConvertToHashtable();

        TableHeaderRow th = new TableHeaderRow()
        {
            TableSection = TableRowSection.TableHeader
        };
        TableHeaderCell ha = new TableHeaderCell();
        TableHeaderCell hn = new TableHeaderCell();
        TableHeaderCell hv = new TableHeaderCell();

        th.CssClass = "unigrid-head";

        ha.Text     = GetString("unigrid.actions");
        ha.CssClass = "unigrid-actions-header";

        hn.Text  = GetString("xmleditor.propertyname");
        hn.Width = Unit.Pixel(180);
        hv.Text  = GetString("xmleditor.propertyvalue");
        hv.Width = Unit.Pixel(500);

        th.Cells.Add(ha);
        th.Cells.Add(hn);
        th.Cells.Add(hv);

        tblData.Rows.Add(th);

        ArrayList keys = new ArrayList(ht);

        keys.Sort(new CustomStringComparer());

        foreach (DictionaryEntry okey in keys)
        {
            String key   = ValidationHelper.GetString(okey.Key, String.Empty);
            String value = ValidationHelper.GetString(okey.Value, String.Empty);

            bool isInvalid = (key == INVALIDTOKEN);
            key = isInvalid ? invalidKey : key;

            if (value == String.Empty)
            {
                continue;
            }

            TableRow tr = new TableRow();

            // Actions
            TableCell tna = new TableCell();
            tna.CssClass = "unigrid-actions";

            var imgEdit = new CMSGridActionButton();
            imgEdit.OnClientClick = String.Format("displayEdit('{1}','{0}'); return false; ", key, ClientID);
            imgEdit.IconCssClass  = "icon-edit";
            imgEdit.IconStyle     = GridIconStyle.Allow;
            imgEdit.ID            = key + "_edit";
            imgEdit.ToolTip       = GetString("xmleditor.edititem");

            var imgOK = new CMSGridActionButton();
            imgOK.IconCssClass  = "icon-check";
            imgOK.IconStyle     = GridIconStyle.Allow;
            imgOK.OnClientClick = String.Format("approveCustomChanges('{0}','{1}');return false;", ClientID, key);
            imgOK.ID            = key + "_ok";
            imgOK.ToolTip       = GetString("xmleditor.approvechanges");

            var imgDelete = new CMSGridActionButton();
            imgDelete.OnClientClick = " if (confirm('" + GetString("xmleditor.deleteconfirm") + "')) {" + ControlsHelper.GetPostBackEventReference(tblData, "delete_" + key) + "} ;return false;";
            imgDelete.IconCssClass  = "icon-bin";
            imgDelete.IconStyle     = GridIconStyle.Critical;
            imgDelete.ID            = key + "_del";
            imgDelete.ToolTip       = GetString("xmleditor.deleteitem");

            var imgUndo = new CMSGridActionButton();
            imgUndo.OnClientClick = String.Format("if (confirm('" + GetString("xmleditor.confirmcancel") + "')) undoCustomChanges('{0}','{1}'); return false;", ClientID, key);
            imgUndo.IconCssClass  = "icon-arrow-crooked-left";
            imgUndo.ID            = key + "_undo";
            imgUndo.ToolTip       = GetString("xmleditor.undochanges");

            tna.Controls.Add(imgEdit);
            tna.Controls.Add(imgOK);
            tna.Controls.Add(imgDelete);
            tna.Controls.Add(imgUndo);

            value = MacroSecurityProcessor.RemoveSecurityParameters(value, false, null);

            // Labels
            Label lblName = new Label();
            lblName.ID   = "sk" + key;
            lblName.Text = key;

            Label lblValue = new Label();
            lblValue.ID   = "sv" + key;
            lblValue.Text = value;

            // Textboxes
            CMSTextBox txtName = new CMSTextBox();
            txtName.Text     = key;
            txtName.ID       = "tk" + key;
            txtName.CssClass = "XmlEditorTextbox";

            CMSTextBox txtValue = new CMSTextBox();
            txtValue.Text     = value;
            txtValue.ID       = "tv" + key;
            txtValue.CssClass = "XmlEditorTextbox";
            txtValue.Width    = Unit.Pixel(490);

            labels.Add(lblName);
            labels.Add(lblValue);

            textboxes.Add(txtName);
            textboxes.Add(txtValue);

            TableCell tcn = new TableCell();
            tcn.Controls.Add(lblName);
            tcn.Controls.Add(txtName);

            TableCell tcv = new TableCell();
            tcv.Controls.Add(lblValue);
            tcv.Controls.Add(txtValue);

            tr.Cells.Add(tna);
            tr.Cells.Add(tcn);
            tr.Cells.Add(tcv);

            tblData.Rows.Add(tr);

            lblValue.CssClass = String.Empty;
            lblName.CssClass  = "CustomEditorKeyClass";

            if (isInvalid)
            {
                imgDelete.AddCssClass("hidden");
                imgEdit.AddCssClass("hidden");

                lblName.AddCssClass("hidden");
                lblValue.AddCssClass("hidden");

                RegisterEnableScript(false);
            }
            else
            {
                imgOK.AddCssClass("hidden");
                imgUndo.AddCssClass("hidden");

                txtName.CssClass  += " hidden";
                txtValue.CssClass += " hidden";
            }
        }
    }
Exemplo n.º 29
0
 private string BuildMacroRuleCondition(string macroCondition) =>
 "<condition>\r\n  <macro>\r\n    <value>" +
 MacroSecurityProcessor.AddSecurityParameters(macroCondition,
                                              MacroIdentityOption.FromUserInfo(UserInfoProvider.AdministratorUser), null) +
 "</value>\r\n  </macro>\r\n</condition>";