Exemplo n.º 1
0
        /// <summary>
        /// Resolves more complex restrictions put on specific elements using HTML parser
        /// </summary>
        /// <param name="doc">The complete HtmlDocument</param>
        private void ResolveComplexElements(HtmlDocument doc)
        {
            // Script tags source URLs from settings
            string ampCustomForm = String.Format(Constants.AMP_CUSTOM_ELEMENT_AMP_FORM, SettingsKeyInfoProvider.GetValue(SiteContext.CurrentSiteName + ".AMPFilterFormScriptUrl"));

            // Process <form> tags
            HtmlNodeCollection nodes = doc.DocumentNode.SelectNodes(Constants.XPATH_FORM);

            if (nodes != null)
            {
                foreach (HtmlNode node in nodes)
                {
                    // If attribute method="post" action attribute must be replaced by action-xhr
                    if ((node.Attributes["method"] != null) && (node.Attributes["method"].Value.ToLower() == "post"))
                    {
                        if (node.Attributes["action"] != null)
                        {
                            node.Attributes["action"].Name = "action-xhr";
                        }
                    }

                    // Ensure that target attribute has correct value or add target attribute with correct value
                    if ((node.Attributes["target"] == null) || (
                            (node.Attributes["target"] != null) && (node.Attributes["target"].Value.ToLower() != "_top")))
                    {
                        node.SetAttributeValue("target", "_blank");
                    }
                }

                // At least one <form> tag is used, we need to import custom element
                customElementsScripts += ampCustomForm + Constants.NEW_LINE;
            }

            // Process included fonts, only fonts from group of providers are allowed
            nodes = doc.DocumentNode.SelectNodes(Constants.XPATH_FONT_STYLESHEET);

            // List of font providers from settings
            string[] fontProviders = SettingsKeyInfoProvider.GetValue(SiteContext.CurrentSiteName + ".AmpFilterFontProviders").Split('\n');
            if (nodes != null)
            {
                foreach (HtmlNode node in nodes)
                {
                    var elementAllowed = false;
                    if (node.Attributes["href"] != null)
                    {
                        foreach (string provider in fontProviders)
                        {
                            if (node.Attributes["href"].Value.ToLower().StartsWith(provider.Trim()))
                            {
                                elementAllowed = true;
                                break;
                            }
                        }
                    }
                    if (!elementAllowed)
                    {
                        node.Remove();
                    }
                }
            }
        }
    /// <summary>
    /// Checks status of current user.
    /// </summary>
    protected void CheckStatus()
    {
        // Get current site name
        string siteName = SiteContext.CurrentSiteName;
        string error    = null;

        // Check return URL
        string returnUrl = QueryHelper.GetString("returnurl", null);

        returnUrl = HttpUtility.UrlDecode(returnUrl);

        // Get current URL
        string currentUrl = RequestContext.CurrentURL;

        currentUrl = URLHelper.RemoveParameterFromUrl(currentUrl, "token");
        currentUrl = URLHelper.RemoveParameterFromUrl(currentUrl, "openid.ns");
        currentUrl = URLHelper.RemoveParameterFromUrl(currentUrl, "openid.mode");
        currentUrl = URLHelper.RemoveParameterFromUrl(currentUrl, "openid.return_to");
        currentUrl = URLHelper.RemoveParameterFromUrl(currentUrl, "openid.claimed_id");
        currentUrl = URLHelper.RemoveParameterFromUrl(currentUrl, "openid.identity");
        currentUrl = URLHelper.RemoveParameterFromUrl(currentUrl, "openid.assoc_handle");
        currentUrl = URLHelper.RemoveParameterFromUrl(currentUrl, "openid.realm");
        currentUrl = URLHelper.RemoveParameterFromUrl(currentUrl, "openid.response_nonce");
        currentUrl = URLHelper.RemoveParameterFromUrl(currentUrl, "openid.signed");
        currentUrl = URLHelper.RemoveParameterFromUrl(currentUrl, "openid.op_endpoint");
        currentUrl = URLHelper.RemoveParameterFromUrl(currentUrl, "openid.pape.auth_level.nist");
        currentUrl = URLHelper.RemoveParameterFromUrl(currentUrl, "openid.sig");

        // Get OpenID response status
        switch (openIDhelper.CheckStatus())
        {
        // User is authenticated
        case CMSOpenIDHelper.RESPONSE_AUTHENTICATED:
            // Claimed ID not found  = save new user
            if (OpenIDUserInfoProvider.GetUserInfoByOpenID(openIDhelper.ClaimedIdentifier) == null)
            {
                // Check whether additional user info page is set
                string additionalInfoPage = SettingsKeyInfoProvider.GetValue(siteName + ".CMSRequiredOpenIDPage").Trim();

                // No page set, user can be created
                if (String.IsNullOrEmpty(additionalInfoPage))
                {
                    // Register new user
                    UserInfo ui = AuthenticationHelper.AuthenticateOpenIDUser(openIDhelper.ClaimedIdentifier, ValidationHelper.GetString(SessionHelper.GetValue(SESSION_NAME_URL), null), siteName, false, true, ref error);

                    // If user was found or successfuly created
                    if (ui != null)
                    {
                        // Load values submited by OpenID provider
                        // Load date of birth
                        if (openIDhelper.BirthDate != DateTime.MinValue)
                        {
                            ui.UserSettings.UserDateOfBirth = openIDhelper.BirthDate;
                        }
                        // Load default country
                        if (openIDhelper.Culture != null)
                        {
                            ui.PreferredCultureCode = openIDhelper.Culture.Name;
                        }
                        // Load e-mail
                        if (!String.IsNullOrEmpty(openIDhelper.Email))
                        {
                            ui.Email = openIDhelper.Email;
                        }
                        // Nick name
                        if (!String.IsNullOrEmpty(openIDhelper.Nickname))
                        {
                            ui.UserSettings.UserNickName = openIDhelper.Nickname;
                        }
                        // User gender
                        if (openIDhelper.UserGender != null)
                        {
                            ui.UserSettings.UserGender = (int)openIDhelper.UserGender;
                        }

                        UserInfoProvider.SetUserInfo(ui);

                        // If user is enabled
                        if (ui.Enabled)
                        {
                            // Create autentification cookie
                            AuthenticationHelper.SetAuthCookieWithUserData(ui.UserName, true, Session.Timeout, new[] { "openidlogin" });
                            // Log activity
                            MembershipActivityLogger.LogLogin(ui.UserName, DocumentContext.CurrentDocument);
                        }

                        // Notify administrator
                        if (NotifyAdministrator && !String.IsNullOrEmpty(FromAddress) && !String.IsNullOrEmpty(ToAddress))
                        {
                            AuthenticationHelper.NotifyAdministrator(ui, FromAddress, ToAddress);
                        }

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

                        MembershipActivityLogger.LogRegistration(ui.UserName, DocumentContext.CurrentDocument);
                    }

                    // Redirect when authentication was succesfull
                    if (String.IsNullOrEmpty(error))
                    {
                        if (URLHelper.IsLocalUrl(returnUrl))
                        {
                            URLHelper.Redirect(returnUrl);
                        }
                        else
                        {
                            URLHelper.Redirect(currentUrl);
                        }
                    }
                    // Display error otherwise
                    else
                    {
                        lblError.Text    = error;
                        lblError.Visible = true;
                    }
                }
                // Additional information page is set
                else
                {
                    // Store user object in session for additional use
                    StoreResponseInSession();

                    // Redirect to additional info page
                    string targetURL = URLHelper.GetAbsoluteUrl(additionalInfoPage);

                    if (URLHelper.IsLocalUrl(returnUrl))
                    {
                        // Add return URL to parameter
                        targetURL = URLHelper.AddParameterToUrl(targetURL, "returnurl", HttpUtility.UrlEncode(returnUrl));
                    }

                    URLHelper.Redirect(UrlResolver.ResolveUrl(targetURL));
                }
            }
            // Claimed OpenID is in DB
            else
            {
                // Login existing user
                UserInfo ui = AuthenticationHelper.AuthenticateOpenIDUser(openIDhelper.ClaimedIdentifier, ValidationHelper.GetString(SessionHelper.GetValue(SESSION_NAME_URL), null), siteName, false, true, ref error);

                if ((ui != null) && (ui.Enabled))
                {
                    // Create autentification cookie
                    AuthenticationHelper.SetAuthCookieWithUserData(ui.UserName, true, Session.Timeout, new[] { "openilogin" });

                    // Log activity
                    MembershipActivityLogger.LogLogin(ui.UserName, DocumentContext.CurrentDocument);

                    // Redirect user
                    if (URLHelper.IsLocalUrl(returnUrl))
                    {
                        URLHelper.Redirect(UrlResolver.ResolveUrl(URLHelper.GetAbsoluteUrl(returnUrl)));
                    }
                    else
                    {
                        URLHelper.Redirect(currentUrl);
                    }
                }
                // Display error which occured during authentication process
                else if (!String.IsNullOrEmpty(error))
                {
                    lblError.Text    = error;
                    lblError.Visible = true;
                }
                // Otherwise is user disabled
                else
                {
                    lblError.Text    = GetString("membership.userdisabled");
                    lblError.Visible = true;
                }
            }
            break;

        // Authentication was canceled
        case CMSOpenIDHelper.RESPONSE_CANCELED:
            lblError.Text    = GetString("openid.logincanceled");
            lblError.Visible = true;
            break;

        // Authentication failed
        case CMSOpenIDHelper.RESPONSE_FAILED:
            lblError.Text    = GetString("openid.loginfailed");
            lblError.Visible = true;
            break;
        }
    }
Exemplo n.º 3
0
 protected void InsertDefaultMainCurrency()
 {
     SettingsKeyInfoProvider.SetValue(ECommerceSettings.USE_GLOBAL_CURRENCIES, SiteID, false);
     mFakeFactory.InitMainCurrency(SiteID).Insert();
 }
Exemplo n.º 4
0
    public string GetCallbackResult()
    {
        string   result = "";
        UserInfo ui     = UserInfoProvider.GetUserInfo(Login1.UserName);

        if (ui != null)
        {
            string siteName = SiteContext.CurrentSiteName;

            // Prepare return URL
            string returnUrl = RequestContext.CurrentURL;
            if (!string.IsNullOrEmpty(Login1.UserName))
            {
                returnUrl = URLHelper.AddParameterToUrl(returnUrl, "username", Login1.UserName);
            }

            switch (UserAccountLockCode.ToEnum(ui.UserAccountLockReason))
            {
            case UserAccountLockEnum.MaximumInvalidLogonAttemptsReached:
                result = AuthenticationHelper.SendUnlockAccountRequest(ui, siteName, "USERLOGON", SettingsKeyInfoProvider.GetValue(siteName + ".CMSSendPasswordEmailsFrom"), null, returnUrl);
                break;

            case UserAccountLockEnum.PasswordExpired:
                bool outParam = true;
                result = AuthenticationHelper.SendPasswordRequest(ui, siteName, "USERLOGON", SettingsKeyInfoProvider.GetValue(siteName + ".CMSSendPasswordEmailsFrom"), "Membership.PasswordExpired", null, AuthenticationHelper.GetResetPasswordUrl(siteName), out outParam, returnUrl);
                break;
            }
        }

        return(result);
    }
Exemplo n.º 5
0
    /// <summary>
    /// Initializes the controls on the page.
    /// </summary>
    private void SetupControls()
    {
        // Hide code name editing for simple mode
        if (DisplayMode == ControlDisplayModeEnum.Simple)
        {
            plcCodeName.Visible = false;
        }

        // Register scripts
        ScriptHelper.RegisterClientScriptBlock(this, typeof(string), "ShowDateFields",
                                               ScriptHelper.GetScript(
                                                   "function ShowDateFields(){ \n" +
                                                   "    document.getElementById('" + lblBoardOpenFrom.ClientID + "').style.display = 'block'; \n" +
                                                   "    document.getElementById('" + dtpBoardOpenFrom.ClientID + "').style.display = 'block'; \n" +
                                                   "    document.getElementById('" + lblBoardOpenTo.ClientID + "').style.display = 'block'; \n" +
                                                   "    document.getElementById('" + dtpBoardOpenTo.ClientID + "').style.display = 'block'; } \n" +
                                                   "function HideDateFields(){ \n " +
                                                   "    document.getElementById('" + lblBoardOpenFrom.ClientID + "').style.display = 'none'; \n " +
                                                   "    document.getElementById('" + dtpBoardOpenFrom.ClientID + "').style.display = 'none'; \n" +
                                                   "    document.getElementById('" + lblBoardOpenTo.ClientID + "').style.display = 'none'; \n" +
                                                   "    document.getElementById('" + dtpBoardOpenTo.ClientID + "').style.display = 'none'; }"
                                                   ));

        ScriptHelper.RegisterClientScriptBlock(this, typeof(string), "CheckBoxes",
                                               ScriptHelper.GetScript(@"
                function check(txtId,chk,inhV)  
                {
                    txt = document.getElementById(txtId);
                    if ((txt != null)&&(chk != null))
                    {
                        if (chk.checked)
                        {
                            txt.disabled = 'disabled';
                            txt.value = inhV;
                        }
                        else
                        {
                            txt.disabled = '';
                        }
                    }
                }"
                                                                      ));

        // Set the labels
        lblBoardCodeName.Text     = GetString("general.codename") + ResHelper.Colon;
        lblBoardOwner.Text        = GetString("board.owner.title") + ResHelper.Colon;
        lblBoardDescription.Text  = GetString("general.description") + ResHelper.Colon;
        lblBoardDisplayName.Text  = GetString("general.displayname") + ResHelper.Colon;
        lblBoardEnable.Text       = GetString("general.enable") + ResHelper.Colon;
        lblBoardOpen.Text         = GetString("general.open") + ResHelper.Colon;
        lblBoardOpenFrom.Text     = GetString("general.openfrom") + ResHelper.Colon;
        lblBoardOpenTo.Text       = GetString("general.opento") + ResHelper.Colon;
        lblBoardRequireEmail.Text = GetString("board.edit.requireemail") + ResHelper.Colon;
        lblUnsubscriptionUrl.Text = GetString("general.unsubscriptionurl") + ResHelper.Colon;
        lblBaseUrl.Text           = GetString("general.baseurl") + ResHelper.Colon;
        btnOk.Text = GetString("general.ok");

        chkBoardOpen.Attributes.Add("onclick", "if(this.checked){ ShowDateFields() }else{ HideDateFields() }");

        // Set the error messages for validators
        rfvBoardCodeName.ErrorMessage    = GetString("board.edit.errcodename");
        rfvBoardDisplayName.ErrorMessage = GetString("board.edit.errdisplayname");

        if (IsLiveSite)
        {
            plcUnsubscription.Visible = false;
        }

        chkInheritBaseUrl.Attributes.Add("onclick", "check('" + txtBaseUrl.ClientID + "', this,'" + ValidationHelper.GetString(SettingsKeyInfoProvider.GetValue(SiteContext.CurrentSiteName + ".CMSBoardBaseUrl"), "") + "')");
        chkInheritUnsubUrl.Attributes.Add("onclick", "check('" + txtUnsubscriptionUrl.ClientID + "', this,'" + ValidationHelper.GetString(SettingsKeyInfoProvider.GetValue(SiteContext.CurrentSiteName + ".CMSBoardUnsubsriptionURL"), "") + "')");
        chkInheritOptInURL.Attributes.Add("onclick", "check('" + txtOptInURL.PathTextBox.ClientID + "', this,'" + ValidationHelper.GetString(SettingsKeyInfoProvider.GetValue(SiteContext.CurrentSiteName + ".CMSBoardSubsriptionApprovalURL"), "") + "');ChangeState_" + txtOptInURL.ClientID + "(!this.checked);");

        chkEnableOptIn.NotSetChoice.Text = chkSendOptInConfirmation.NotSetChoice.Text = GetString("general.sitesettings") + " (##DEFAULT##)";
        chkEnableOptIn.SetDefaultValue(BoardInfoProvider.EnableDoubleOptIn(SiteContext.CurrentSiteName));
        chkSendOptInConfirmation.SetDefaultValue(BoardInfoProvider.SendOptInConfirmation(SiteContext.CurrentSiteName));

        if (ActivitySettingsHelper.IsModuleLoaded())
        {
            plcOnline.Visible = true;
        }
    }
        // Contains initialization code that is executed when the application starts
        protected override void OnInit()
        {
            base.OnInit();


            // Custom Relationship Name logging since adhoc is disabled in staging by default (since usually tied to page type)
            RelationshipNameInfo.TYPEINFO.Events.Insert.After     += RelationshipName_Insert_After;
            RelationshipNameInfo.TYPEINFO.Events.Update.After     += RelationshipName_Update_After;
            RelationshipNameInfo.TYPEINFO.Events.Delete.After     += RelationshipName_Delete_After;
            RelationshipNameSiteInfo.TYPEINFO.Events.Insert.After += RelationshipNameSiteInfo_Insert_After;
            RelationshipNameSiteInfo.TYPEINFO.Events.Delete.After += RelationshipNameSiteInfo_Delete_After;

            // Since normally a page is "Saved" (changed) when you handle ad-hoc relationships, must also handle triggering the update on the document
            RelationshipInfo.TYPEINFO.Events.Insert.After += Relationship_Insert_Or_Delete_After;
            RelationshipInfo.TYPEINFO.Events.Delete.After += Relationship_Insert_Or_Delete_After;

            // Add in events to handle Document-bound node categories, or adjust to synchronize manually
            if (DataHelper.GetNotEmpty(SettingsKeyInfoProvider.GetValue(new SettingsKeyName("NodeCategoryStagingMode")), "WithDocument") == "WithDocument")
            {
                // Similar to Relationships, a Node Category needs to touch the Node, however this really is touching the 'document' not the node, so must manually trigger
                TreeCategoryInfo.TYPEINFO.Events.Insert.After += TreeCategory_Insert_Or_Delete_After;
                TreeCategoryInfo.TYPEINFO.Events.Delete.After += TreeCategory_Insert_Or_Delete_After;

                // Need to add TreeCategories to document data set and then processes it since sadly isn't doing it automatically :(
                StagingEvents.LogTask.Before    += LogTask_Before;
                StagingEvents.ProcessTask.After += ProcessTask_After;
            }
            else
            {
                // Add some custom logic to create a more readable Task Title
                StagingEvents.LogTask.Before += NonBindingLogTask_Before;
                // Handle object deletions, additions work but removals don't for node object relationships
                StagingEvents.ProcessTask.After += NonBindingNodeDocument_ProcessTask_After;
            }

            // Handle any tasks that need to be deleted due to originating from another server
            StagingEvents.LogTask.After += LogTask_After;

            // Also make sure that the foreign key exists for the class
            try
            {
                if (DataClassInfoProvider.GetDataClassInfo("CMS.TreeCategory") != null)
                {
                    ConnectionHelper.ExecuteQuery("CMS.TreeCategory.EnsureForeignKeys", null);
                }
            }
            catch (Exception ex)
            {
                Service.Resolve <IEventLogService>().LogException("RelationshipsExtended", "ErrorSettingForeignKeys", ex, additionalMessage: "Make sure the Query CMS.TreeCategory.EnsureForeignKey exists.  IGNORE if you just installed the module as this will run before the class installs on the first application start after installation.");
            }

            // Registers "CustomNamespace" into the macro engine
            MacroContext.GlobalResolver.SetNamedSourceData("RelHelper", RelHelperMacroNamespace.Instance);
            MacroContext.GlobalResolver.SetNamedSourceData("RelEnums", EnumMacroEvaluator.EnumMacroObjects());

            /* Check to make sure the 2 forms exist */
            if (AlternativeFormInfoProvider.GetAlternativeFormInfo("cms.relationshipname.NewForm") == null)
            {
                int ClassID = DataClassInfoProvider.GetDataClassInfo("cms.relationshipname").ClassID;
                AlternativeFormInfo RelationshipNewForm = new AlternativeFormInfo()
                {
                    FormClassID             = ClassID,
                    FormName                = "NewForm",
                    FormDisplayName         = "New Form",
                    FormDefinition          = "<form version=\"2\"><field column=\"RelationshipNameID\" guid=\"47839bd6-f19c-4cfd-b67f-1ca754694d46\" /><field column=\"RelationshipDisplayName\" guid=\"6515b190-003a-44b6-b541-8814760de218\" /><field column=\"RelationshipName\" guid=\"42221f4a-30fa-47a6-bc80-3f99ee81f8a5\" /><field column=\"RelationshipAllowedObjects\" guid=\"2a02c9d5-f0f9-4a19-be8d-9a007f4464ac\" /><field column=\"RelationshipNameIsAdHoc\" guid=\"f1d3667d-77eb-47de-9ad0-5f22ad63e082\" visible=\"true\"><settings><controlname>CheckBoxControl</controlname></settings><properties><fieldcaption>Relationship Is AdHoc (Sortable)</fieldcaption><fielddescription>Must be true if you wish to use sorting.</fielddescription></properties></field><field column=\"RelationshipGUID\" guid=\"03ad948a-2bb7-44b2-b580-b05abf3a2a8b\" /><field column=\"RelationshipLastModified\" guid=\"ea7edf35-ed86-4cef-91c5-7bfdde27c389\" /><field column=\"ReltionshipSite\" guid=\"a733ba02-3675-481a-b586-b87c49e23268\" /></form>",
                    FormHideNewParentFields = false,
                    FormIsCustom            = true
                };
                AlternativeFormInfoProvider.SetAlternativeFormInfo(RelationshipNewForm);
            }
            if (AlternativeFormInfoProvider.GetAlternativeFormInfo("cms.relationshipname.EditForm") == null)
            {
                int ClassID = DataClassInfoProvider.GetDataClassInfo("cms.relationshipname").ClassID;
                AlternativeFormInfo RelationshipNewForm = new AlternativeFormInfo()
                {
                    FormClassID             = ClassID,
                    FormName                = "EditForm",
                    FormDisplayName         = "Edit Form",
                    FormDefinition          = "<form version=\"2\"><field column=\"RelationshipNameID\" guid=\"47839bd6-f19c-4cfd-b67f-1ca754694d46\" /><field column=\"RelationshipDisplayName\" guid=\"6515b190-003a-44b6-b541-8814760de218\" /><field column=\"RelationshipName\" guid=\"42221f4a-30fa-47a6-bc80-3f99ee81f8a5\" /><field column=\"RelationshipAllowedObjects\" guid=\"2a02c9d5-f0f9-4a19-be8d-9a007f4464ac\" /><field column=\"RelationshipNameIsAdHoc\" guid=\"f1d3667d-77eb-47de-9ad0-5f22ad63e082\" visible=\"true\"><settings><controlname>CheckBoxControl</controlname></settings><properties><fieldcaption>Relationship Is AdHoc (Sortable)</fieldcaption><fielddescription>Must be true if you wish to use sorting.</fielddescription></properties></field><field column=\"RelationshipGUID\" guid=\"03ad948a-2bb7-44b2-b580-b05abf3a2a8b\" /><field column=\"RelationshipLastModified\" guid=\"ea7edf35-ed86-4cef-91c5-7bfdde27c389\" /><field column=\"ReltionshipSite\" guid=\"a733ba02-3675-481a-b586-b87c49e23268\" /></form>",
                    FormHideNewParentFields = false,
                    FormIsCustom            = true
                };
                AlternativeFormInfoProvider.SetAlternativeFormInfo(RelationshipNewForm);
            }
        }
    /// <summary>
    /// Reloads control.
    /// </summary>
    public void ReloadData()
    {
        string where = WhereCondition;

        var siteName    = SiteID > 0 ? SiteInfoProvider.GetSiteName(SiteID) : SiteContext.CurrentSiteName;
        var allowGlobal = SettingsKeyInfoProvider.GetBoolValue(siteName + ".cmscmglobalconfiguration");

        uniselector.AllowAll = AllowAllItem;

        if (DisplayAll || DisplaySiteOrGlobal)
        {
            // Display all site and global statuses
            if (DisplayAll && allowGlobal)
            {
                // No WHERE condition required
            }
            // Display current site and global statuses
            else if (DisplaySiteOrGlobal && allowGlobal && (SiteID > 0))
            {
                where = SqlHelper.AddWhereCondition(where, "AccountStatusSiteID IS NULL OR AccountStatusSiteID = " + SiteID);
            }
            // Current site
            else if (SiteID > 0)
            {
                where = SqlHelper.AddWhereCondition(where, "AccountStatusSiteID = " + SiteID);
            }
            // Display global statuses
            else if (allowGlobal)
            {
                where = SqlHelper.AddWhereCondition(where, "AccountStatusSiteID IS NULL ");
            }
            // Don't display anything
            if (String.IsNullOrEmpty(where) && !DisplayAll)
            {
                where = "(1=0)";
            }
        }
        // Display either global or current site statuses
        else
        {
            // Current site
            if (SiteID > 0)
            {
                where = SqlHelper.AddWhereCondition(where, "AccountStatusSiteID = " + SiteID);
            }
            // Display global statuses
            else if (((SiteID == UniSelector.US_GLOBAL_RECORD) || (SiteID == UniSelector.US_NONE_RECORD)) && allowGlobal)
            {
                where = SqlHelper.AddWhereCondition(where, "AccountStatusSiteID IS NULL ");
            }
            // Don't display anything
            if (String.IsNullOrEmpty(where))
            {
                where = "(1=0)";
            }
        }

        // Do not add condition to empty condition which allows everything
        if (!String.IsNullOrEmpty(where))
        {
            string status = ValidationHelper.GetString(Value, "");
            if (!String.IsNullOrEmpty(status))
            {
                where = SqlHelper.AddWhereCondition(where, String.Format("{0} = {1}", SqlHelper.GetSafeQueryString(uniselector.ReturnColumnName), SqlHelper.GetSafeQueryString(status)), "OR");
            }
        }

        uniselector.WhereCondition = where;
        uniselector.Reload(true);
    }
Exemplo n.º 8
0
    /// <summary>
    /// Updates settings key for all sites (or only global if the IsGlobal checkbox is checked).
    /// </summary>
    /// <returns>CodeName of the SettingsKey objects.</returns>
    private int UpdateKey()
    {
        // Try to get the key
        var keyObj = (mSettingsKeyId > 0) ? SettingsKeyInfoProvider.GetSettingsKeyInfo(mSettingsKeyId) : null;

        if (keyObj == null)
        {
            // Create new
            keyObj = new SettingsKeyInfo();
        }

        var oldKeyCategoryID = keyObj.KeyCategoryID;

        // Set values
        keyObj.KeyName         = txtKeyName.Text.Trim();
        keyObj.KeyDisplayName  = txtKeyDisplayName.Text.Trim();
        keyObj.KeyDescription  = txtKeyDescription.Text.Trim();
        keyObj.KeyType         = drpKeyType.SelectedValue;
        keyObj.KeyCategoryID   = mSelectedGroupId >= 0 ? mSelectedGroupId : drpCategory.SelectedCategory;
        keyObj.KeyIsGlobal     = chkKeyIsGlobal.Checked;
        keyObj.KeyIsHidden     = chkKeyIsHidden.Checked;
        keyObj.KeyValidation   = (string.IsNullOrEmpty(txtKeyValidation.Text.Trim()) ? null : txtKeyValidation.Text.Trim());
        keyObj.KeyDefaultValue = (string.IsNullOrEmpty(DefaultValue) ? null : DefaultValue);

        var path = ValidationHelper.GetString(ucSettingsKeyControlSelector.ControlPath, string.Empty);

        keyObj.KeyEditingControlPath = (string.IsNullOrEmpty(path.Trim()) ? null : path.Trim());

        // Update form control settings
        if (ucSettingsKeyControlSelector.IsFormControlSelected)
        {
            var formFieldInfo = new FormFieldInfo();
            ucControlSettings.SaveData();

            formFieldInfo.SettingsMacroTable = ucControlSettings.MacroTable;

            if ((ucControlSettings.FormData != null) && (ucControlSettings.FormData.ItemArray.Length > 0))
            {
                foreach (DataColumn column in ucControlSettings.FormData.Table.Columns)
                {
                    formFieldInfo.Settings[column.ColumnName] = ucControlSettings.FormData.Table.Rows[0][column.Caption];
                }
            }

            var settings = FormHelper.GetFormControlSettingsXml(formFieldInfo);
            keyObj.KeyFormControlSettings = settings;
        }
        else
        {
            keyObj.KeyFormControlSettings = null;
        }

        if (drpGeneration.Value >= 0)
        {
            keyObj.KeyLoadGeneration = drpGeneration.Value;
        }

        if (keyObj.KeyID == 0)
        {
            keyObj.KeyValue = DefaultValue;
        }

        if (chkKeyIsGlobal.Checked)
        {
            keyObj.SiteID = 0;
        }

        // If category changed set new order or if new set on the end of key list
        if (keyObj.KeyCategoryID != oldKeyCategoryID)
        {
            var keys = SettingsKeyInfoProvider.GetSettingsKeys(keyObj.KeyCategoryID)
                       .OrderByDescending("KeyOrder")
                       .Column("KeyOrder");

            keyObj.KeyOrder = keys.GetScalarResult(0) + 1;
        }

        SettingsKeyInfoProvider.SetSettingsKeyInfo(keyObj);

        // Update property
        mSettingsKeyObj = keyObj;

        return(keyObj.KeyID);
    }
 private Dictionary <String, bool> GetOutputCacheItemNames()
 {
     return(CacheHelper.GetCombinedCacheItems(SettingsKeyInfoProvider.GetValue("CMSOutputCacheItems"), OutputHelper.AvailableCacheItemNames));
 }
Exemplo n.º 10
0
    /// <summary>
    /// Handles btnOkNew click, creates new user and joins it with LinkedIn member id.
    /// </summary>
    protected void btnOkNew_Click(object sender, EventArgs e)
    {
        if (!String.IsNullOrEmpty(linkedInHelper.MemberId))
        {
            string currentSiteName = SiteContext.CurrentSiteName;

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

            string password = passStrength.Text;

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

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

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

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

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

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

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

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

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

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

                        UserInfoProvider.SetUserInfo(ui);

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

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

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

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

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

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

                        if (!String.IsNullOrEmpty(DisplayMessage))
                        {
                            lblInfo.Visible = true;
                            lblInfo.Text    = DisplayMessage;
                            plcForm.Visible = false;
                        }
                        else
                        {
                            URLHelper.Redirect(ResolveUrl("~/Default.aspx"));
                        }
                    }
                }
            }
            // Validation failed - display error message
            else
            {
                lblError.Text    = errorMessage;
                plcError.Visible = true;
            }
        }
    }
    /// <summary>
    /// Sends e-mail with password in case the user has specified his email address.
    /// Otherwise, displays the newly generated password to the current user.
    /// </summary>
    /// <param name="pswd">Password to send</param>
    private void SendEmail(string pswd)
    {
        if (UserInfo == null)
        {
            return;
        }

        // Check whether the 'From' element was specified
        string siteName  = SiteContext.CurrentSiteName;
        string emailFrom = SettingsKeyInfoProvider.GetValue("CMSSendPasswordEmailsFrom", siteName);

        if (string.IsNullOrEmpty(emailFrom))
        {
            ShowError(String.Format("{0} {1}", GetString("Administration-User_Edit_Password.PassChangedNotSent"), GetString("Administration-User_Edit_Password.FromMissing")));

            return;
        }

        string emailTo = UserInfo.Email;

        if (!String.IsNullOrEmpty(emailTo))
        {
            EmailMessage em = new EmailMessage
            {
                From        = emailFrom,
                Recipients  = emailTo,
                Subject     = GetString("Administration-User_Edit_Password.NewGen"),
                EmailFormat = EmailFormatEnum.Default
            };

            // Get e-mail template - try to get site specific template if edited user is assigned to current site
            EmailTemplateInfo template = EmailTemplateProvider.GetEmailTemplate("Membership.ChangedPassword", UserInfo.IsInSite(siteName) ? siteName : null);
            if (template != null)
            {
                em.Body = template.TemplateText;

                // Because the password was generated by the system, it's included in the e-mail
                MacroResolver resolver = MembershipResolvers.GetPasswordResolver(UserInfo, pswd);

                try
                {
                    EmailHelper.ResolveMetaFileImages(em, template.TemplateID, EmailTemplateInfo.OBJECT_TYPE, ObjectAttachmentsCategories.TEMPLATE);

                    // Send message immediately (+ resolve macros)
                    EmailSender.SendEmailWithTemplateText(siteName, em, template, resolver, true);

                    // Inform on success
                    ShowConfirmation(GetString("Administration-User_Edit_Password.PasswordsSent") + " " + HTMLHelper.HTMLEncode(emailTo));

                    return;
                }
                catch (Exception ex)
                {
                    EventLogProvider.LogException("PasswordRetrieval", "USERPASSWORD", ex);
                    ShowError("Failed to send the password: "******"Administration-User_Edit_Password.PassChangedNotSent"));
            }
        }
        else
        {
            ShowConfirmation(String.Format(GetString("Administration-User_Edit_Password.passshow"), pswd), true);
        }
    }
Exemplo n.º 12
0
    /// <summary>
    /// Send e-mail to administrator about new registration.
    /// </summary>
    /// <param name="administrationApproval">Indicates if administration approval is required</param>
    private void SendEmailToAdministrator(bool administrationApproval)
    {
        MacroResolver resolver        = MembershipResolvers.GetRegistrationResolver(RegisteredUser);
        string        currentSiteName = SiteContext.CurrentSiteName;
        var           template        = EmailTemplateProvider.GetEmailTemplate(administrationApproval ? "Registration.Approve" : "Registration.New", currentSiteName);

        if (template == null)
        {
            EventLogProvider.LogEvent(EventType.ERROR, "RegistrationForm", "GetEmailTemplate", eventUrl: RequestContext.RawURL);
        }
        else
        {
            // E-mail template ok
            string from = EmailHelper.GetSender(template, (!String.IsNullOrEmpty(FromAddress)) ? FromAddress : SettingsKeyInfoProvider.GetValue(currentSiteName + ".CMSNoreplyEmailAddress"));
            if (!String.IsNullOrEmpty(from))
            {
                // Email message
                EmailMessage email = new EmailMessage();
                email.EmailFormat = EmailFormatEnum.Default;
                email.Recipients  = AdministratorEmail;
                email.From        = from;
                email.Subject     = GetString("RegistrationForm.EmailSubject");

                try
                {
                    EmailSender.SendEmailWithTemplateText(currentSiteName, email, template, resolver, true);
                }
                catch
                {
                    EventLogProvider.LogEvent(EventType.ERROR, "Membership", "RegistrationApprovalEmail");
                }
            }
            else
            {
                EventLogProvider.LogEvent(EventType.ERROR, "RegistrationApproval", "EmailSenderNotSpecified");
            }
        }
    }
Exemplo n.º 13
0
    /// <summary>
    /// Returns true if given path is excluded from URL rewriting.
    /// </summary>
    /// <param name="requestPath">Path to be checked</param>
    public static bool IsExcluded(string requestPath)
    {
        string customExcludedPaths = "";

        // Get Custom excluded URLs path
        if (SiteContext.CurrentSite != null && SiteContext.CurrentSiteName != null && SettingsKeyInfoProvider.GetValue(SiteContext.CurrentSiteName + ".CMSExcludedURLs") != null)
        {
            customExcludedPaths = SettingsKeyInfoProvider.GetValue(SiteContext.CurrentSiteName + ".CMSExcludedURLs");
        }

        return(URLHelper.IsExcluded(requestPath, customExcludedPaths));
    }
Exemplo n.º 14
0
 /// <summary>
 /// Replaces standard HTML tags by special AMP HTML tags and appends import scripts for custom elements
 /// </summary>
 /// <param name="doc">The complete HtmlDocument</param>
 private void ReplaceRegularTagsByAmpTags(HtmlDocument doc)
 {
     ReplaceElement(doc, Constants.XPATH_IMG, Constants.XPATH_IMG_REPLACEMENT);
     if (ReplaceElement(doc, Constants.XPATH_VIDEO, Constants.XPATH_VIDEO_REPLACEMENT))
     {
         string ampCustomVideo = String.Format(Constants.AMP_CUSTOM_ELEMENT_AMP_VIDEO, SettingsKeyInfoProvider.GetValue(SiteContext.CurrentSiteName + ".AMPFilterVideoScriptUrl"));
         customElementsScripts += ampCustomVideo + Constants.NEW_LINE;
     }
     if (ReplaceElement(doc, Constants.XPATH_AUDIO, Constants.XPATH_AUDIO_REPLACEMENT))
     {
         string ampCustomAudio = String.Format(Constants.AMP_CUSTOM_ELEMENT_AMP_AUDIO, SettingsKeyInfoProvider.GetValue(SiteContext.CurrentSiteName + ".AMPFilterAudioScriptUrl"));
         customElementsScripts += ampCustomAudio + Constants.NEW_LINE;
     }
     if (ReplaceElement(doc, Constants.XPATH_IFRAME, Constants.XPATH_IFRAME_REPLACEMENT))
     {
         string ampCustomIframe = String.Format(Constants.AMP_CUSTOM_ELEMENT_AMP_IFRAME, SettingsKeyInfoProvider.GetValue(SiteContext.CurrentSiteName + ".AMPFilterIframeScriptUrl"));
         customElementsScripts += ampCustomIframe + Constants.NEW_LINE;
     }
 }
Exemplo n.º 15
0
    /// <summary>
    /// Initializes the control properties.
    /// </summary>
    protected void SetupControl()
    {
        if (!StopProcessing)
        {
            plcError.Visible = false;

            // Check if OpenID module is enabled
            if (!SettingsKeyInfoProvider.GetBoolValue(SiteContext.CurrentSiteName + ".CMSEnableOpenID") && !plcError.Visible)
            {
                // Error label is displayed only in Design mode
                if (PortalContext.IsDesignMode(PortalContext.ViewMode))
                {
                    StringBuilder parameter = new StringBuilder();
                    parameter.Append(UIElementInfoProvider.GetApplicationNavigationString("cms", "Settings") + " -> ");
                    parameter.Append(GetString("settingscategory.cmsmembership") + " -> ");
                    parameter.Append(GetString("settingscategory.cmsmembershipauthentication") + " -> ");
                    parameter.Append(GetString("settingscategory.cmsopenid"));
                    if (MembershipContext.AuthenticatedUser.CheckPrivilegeLevel(UserPrivilegeLevelEnum.GlobalAdmin))
                    {
                        // Make it link for Admin
                        parameter.Insert(0, "<a href=\"" + URLHelper.GetAbsoluteUrl(ApplicationUrlHelper.GetApplicationUrl("cms", "settings")) + "\" target=\"_top\">");
                        parameter.Append("</a>");
                    }

                    lblError.Text      = String.Format(GetString("mem.openid.disabled"), parameter.ToString());
                    plcError.Visible   = true;
                    plcContent.Visible = false;
                }
                // In other modes is webpart hidden
                else
                {
                    Visible = false;
                }
            }

            // Display webpart when no error occured
            if (!plcError.Visible && Visible)
            {
                if (!AuthenticationHelper.IsAuthenticated())
                {
                    plcPasswordNew.Visible  = AllowFormsAuthentication;
                    pnlExistingUser.Visible = AllowExistingUser;

                    // Initialize OpenID session
                    response = (Dictionary <string, object>)SessionHelper.GetValue(SESSION_NAME_USERDATA);

                    userProviderUrl = ValidationHelper.GetString(SessionHelper.GetValue(SESSION_NAME_URL), null);

                    // Check that OpenID is not already registered
                    if (response != null)
                    {
                        UserInfo ui = OpenIDUserInfoProvider.GetUserInfoByOpenID((string)response["ClaimedIdentifier"]);

                        // OpenID is already registered to some user
                        if (ui != null)
                        {
                            plcContent.Visible = false;
                            plcError.Visible   = true;
                            lblError.Text      = GetString("mem.openid.openidregistered");
                        }
                    }

                    // There is no OpenID response object stored in session - hide all
                    if (response == null)
                    {
                        if (HideForNoOpenID)
                        {
                            Visible = false;
                        }
                    }
                    else if (!RequestHelper.IsPostBack())
                    {
                        LoadData();
                    }
                }
                // Hide webpart for authenticated users
                else
                {
                    Visible = false;
                }
            }
        }
        // Hide control when StopProcessing = TRUE
        else
        {
            Visible = false;
        }
    }
    /// <summary>
    /// Checks status of current user.
    /// </summary>
    protected void CheckStatus()
    {
        // Get current site name
        string siteName = SiteContext.CurrentSiteName;
        string error    = null;

        // Check return URL
        string returnUrl = QueryHelper.GetString("returnurl", null);

        returnUrl = HttpUtility.UrlDecode(returnUrl);

        // Get current URL
        string currentUrl = RequestContext.CurrentURL;

        currentUrl = URLHelper.RemoveParameterFromUrl(currentUrl, "oauth_token");
        currentUrl = URLHelper.RemoveParameterFromUrl(currentUrl, "oauth_verifier");

        // Get LinkedIn response status
        switch (linkedInHelper.CheckStatus(RequireFirstName, RequireLastName, RequireBirthDate, null))
        {
        // User is authenticated
        case LinkedInHelper.RESPONSE_AUTHENTICATED:
            // LinkedIn profile Id not found  = save new user
            if (UserInfoProvider.GetUserInfoByLinkedInID(linkedInHelper.MemberId) == null)
            {
                string additionalInfoPage = SettingsKeyInfoProvider.GetValue(siteName + ".CMSRequiredLinkedInPage").Trim();

                // No page set, user can be created
                if (String.IsNullOrEmpty(additionalInfoPage))
                {
                    // Register new user
                    UserInfo ui = AuthenticationHelper.AuthenticateLinkedInUser(linkedInHelper.MemberId, linkedInHelper.FirstName, linkedInHelper.LastName, siteName, true, true, ref error);

                    // If user was successfully created
                    if (ui != null)
                    {
                        if (linkedInHelper.BirthDate != DateTimeHelper.ZERO_TIME)
                        {
                            ui.UserSettings.UserDateOfBirth = linkedInHelper.BirthDate;
                        }

                        UserInfoProvider.SetUserInfo(ui);

                        // If user is enabled
                        if (ui.Enabled)
                        {
                            // Create authentication cookie
                            AuthenticationHelper.SetAuthCookieWithUserData(ui.UserName, true, Session.Timeout, new[] { "linkedinlogin" });

                            MembershipActivityLogger.LogLogin(ui.UserName, DocumentContext.CurrentDocument);
                        }

                        // Notify administrator
                        if (NotifyAdministrator && !String.IsNullOrEmpty(FromAddress) && !String.IsNullOrEmpty(ToAddress))
                        {
                            AuthenticationHelper.NotifyAdministrator(ui, FromAddress, ToAddress);
                        }

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

                        MembershipActivityLogger.LogRegistration(ui.UserName, DocumentContext.CurrentDocument);
                    }

                    // Redirect when authentication was successful
                    if (String.IsNullOrEmpty(error))
                    {
                        if (URLHelper.IsLocalUrl(returnUrl))
                        {
                            URLHelper.Redirect(returnUrl);
                        }
                        else
                        {
                            URLHelper.Redirect(currentUrl);
                        }
                    }
                    // Display error otherwise
                    else
                    {
                        lblError.Text    = error;
                        lblError.Visible = true;
                    }
                }
                // Additional information page is set
                else
                {
                    // Store user object in session for additional use
                    string response = (linkedInHelper.LinkedInResponse != null) ? linkedInHelper.LinkedInResponse.OuterXml : null;
                    SessionHelper.SetValue(SESSION_NAME_USERDATA, response);

                    // Redirect to additional info page
                    string targetURL = URLHelper.GetAbsoluteUrl(additionalInfoPage);

                    if (URLHelper.IsLocalUrl(returnUrl))
                    {
                        // Add return URL to parameter
                        targetURL = URLHelper.AddParameterToUrl(targetURL, "returnurl", HttpUtility.UrlEncode(returnUrl));
                    }
                    URLHelper.Redirect(UrlResolver.ResolveUrl(targetURL));
                }
            }
            // LinkedIn profile id is in DB
            else
            {
                // Login existing user
                UserInfo ui = AuthenticationHelper.AuthenticateLinkedInUser(linkedInHelper.MemberId, linkedInHelper.FirstName, linkedInHelper.LastName, siteName, false, true, ref error);

                if ((ui != null) && (ui.Enabled))
                {
                    // Create authentication cookie
                    AuthenticationHelper.SetAuthCookieWithUserData(ui.UserName, true, Session.Timeout, new[] { "linkedinlogin" });

                    MembershipActivityLogger.LogLogin(ui.UserName, DocumentContext.CurrentDocument);

                    // Redirect user
                    if (URLHelper.IsLocalUrl(returnUrl))
                    {
                        URLHelper.Redirect(UrlResolver.ResolveUrl(URLHelper.GetAbsoluteUrl(returnUrl)));
                    }
                    else
                    {
                        URLHelper.Redirect(currentUrl);
                    }
                }
                // Display error which occurred during authentication process
                else if (!String.IsNullOrEmpty(error))
                {
                    lblError.Text    = error;
                    lblError.Visible = true;
                }
                // Otherwise is user disabled
                else
                {
                    lblError.Text    = GetString("membership.userdisabled");
                    lblError.Visible = true;
                }
            }
            break;

        // No authentication, do nothing
        case LinkedInHelper.RESPONSE_NOTAUTHENTICATED:
            break;
        }
    }
Exemplo n.º 17
0
    /// <summary>
    /// Handles btnOkNew click, creates new user and joins it with openID token.
    /// </summary>
    protected void btnOkNew_Click(object sender, EventArgs e)
    {
        if (response != null)
        {
            // Validate entered values
            string errorMessage = new Validator().IsRegularExp(txtUserNameNew.Text, "^([a-zA-Z0-9_\\-\\.@]+)$", GetString("mem.openid.fillcorrectusername"))
                                  .IsEmail(txtEmail.Text, GetString("mem.openid.fillvalidemail")).Result;
            string siteName = SiteContext.CurrentSiteName;
            string password = passStrength.Text;

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

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

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

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

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

                // User with given username is already registered
                if (ui != null)
                {
                    plcError.Visible = true;
                    lblError.Text    = GetString("mem.openid.usernameregistered");
                }
                else
                {
                    string error = DisplayMessage;
                    // Register new user
                    ui             = AuthenticationHelper.AuthenticateOpenIDUser((string)response["ClaimedIdentifier"], ValidationHelper.GetString(SessionHelper.GetValue(SESSION_NAME_URL), null), siteName, true, false, ref error);
                    DisplayMessage = error;

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

                        // Load values submitted by OpenID provider
                        // Load date of birth
                        DateTime birthdate = (DateTime)response["BirthDate"];
                        if (birthdate != DateTime.MinValue)
                        {
                            ui.UserSettings.UserDateOfBirth = birthdate;
                        }
                        // Load default country
                        var culture = (System.Globalization.CultureInfo)response["Culture"];
                        if (culture != null)
                        {
                            ui.PreferredCultureCode = culture.Name;
                        }
                        // Nick name
                        string nick = (string)response["Nickname"];
                        if (!String.IsNullOrEmpty(nick))
                        {
                            ui.UserSettings.UserNickName = nick;
                        }
                        // Full name
                        string full = (string)response["FullName"];
                        if (!String.IsNullOrEmpty(full))
                        {
                            ui.FullName = full;
                        }
                        // User gender
                        var gender = (int?)response["UserGender"];
                        if (gender != null)
                        {
                            ui.UserSettings.UserGender = (int)gender;
                        }
                        // Set password
                        if (plcPasswordNew.Visible)
                        {
                            UserInfoProvider.SetPassword(ui, password);

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

                        // Set user
                        UserInfoProvider.SetUserInfo(ui);

                        // Clear used session
                        SessionHelper.Remove(SESSION_NAME_URL);
                        SessionHelper.Remove(SESSION_NAME_USERDATA);

                        AuthenticationHelper.SendRegistrationEmails(ui, ApprovalPage, true, SendWelcomeEmail);

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

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

                        MembershipActivityLogger.LogRegistration(ui.UserName, DocumentContext.CurrentDocument);

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

                        if (!String.IsNullOrEmpty(DisplayMessage))
                        {
                            lblInfo.Visible = true;
                            lblInfo.Text    = DisplayMessage;
                            plcForm.Visible = false;
                        }
                        else
                        {
                            URLHelper.Redirect("~/Default.aspx");
                        }
                    }
                }
            }
            // Validation failed - display error message
            else
            {
                lblError.Text    = errorMessage;
                plcError.Visible = true;
            }
        }
    }
Exemplo n.º 18
0
    /// <summary>
    /// Initializes the control properties.
    /// </summary>
    protected void SetupControl()
    {
        if (StopProcessing)
        {
            // Do nothing
        }
        else
        {
            if (SettingsKeyInfoProvider.GetBoolValue(SiteContext.CurrentSiteName + ".CMSEnableWindowsLiveID"))
            {
                string siteName = SiteContext.CurrentSiteName;
                if (!string.IsNullOrEmpty(siteName))
                {
                    // Get LiveID settings
                    string appId  = SettingsKeyInfoProvider.GetStringValue(siteName + ".CMSApplicationID");
                    string secret = SettingsKeyInfoProvider.GetStringValue(siteName + ".CMSApplicationSecret");

                    if (!WindowsLiveLogin.UseServerSideAuthorization)
                    {
                        // Add windows live ID script
                        ScriptHelper.RegisterClientScriptInclude(Page, typeof(string), "WLScript", LIVE_CONNECT_API_URL);

                        // Add login functions
                        String loginLiveIDClientScript = @"

                            function signUserIn() {
                                var scopesArr = ['wl.signin'];
                                WL.login({ scope: scopesArr });
                            }
                    
                            function refreshLiveID(param)
                            {
                                " + ControlsHelper.GetPostBackEventReference(btnHidden, "#").Replace("'#'", "param") + @" 
                            }                                       
                        ";

                        ScriptHelper.RegisterClientScriptBlock(this, typeof(string), "ClientInitLiveIDScript", ScriptHelper.GetScript(loginLiveIDClientScript));
                    }

                    // Check valid Windows LiveID parameters
                    if ((appId == string.Empty) || (secret == string.Empty))
                    {
                        lblError.Visible = true;
                        lblError.Text    = GetString("liveid.incorrectsettings");
                        return;
                    }

                    WindowsLiveLogin wll = new WindowsLiveLogin(appId, secret);

                    // If user is already authenticated
                    if (AuthenticationHelper.IsAuthenticated())
                    {
                        // If signout should be visible and user has LiveID registered

                        if (ShowSignOut && !String.IsNullOrEmpty(MembershipContext.AuthenticatedUser.UserSettings.WindowsLiveID))
                        {
                            // Get data from auth cookie
                            string[] userData = AuthenticationHelper.GetUserDataFromAuthCookie();

                            // Check if user has truly logged in by LiveID
                            if ((userData != null) && (Array.IndexOf(userData, "liveidlogin") >= 0))
                            {
                                // Redirect to Windows Live and back to "home" page
                                string defaultAliasPath = SettingsKeyInfoProvider.GetStringValue(siteName + ".CMSDefaultAliasPath");
                                string url    = DocumentURLProvider.GetUrl(defaultAliasPath);
                                string navUrl = wll.GetLogoutUrl(URLHelper.GetAbsoluteUrl(url));

                                // If text is set use text/button link
                                if (!string.IsNullOrEmpty(SignOutText))
                                {
                                    // Button link
                                    if (ShowAsButton)
                                    {
                                        btnSignOut.CommandArgument = navUrl;
                                        btnSignOut.Text            = SignOutText;
                                        btnSignOut.Visible         = true;
                                    }
                                    // Text link
                                    else
                                    {
                                        btnSignOutLink.CommandArgument = navUrl;
                                        btnSignOutLink.Text            = SignOutText;
                                        btnSignOutLink.Visible         = true;
                                    }
                                }
                                // Image link
                                else
                                {
                                    btnSignOutImage.CommandArgument = navUrl;
                                    btnSignOutImage.ImageUrl        = ResolveUrl(SignOutImageURL);
                                    btnSignOutImage.Visible         = true;
                                    btnSignOut.Text = GetString("webparts_membership_signoutbutton.signout");
                                }
                            }
                        }
                        else
                        {
                            Visible = false;
                        }
                    }
                    // Sign In
                    else
                    {
                        // Create return URL
                        string returnUrl = QueryHelper.GetText("returnurl", "");
                        returnUrl = (returnUrl == String.Empty) ? RequestContext.CurrentURL : returnUrl;

                        // Create parameters for LiveID request URL
                        String[] parameters = new String[3];
                        parameters[0] = returnUrl;
                        parameters[1] = TrackConversionName;
                        parameters[2] = ConversionValue.ToString();
                        SessionHelper.SetValue("LiveIDInformtion", parameters);

                        returnUrl = wll.GetLoginUrl();

                        // Get App ID
                        appId = SettingsKeyInfoProvider.GetStringValue(siteName + ".CMSApplicationID");

                        // Create full LiveID request URL
                        string navUrl = AUTHORIZATION_URL + "?client_id=" + appId + "&redirect=true&scope=wl.signin&response_type=code&redirect_uri=" + HttpUtility.UrlEncode(returnUrl);

                        // If text is set use text/button link
                        if (!string.IsNullOrEmpty(SignInText))
                        {
                            // Button link
                            if (ShowAsButton)
                            {
                                AssignButtonControl(navUrl, returnUrl, appId);
                                btnSignIn.Text = SignInText;
                            }
                            // Text link
                            else
                            {
                                AssignHyperlinkControl(navUrl, returnUrl, appId);
                                lnkSignIn.Text = SignInText;
                            }
                        }
                        // Image link
                        else
                        {
                            AssignHyperlinkControl(navUrl, returnUrl, appId);
                            lnkSignIn.ImageUrl = ResolveUrl(SignInImageURL);
                            lnkSignIn.Text     = GetString("webparts_membership_signoutbutton.signin");
                        }
                    }
                }
            }
            else
            {
                // Error label is displayed in Design mode when Windows Live ID is disabled
                if (PortalContext.IsDesignMode(PortalContext.ViewMode))
                {
                    StringBuilder parameter = new StringBuilder();
                    parameter.Append(UIElementInfoProvider.GetApplicationNavigationString("cms", "Settings") + " -> ");
                    parameter.Append(GetString("settingscategory.cmsmembership") + " -> ");
                    parameter.Append(GetString("settingscategory.cmsmembershipauthentication") + " -> ");
                    parameter.Append(GetString("settingscategory.cmswindowsliveid"));
                    if (MembershipContext.AuthenticatedUser.CheckPrivilegeLevel(UserPrivilegeLevelEnum.GlobalAdmin))
                    {
                        // Make it link for Admin
                        parameter.Insert(0, "<a href=\"" + URLHelper.GetAbsoluteUrl(UIContextHelper.GetApplicationUrl("cms", "settings")) + "\" target=\"_top\">");
                        parameter.Append("</a>");
                    }

                    lblError.Text    = String.Format(GetString("mem.liveid.disabled"), parameter);
                    lblError.Visible = true;
                }
                else
                {
                    Visible = false;
                }
            }
        }
    }
Exemplo n.º 19
0
    protected void menuNew_OnReloadData(object sender, EventArgs e)
    {
        int nodeId = ValidationHelper.GetInteger(menuNew.Parameter, 0);

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

        plcNewVariant.Visible = false;

        if (node != null)
        {
            if (CurrentUser.IsAuthorizedToCreateNewDocument(node, null))
            {
                DocumentTypeScopeInfo scope = DocumentTypeScopeInfoProvider.GetScopeInfo(node);
                if (scope != null)
                {
                    plcNewLink.Visible = scope.ScopeAllowLinks;
                }

                // AB test variant settings
                if (SettingsKeyInfoProvider.GetBoolValue(SiteContext.CurrentSiteName + ".CMSABTestingEnabled") &&
                    EnableABTestVariant &&
                    CurrentUser.IsAuthorizedPerResource("cms.ABTest", "Read") &&
                    ModuleEntryManager.IsModuleLoaded(ModuleName.ONLINEMARKETING) &&
                    ResourceSiteInfoProvider.IsResourceOnSite("CMS.ABTest", SiteContext.CurrentSiteName) &&
                    LicenseHelper.CheckFeature(RequestContext.CurrentDomain, FeatureEnum.ABTesting) &&
                    (node.NodeAliasPath != "/") &&
                    (node.NodeClassName != "CMS.Folder") &&
                    ((scope == null) || scope.ScopeAllowABVariant) &&
                    CurrentUser.IsAuthorizedToCreateNewDocument(node, node.ClassName))
                {
                    plcNewVariant.Visible = true;
                }

                pnlSepNewLinkVariant.Visible = (plcNewVariant.Visible || plcNewLink.Visible);

                string where = "ClassID IN (SELECT ChildClassID FROM CMS_AllowedChildClasses WHERE ParentClassID=" + ValidationHelper.GetInteger(node.GetValue("NodeClassID"), 0) + ") " +
                               "AND ClassID IN (SELECT ClassID FROM CMS_ClassSite WHERE SiteID = " + SiteContext.CurrentSiteID + ")";

                if (!string.IsNullOrEmpty(DocumentTypeWhere))
                {
                    where = SqlHelper.AddWhereCondition(where, DocumentTypeWhere);
                }

                if (scope != null)
                {
                    // Apply document type scope
                    where = SqlHelper.AddWhereCondition(where, DocumentTypeScopeInfoProvider.GetScopeClassWhereCondition(scope));
                }

                // Get the allowed child classes
                DataSet ds = DocumentTypeHelper.GetDocumentTypeClasses()
                             .Where(where)
                             .OrderBy(DocumentTypeOrderBy)
                             .TopN(50)
                             .Columns("ClassID", "ClassName", "ClassDisplayName", "(CASE WHEN (ClassName = 'CMS.MenuItem' OR ClassName = 'CMS.Wireframe')  THEN 0 ELSE 1 END) AS MenuItemOrder");

                var rows = new List <DataRow>();

                if (!DataHelper.DataSourceIsEmpty(ds))
                {
                    // Check user permissions for "Create" permission
                    bool hasNodeAllowCreate            = (CurrentUser.IsAuthorizedPerTreeNode(node, NodePermissionsEnum.Create) == AuthorizationResultEnum.Allowed);
                    bool isAuthorizedToCreateInContent = CurrentUser.IsAuthorizedPerResource("CMS.Content", "Create");

                    DataTable resultTable = ds.Tables[0].DefaultView.ToTable();

                    for (int i = 0; i < resultTable.Rows.Count; ++i)
                    {
                        DataRow dr  = resultTable.Rows[i];
                        string  doc = ValidationHelper.GetString(DataHelper.GetDataRowValue(dr, "ClassName"), "");

                        // Document type is not allowed, remove it from the data set
                        if (!isAuthorizedToCreateInContent && !CurrentUser.IsAuthorizedPerClassName(doc, "Create") && (!CurrentUser.IsAuthorizedPerClassName(doc, "CreateSpecific") || !hasNodeAllowCreate))
                        {
                            rows.Add(dr);
                        }
                        else if (doc.EqualsCSafe("cms.wireframe", true) && !CurrentUser.IsAuthorizedPerResource("CMS.Design", "Wireframing"))
                        {
                            rows.Add(dr);
                        }
                    }

                    // Remove the document types
                    foreach (DataRow dr in rows)
                    {
                        resultTable.Rows.Remove(dr);
                    }

                    bool classesRemoved = false;

                    // Leave only first 15 rows
                    while (resultTable.Rows.Count > 15)
                    {
                        resultTable.Rows.RemoveAt(resultTable.Rows.Count - 1);
                        classesRemoved = true;
                    }

                    if (!DataHelper.DataSourceIsEmpty(resultTable))
                    {
                        // Add show more item
                        if (classesRemoved)
                        {
                            DataRow dr = resultTable.NewRow();
                            dr["ClassID"]          = 0;
                            dr["ClassName"]        = "more";
                            dr["ClassDisplayName"] = ResHelper.GetString("class.showmore");
                            resultTable.Rows.InsertAt(dr, resultTable.Rows.Count);
                        }

                        // Create temp column
                        int        rowCount  = resultTable.Rows.Count;
                        DataColumn tmpColumn = new DataColumn("Count");
                        tmpColumn.DefaultValue = rowCount;
                        resultTable.Columns.Add(tmpColumn);

                        repNew.DataSource = resultTable;
                        repNew.DataBind();
                    }
                    else
                    {
                        DisplayErrorMessage(scope != null ? "Content.ScopeApplied" : "Content.NoPermissions");
                    }
                }
                else
                {
                    DisplayErrorMessage(scope != null ? "Content.ScopeApplied" : "NewMenu.NoChildAllowed");
                }
            }
            else
            {
                DisplayErrorMessage("Content.NoPermissions");
            }
        }
    }
    /// <summary>
    /// Reloads control.
    /// </summary>
    public void ReloadData()
    {
        var where = new WhereCondition(WhereCondition);

        var siteName    = SiteID > 0 ? SiteInfoProvider.GetSiteName(SiteID) : SiteContext.CurrentSiteName;
        var allowGlobal = SettingsKeyInfoProvider.GetBoolValue(siteName + ".cmscmglobalconfiguration");

        uniselector.AllowAll = AllowAllItem;

        if (DisplayAll || DisplaySiteOrGlobal)
        {
            // Display all site and global statuses
            if (DisplayAll && allowGlobal)
            {
                // No WHERE condition required
            }
            // Display current site and global statuses
            else if (DisplaySiteOrGlobal && allowGlobal && (SiteID > 0))
            {
                where.WhereEqualsOrNull("AccountStatusSiteID", SiteID);
            }
            // Current site
            else if (SiteID > 0)
            {
                where.WhereEquals("AccountStatusSiteID", SiteID);
            }
            // Display global statuses
            else if (allowGlobal)
            {
                where.WhereNull("AccountStatusSiteID");
            }

            // Don't display anything
            if (String.IsNullOrEmpty(where.WhereCondition) && !DisplayAll)
            {
                where.NoResults();
            }
        }
        // Display either global or current site statuses
        else
        {
            // Current site
            if (SiteID > 0)
            {
                where.WhereEquals("AccountStatusSiteID", SiteID);
            }
            // Display global statuses
            else if (((SiteID == UniSelector.US_GLOBAL_RECORD) || (SiteID == UniSelector.US_NONE_RECORD)) && allowGlobal)
            {
                where.WhereNull("AccountStatusSiteID");
            }
            // Don't display anything
            if (String.IsNullOrEmpty(where.WhereCondition))
            {
                where.NoResults();
            }
        }

        // Do not add condition to empty condition which allows everything
        if (!String.IsNullOrEmpty(where.WhereCondition))
        {
            string status = ValidationHelper.GetString(Value, "");
            if (!String.IsNullOrEmpty(status))
            {
                where.Or().WhereEquals(uniselector.ReturnColumnName, status);
            }
        }

        uniselector.WhereCondition = where.ToString(expand: true);
        uniselector.Reload(true);
    }
Exemplo n.º 21
0
    private void btnItem_Click(object sender, EventArgs e)
    {
        // Check if should send password
        if (IsForgottenPassword)
        {
            SetForgottenPasswordMode();

            TextBox txtUserName = (TextBox)Login1.FindControl("UserName");
            if ((txtUserName != null) && !string.IsNullOrEmpty(txtUserName.Text.Trim()))
            {
                // Reset password
                string siteName = SiteContext.CurrentSiteName;
                bool   success;
                string result;

                // Prepare URL to which may user return after password reset
                string returnUrl = RequestContext.CurrentURL;
                if (!string.IsNullOrEmpty(Login1.UserName))
                {
                    returnUrl = URLHelper.AddParameterToUrl(returnUrl, "username", Login1.UserName);
                }

                result = AuthenticationHelper.ForgottenEmailRequest(txtUserName.Text.Trim(), siteName, "Logon page", SettingsKeyInfoProvider.GetValue(siteName + ".CMSSendPasswordEmailsFrom"), null, AuthenticationHelper.GetResetPasswordUrl(siteName), out success, returnUrl);
                if (!success)
                {
                    DisplayError(result);
                }
                else
                {
                    DisplayWarning(result);
                }
            }
            else
            {
                DisplayError(GetString("logonform.nouser"));
            }
        }
    }
Exemplo n.º 22
0
    /// <summary>
    /// Initializes the controls.
    /// </summary>
    private void SetupControls()
    {
        // If the web part shouldn't proceed further
        if (StopProcessing)
        {
            msgBoard.BoardProperties.StopProcessing = true;
            Visible = false;
        }
        else
        {
            // Set the message board transformation
            msgBoard.MessageTransformation = MessageTransformation;

            // Set sorting
            msgBoard.OrderBy = String.IsNullOrEmpty(OrderBy) ? "MessageInserted DESC" : OrderBy;

            // Set buttons
            msgBoard.BoardProperties.ShowApproveButton = ShowApprove;
            msgBoard.BoardProperties.ShowDeleteButton  = ShowDelete;
            msgBoard.BoardProperties.ShowEditButton    = ShowEdit;
            msgBoard.BoardProperties.ShowRejectButton  = ShowReject;

            // Set fields
            msgBoard.FormResourcePrefix             = ResourcePrefix;
            msgBoard.BoardProperties.ShowNameField  = ShowNameField;
            msgBoard.BoardProperties.ShowEmailField = ShowEmailField;
            msgBoard.BoardProperties.ShowURLField   = ShowURLField;

            // Set rating
            msgBoard.BoardProperties.EnableContentRating = EnableContentRating;
            msgBoard.BoardProperties.RatingType          = RatingType;
            msgBoard.BoardProperties.MaxRatingValue      = MaxRatingValue;
            msgBoard.BoardProperties.AllowEmptyRating    = AllowEmptyRating;
            msgBoard.BoardProperties.CheckIfUserRated    = CheckIfUserRated;

            // Set caching
            msgBoard.CacheItemName     = CacheItemName;
            msgBoard.CacheMinutes      = CacheMinutes;
            msgBoard.CacheDependencies = CacheDependencies;

            // Set web part only properties
            msgBoard.BoardProperties.BoardEnableAnonymousRead = EnableAnonymousRead;
            msgBoard.BoardProperties.CheckPermissions         = CheckPermissions;
            msgBoard.NoMessagesText = NoMessagesText;

            // Use board properties
            if (BoardObj != null)
            {
                msgBoard.BoardProperties.BoardAccess      = BoardObj.BoardAccess;
                msgBoard.BoardProperties.BoardName        = BoardObj.BoardName;
                msgBoard.BoardProperties.BoardDisplayName = BoardObj.BoardDisplayName;

                msgBoard.BoardProperties.BoardUnsubscriptionUrl   = BoardInfoProvider.GetUnsubscriptionUrl(BoardObj.BoardUnsubscriptionURL, SiteContext.CurrentSiteName);
                msgBoard.BoardProperties.BoardBaseUrl             = (string.IsNullOrEmpty(BoardObj.BoardBaseURL)) ? ValidationHelper.GetString(SettingsKeyInfoProvider.GetValue(SiteContext.CurrentSiteName + ".CMSBoardBaseURL"), "") : BoardObj.BoardBaseURL;
                msgBoard.BoardProperties.BoardEnableSubscriptions = BoardObj.BoardEnableSubscriptions;
                msgBoard.BoardProperties.BoardOpened        = BoardObj.BoardOpened;
                msgBoard.BoardProperties.BoardRequireEmails = BoardObj.BoardRequireEmails;
                msgBoard.BoardProperties.BoardModerated     = BoardObj.BoardModerated;
                msgBoard.BoardProperties.BoardUseCaptcha    = BoardObj.BoardUseCaptcha;
                msgBoard.BoardProperties.BoardOpenedFrom    = BoardObj.BoardOpenedFrom;
                msgBoard.BoardProperties.BoardOpenedTo      = BoardObj.BoardOpenedTo;
                msgBoard.MessageBoardID = BoardObj.BoardID;
            }
            // Use default properties
            else
            {
                // If the board is user and information on current user wasn't supplied hide the web part
                if (((BoardOwner == "user") && (CurrentUser == null)))
                {
                    if (!String.IsNullOrEmpty(NoMessagesText))
                    {
                        msgBoard.NoMessagesText = NoMessagesText;
                    }
                    Visible = false;
                }
                else
                {
                    // Default board- document related continue
                    msgBoard.BoardProperties.BoardAccess = BoardAccess;
                    msgBoard.BoardProperties.BoardOwner  = BoardOwner;
                    msgBoard.BoardProperties.BoardName   = GetBoardName(WebPartName, BoardOwner);

                    string boardDisplayName;
                    if (!String.IsNullOrEmpty(BoardDisplayName))
                    {
                        boardDisplayName = BoardDisplayName;
                    }
                    // Use predefined display name format
                    else
                    {
                        boardDisplayName = DocumentContext.CurrentPageInfo.GetDocumentName() + " (" + DocumentContext.CurrentPageInfo.DocumentNamePath + ")";
                    }
                    // Limit display name length
                    msgBoard.BoardProperties.BoardDisplayName = TextHelper.LimitLength(boardDisplayName, 250, "");

                    msgBoard.BoardProperties.BoardUnsubscriptionUrl   = BoardInfoProvider.GetUnsubscriptionUrl(BoardUnsubscriptionUrl, SiteContext.CurrentSiteName);
                    msgBoard.BoardProperties.BoardBaseUrl             = (string.IsNullOrEmpty(BoardBaseUrl)) ? ValidationHelper.GetString(SettingsKeyInfoProvider.GetValue(SiteContext.CurrentSiteName + ".CMSBoardBaseURL"), "") : BoardBaseUrl;
                    msgBoard.BoardProperties.BoardEnableSubscriptions = BoardEnableSubscriptions;
                    msgBoard.BoardProperties.BoardOpened        = BoardOpened;
                    msgBoard.BoardProperties.BoardRequireEmails = BoardRequireEmails;
                    msgBoard.BoardProperties.BoardModerated     = BoardModerated;
                    msgBoard.BoardProperties.BoardRoles         = BoardRoles;
                    msgBoard.BoardProperties.BoardModerators    = BoardModerators;
                    msgBoard.BoardProperties.BoardUseCaptcha    = BoardUseCaptcha;
                    msgBoard.BoardProperties.BoardOpenedFrom    = BoardOpenedFrom;
                    msgBoard.BoardProperties.BoardOpenedTo      = BoardOpenedTo;
                    msgBoard.BoardProperties.BoardLogActivity   = LogActivity;
                    msgBoard.MessageBoardID = 0;
                }
            }
        }
    }
Exemplo n.º 23
0
    protected void Page_Load(object sender, EventArgs e)
    {
        var previewState = GetPreviewStateFromCookies(MASTERPAGE);

        // Keep current user
        var user = MembershipContext.AuthenticatedUser;

        // Get document node
        tree = new TreeProvider(user);
        node = UIContext.EditedObject as TreeNode;

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

        // Register save changes
        ScriptHelper.RegisterSaveChanges(Page);

        // Save changes support
        bool   confirmChanges = SettingsKeyInfoProvider.GetBoolValue(SiteContext.CurrentSiteName + ".CMSConfirmChanges");
        string script         = string.Empty;

        if (confirmChanges)
        {
            script  = "CMSContentManager.confirmLeave=" + ScriptHelper.GetString(ResHelper.GetString("Content.ConfirmLeave", user.PreferredUICultureCode), true, false) + "; \n";
            script += "CMSContentManager.confirmLeaveShort=" + ScriptHelper.GetString(ResHelper.GetString("Content.ConfirmLeaveShort", user.PreferredUICultureCode), true, false) + "; \n";
        }
        else
        {
            script += "CMSContentManager.confirmChanges = false;";
        }

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

        try
        {
            if (node != null)
            {
                DocumentContext.CurrentPageInfo = PageInfoProvider.GetPageInfo(node.NodeSiteName, node.NodeAliasPath, node.DocumentCulture, null, node.NodeID, false);

                // Title
                string title = DocumentContext.CurrentTitle;
                if (!string.IsNullOrEmpty(title))
                {
                    title = "<title>" + title + "</title>";
                }

                // Body class
                string bodyCss = DocumentContext.CurrentBodyClass;

                if (bodyCss != null && bodyCss.Trim() != "")
                {
                    bodyCss = "class=\"" + bodyCss + "\"";
                }
                else
                {
                    bodyCss = "";
                }

                // Metadata
                string meta = "<meta http-equiv=\"pragma\" content=\"no-cache\" />";

                string description = DocumentContext.CurrentDescription;
                if (description != "")
                {
                    meta += "<meta name=\"description\" content=\"" + description + "\" />";
                }

                string keywords = DocumentContext.CurrentKeyWords;
                if (keywords != "")
                {
                    meta += "<meta name=\"keywords\"  content=\"" + keywords + "\" />";
                }

                // Site style sheet
                string cssSiteSheet = "";

                int stylesheetId = DocumentContext.CurrentPageInfo.DocumentStylesheetID;

                CssStylesheetInfo cssInfo = CssStylesheetInfoProvider.GetCssStylesheetInfo((stylesheetId > 0) ? stylesheetId : SiteContext.CurrentSite.SiteDefaultStylesheetID);

                if (cssInfo != null)
                {
                    cssSiteSheet = CssLinkHelper.GetCssFileLink(CssLinkHelper.GetStylesheetUrl(cssInfo.StylesheetName));
                }

                // Theme CSS files
                string themeCssFiles = "";
                if (cssInfo != null)
                {
                    try
                    {
                        string directory = URLHelper.GetPhysicalPath(string.Format("~/App_Themes/{0}/", cssInfo.StylesheetName));
                        if (Directory.Exists(directory))
                        {
                            foreach (string file in Directory.GetFiles(directory, "*.css"))
                            {
                                themeCssFiles += CssLinkHelper.GetCssFileLink(CssLinkHelper.GetPhysicalCssUrl(cssInfo.StylesheetName, Path.GetFileName(file)));
                            }
                        }
                    }
                    catch
                    {
                    }
                }

                // Add values to page
                mHead = FormatHTML(HighlightHTML(title + meta + cssSiteSheet + themeCssFiles), 2);
                mBody = bodyCss;
            }
        }
        catch
        {
            ShowError(GetString("MasterPage.PageEditErr"));
        }

        LoadData();

        // Add save action
        SaveAction save = new SaveAction();

        save.CommandArgument = ComponentEvents.SAVE_DATA;
        save.CommandName     = ComponentEvents.SAVE_DATA;

        headerActions.ActionsList.Add(save);

        if (pti != null)
        {
            // Disable buttons for no-template
            bool actionsEnabled = (pti.PageTemplateId > 0);

            // Edit layout
            HeaderAction action = new HeaderAction
            {
                Text          = GetString("content.ui.pagelayout"),
                Tooltip       = GetString("pageplaceholder.editlayouttooltip"),
                OnClientClick = "EditLayout();return false;",
                Enabled       = actionsEnabled
            };
            headerActions.ActionsList.Add(action);

            string elemUrl = ApplicationUrlHelper.GetElementDialogUrl("cms.design", "PageTemplate.EditPageTemplate", pti.PageTemplateId);

            // Edit page properties action
            action = new HeaderAction
            {
                Text          = GetString("PageProperties.EditTemplateProperties"),
                Tooltip       = GetString("PageProperties.EditTemplateProperties"),
                OnClientClick = "modalDialog('" + elemUrl + "', 'TemplateSelection', '85%', '85%');return false;",
                Enabled       = actionsEnabled
            };

            CMSPagePlaceholder.RegisterEditLayoutScript(this, pti.PageTemplateId, node.NodeAliasPath, null);
            headerActions.ActionsList.Add(action);

            // Preview
            HeaderAction preview = new HeaderAction
            {
                Text          = GetString("general.preview"),
                OnClientClick = "performToolbarAction('split');return false;",
                Visible       = ((previewState == 0) && !PortalUIHelper.DisplaySplitMode),
                Tooltip       = GetString("preview.tooltip")
            };
            headerActions.ActionsList.Add(preview);

            headerActions.ActionPerformed += headerActions_ActionPerformed;
        }

        RegisterInitScripts(pnlBody.ClientID, pnlMenu.ClientID, false);
    }
Exemplo n.º 24
0
    /// <summary>
    /// Page load.
    /// </summary>
    /// <param name="sender">Sender.</param>
    /// <param name="e">Arguments</param>
    protected void Page_Load(object sender, EventArgs e)
    {
        hash      = QueryHelper.GetString("hash", string.Empty);
        time      = QueryHelper.GetString("datetime", string.Empty);
        policyReq = QueryHelper.GetInteger("policyreq", 0);
        pwdExp    = QueryHelper.GetInteger("exp", 0);

        // Prepare URL of logon page
        string securedAreasLogonUrl = AuthenticationHelper.GetSecuredAreasLogonPage(SiteContext.CurrentSiteName);

        securedAreasLogonUrl = URLHelper.ResolveUrl(securedAreasLogonUrl);

        returnUrl = QueryHelper.GetString("returnurl", securedAreasLogonUrl);

        rfvConfirmPassword.Text = GetString("general.requiresvalue");

        siteName = SiteContext.CurrentSiteName;

        // Get interval from settings
        interval = SettingsKeyInfoProvider.GetDoubleValue("CMSResetPasswordInterval", siteName);

        // Prepare failed message
        string invalidRequestMessage = DataHelper.GetNotEmpty(InvalidRequestText, String.Format(ResHelper.GetString("membership.passwresetfailed"), URLHelper.AddParameterToUrl(securedAreasLogonUrl, "forgottenpassword", "1")));

        // Reset password cancelation
        if (QueryHelper.GetBoolean("cancel", false))
        {
            // Get user info
            UserInfo ui = UserInfoProvider.GetUsersDataWithSettings()
                          .WhereEquals("UserPasswordRequestHash", hash)
                          .FirstObject;

            if (ui != null)
            {
                ui.UserPasswordRequestHash = null;
                UserInfoProvider.SetUserInfo(ui);
                ClearResetRequestID();

                ShowInformation(GetString("membership.passwresetcancelled"));
            }
            else
            {
                ShowError(invalidRequestMessage);
            }

            pnlReset.Visible = false;
            return;
        }

        // Reset password request
        if (!URLHelper.IsPostback())
        {
            if (policyReq > 0)
            {
                ShowInformation(GetString("passwordpolicy.policynotmet") + "<br />" + passStrength.GetPasswordPolicyHint());
            }

            UserInfo ui;

            // Get user info
            int userId = GetResetRequestID();
            if (userId > 0)
            {
                ui = UserInfoProvider.GetUserInfo(userId);
                if (ui != null)
                {
                    // Invalidation forces user info to load user settings from DB and not use cached values.
                    ui.Generalized.Invalidate(false);
                }
            }
            else
            {
                ui = UserInfoProvider.GetUsersDataWithSettings()
                     .WhereEquals("UserPasswordRequestHash", hash).FirstObject;
            }

            // There is nobody to reset password for
            if (ui == null)
            {
                return;
            }

            // Validate request
            ResetPasswordResultEnum result = AuthenticationHelper.ValidateResetPassword(ui, hash, time, interval, "Reset password control");

            // Prepare messages
            string resultMessage = string.Empty;

            // Check result
            switch (result)
            {
            case ResetPasswordResultEnum.Success:
                // Save user to session
                SetResetRequestID(ui.UserID);

                // Delete it from user info
                ui.UserPasswordRequestHash = null;
                UserInfoProvider.SetUserInfo(ui);

                break;

            case ResetPasswordResultEnum.TimeExceeded:
                resultMessage = DataHelper.GetNotEmpty(ExceededIntervalText, String.Format(ResHelper.GetString("membership.passwreqinterval"), URLHelper.AddParameterToUrl(securedAreasLogonUrl, "forgottenpassword", "1")));
                break;

            default:
                resultMessage = invalidRequestMessage;
                break;
            }

            if (!string.IsNullOrEmpty(resultMessage))
            {
                // Show error message
                ShowError(resultMessage);

                pnlReset.Visible = false;
            }
        }
    }
Exemplo n.º 25
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
        ctlAsync.OnFinished   += ctlAsync_OnFinished;
        ctlAsync.OnError      += ctlAsync_OnError;
        ctlAsync.OnRequestLog += ctlAsync_OnRequestLog;
        ctlAsync.OnCancel     += ctlAsync_OnCancel;

        if (!RequestHelper.IsCallback())
        {
            DataSet      allDocs = null;
            TreeProvider tree    = new TreeProvider(currentUser);
            btnCancel.Text = GetString("general.cancel");

            // 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
            {
                string where = "ClassName <> 'CMS.Root'";
                if (!string.IsNullOrEmpty(WhereCondition))
                {
                    where = SqlHelper.AddWhereCondition(where, WhereCondition);
                }
                allDocs = tree.SelectNodes(currentSite.SiteName, parentAliasPath.TrimEnd(new[] { '/' }) + "/%",
                                           TreeProvider.ALL_CULTURES, true, ClassID > 0 ? DataClassInfoProvider.GetClassName(ClassID) : TreeProvider.ALL_CLASSNAMES, where,
                                           "DocumentName", TreeProvider.ALL_LEVELS, false, 0,
                                           TreeProvider.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);

            btnCancel.Attributes.Add("onclick", ctlAsync.GetCancelScript(true) + "return false;");

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

            titleElemAsync.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;
                chkAllCultures.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.GetStringValue(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
                            chkAllCultures.Visible = false;

                            if (!URLHelper.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.IsGlobalAdministrator)
                            {
                                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.NodeClassName.ToLowerCSafe() == "cms.root")
                            {
                                nodeName = HTMLHelper.HTMLEncode(currentSite.DisplayName);
                            }
                            PageTitle.TitleText = GetString("Content.DeleteTitle") + " \"" + HTMLHelper.HTMLEncode(ResHelper.LocalizeString(nodeName)) + "\"";

                            bool showSKUGroup = false;
                            if (NodeHasChildWithProduct(tree, node))
                            {
                                // Deleting product section
                                lblSKUActionInfo.Text = GetString("ContentDelete.SectionAssignedSKUInfo");
                                headDeleteSKU.Text    = GetString("ContentDelete.AssignedSKUs");

                                showSKUGroup = true;
                            }
                            else if (node.HasSKU && authorizedToDeleteSKU)
                            {
                                // Deleting product
                                if (!NodeSharesSKUWithOtherNode(tree, node))
                                {
                                    lblSKUActionInfo.Text = GetString("contentdelete.assignedskuinfo");
                                    headDeleteSKU.Text    = GetString("ContentDelete.AssignedSKU");

                                    showSKUGroup = true;
                                }
                            }

                            pnlDeleteSKU.Visible = showSKUGroup;
                            rblSKUAction.Visible = showSKUGroup;
                        }

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

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

                        if (node.IsRoot())
                        {
                            // Change SEO panel if root is selected
                            pnlSeo.Visible = false;
                        }
                    }
                    else
                    {
                        if (!RequestHelper.IsPostBack())
                        {
                            URLHelper.Redirect(UIHelper.GetInformationUrl("editeddocument.notexists"));
                        }
                        else
                        {
                            // Hide everything
                            pnlContent.Visible = false;
                        }
                    }

                    headQuestion.Text       = GetString("ContentDelete.Question");
                    chkAllCultures.Text     = GetString("ContentDelete.AllCultures");
                    chkDestroy.Text         = GetString("ContentDelete.Destroy");
                    headDeleteDocument.Text = GetString("ContentDelete.Document");
                }
                else if (nodeIds.Count > 1)
                {
                    pnlDocList.Visible = true;
                    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 = ValidationHelper.GetInteger(DataHelper.GetDataRowValue(ds.Tables[0].Rows[0], "NodeParentID"), 0);
                        }
                        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 += DocumentHelper.GetDocumentMarkImage(Page, DocumentMarkEnum.Link);
                                }
                                docList          += "<br />";
                                lblDocuments.Text = docList;

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

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

                                if ((node.HasSKU && IsUserAuthorizedToModifySKU(node)) || NodeHasChildWithProduct(tree, node))
                                {
                                    pnlDeleteSKU.Visible = true;
                                    rblSKUAction.Visible = true;
                                }
                            }
                        }

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

                    headQuestion.Text       = GetString("ContentDelete.QuestionMultiple");
                    PageTitle.TitleText     = GetString("Content.DeleteTitleMultiple");
                    chkAllCultures.Text     = GetString("ContentDelete.AllCulturesMultiple");
                    chkDestroy.Text         = GetString("ContentDelete.DestroyMultiple");
                    headDeleteDocument.Text = GetString("global.pages");
                    headDeleteSKU.Text      = GetString("ContentDelete.AssignedSKUs");
                    lblSKUActionInfo.Text   = GetString("ContentDelete.AssignedSKUsInfo");
                }

                // Init product actions
                if (!RequestHelper.IsPostBack())
                {
                    rblSKUAction.Items.Add(new ListItem(GetString("ContentDelete.SKU.deleteordisable"), "deleteordisable"));
                    rblSKUAction.Items.Add(new ListItem(GetString("ContentDelete.SKU.delete"), "delete"));
                    rblSKUAction.Items.Add(new ListItem(GetString("ContentDelete.SKU.disable"), "disable"));
                    rblSKUAction.Items.Add(new ListItem(GetString("ContentDelete.SKU.noaction"), "noaction"));

                    rblSKUAction.SelectedValue = "deleteordisable";
                }

                lblAltPath.AssociatedControlClientID = selAltPath.PathTextBox.ClientID;

                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.GetStringValue(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 = ValidationHelper.GetString(DataHelper.GetDataRowValue(culture, "CultureCode"), string.Empty);
                        if (!currentUser.IsCultureAllowed(cultureCode, currentSite.SiteName))
                        {
                            denyAllCulturesDeletion = true;
                        }
                    }
                    // If user can't edit all site cultures
                    if (denyAllCulturesDeletion)
                    {
                        // Hide all cultures selector
                        chkAllCultures.Visible = false;
                        chkAllCultures.Checked = false;
                    }
                }
                pnlDeleteDocument.Visible = chkAllCultures.Visible || chkDestroy.Visible;
            }
            else
            {
                // Hide everything
                pnlContent.Visible = false;
            }
        }
    }
Exemplo n.º 26
0
    /// <summary>
    /// Click event of btnOk.
    /// </summary>
    /// <param name="sender">Sender</param>
    /// <param name="e">Arguments</param>
    protected void btnReset_Click(object sender, EventArgs e)
    {
        if ((passStrength.Text.Length > 0) && rfvConfirmPassword.IsValid)
        {
            if (passStrength.Text == txtConfirmPassword.Text)
            {
                // Check policy
                if (passStrength.IsValid())
                {
                    int userId = GetResetRequestID();

                    // Check if password expired
                    if (pwdExp > 0)
                    {
                        UserInfo ui = UserInfoProvider.GetUserInfo(userId);
                        if (!UserInfoProvider.IsUserPasswordDifferent(ui, passStrength.Text))
                        {
                            ShowError(GetString("passreset.newpasswordrequired"));
                            return;
                        }
                    }

                    // Get e-mail address of sender
                    string emailFrom = DataHelper.GetNotEmpty(SendEmailFrom, SettingsKeyInfoProvider.GetValue("CMSSendPasswordEmailsFrom", siteName));

                    // Try to reset password and show result to user
                    bool   success;
                    string resultText = AuthenticationHelper.ResetPassword(hash, time, userId, interval, passStrength.Text, "Reset password control", emailFrom, siteName, null, out success, InvalidRequestText, ExceededIntervalText);

                    // If password reset was successful
                    if (success)
                    {
                        ClearResetRequestID();

                        // Redirect to specified URL
                        if (!string.IsNullOrEmpty(RedirectUrl))
                        {
                            URLHelper.Redirect(RedirectUrl);
                        }

                        // Get proper text
                        ShowConfirmation(DataHelper.GetNotEmpty(SuccessText, resultText));
                        pnlReset.Visible  = false;
                        lblLogonLink.Text = String.Format(GetString("memberhsip.logonlink"), HTMLHelper.EncodeForHtmlAttribute(returnUrl));
                    }
                    else
                    {
                        ShowError(resultText);
                    }
                }
                else
                {
                    ShowError(AuthenticationHelper.GetPolicyViolationMessage(SiteContext.CurrentSiteName));
                }
            }
            else
            {
                ShowError(GetString("passreset.notmatch"));
            }
        }
        else
        {
            ShowError(GetString("general.requiresvalue"));
        }
    }
Exemplo n.º 27
0
    /// <summary>
    /// On btnOK click, save changed password.
    /// </summary>
    protected void btnOK_Click(object sender, EventArgs e)
    {
        UserInfo ui = MembershipContext.AuthenticatedUser;

        if (ui != null)
        {
            // Check match of old password
            if (!UserInfoProvider.IsUserPasswordDifferent(ui, txtExistingPassword.Text))
            {
                if ((!mAllowEmptyPassword) && (DataHelper.IsEmpty(passStrength.Text.Trim())))
                {
                    ShowError(GetString("myaccount.password.emptypassword"));
                }
                else
                {
                    if (passStrength.Text == txtPassword2.Text)
                    {
                        // Check policy
                        if (!passStrength.IsValid())
                        {
                            ShowError(AuthenticationHelper.GetPolicyViolationMessage(SiteContext.CurrentSiteName));
                        }
                        else
                        {
                            // Check if different password is required
                            if (ForceDifferentPassword)
                            {
                                if (!UserInfoProvider.IsUserPasswordDifferent(ui, passStrength.Text))
                                {
                                    ShowError(GetString("passreset.newpasswordrequired"));
                                    return;
                                }
                            }

                            UserInfoProvider.SetPassword(ui.UserName, passStrength.Text);
                            ShowChangesSaved();

                            if (SettingsKeyInfoProvider.GetBoolValue(SiteContext.CurrentSiteName + ".CMSSendPasswordResetConfirmation"))
                            {
                                AuthenticationHelper.SendPasswordResetConfirmation(ui, SiteContext.CurrentSiteName, "Change password control", "Membership.PasswordResetConfirmation");
                            }

                            // Call Password change event
                            if (OnPasswordChange != null)
                            {
                                OnPasswordChange(this, null);
                            }
                        }
                    }
                    else
                    {
                        // New and confirmed password are not equal
                        ShowError(GetString("Administration-User_Edit_Password.PasswordsDoNotMatch"));
                    }
                }
            }
            else
            {
                // Incorrect existing password
                ShowError(GetString("myaccount.password.incorrectexistingpassword"));
            }
        }
    }
 /// <summary>
 /// Returns true if the files are stored in database on the given site.
 /// </summary>
 /// <param name="siteId">Site ID</param>
 protected bool StoreInDatabase(int siteId)
 {
     return(SettingsKeyInfoProvider.GetBoolValue(GetSiteName(siteId) + ".CMSStoreFilesInDatabase"));
 }
Exemplo n.º 29
0
 protected void InsertDefaultOrderStatuses()
 {
     SettingsKeyInfoProvider.SetValue(ECommerceSettings.USE_GLOBAL_ORDER_STATUS, SiteID, false);
     mFakeFactory.InitOrderStatuses().InsertDB();
 }
    /// <summary>
    /// Handles btnOkNew click, creates new user and joins it with liveid token.
    /// </summary>
    protected void btnOkNew_Click(object sender, EventArgs e)
    {
        if (liveUser != null)
        {
            // Validate entered values
            string errorMessage = new Validator().IsRegularExp(txtUserNameNew.Text, "^([a-zA-Z0-9_\\-\\.@]+)$", GetString("mem.liveid.fillcorrectusername"))
                                  .IsEmail(txtEmail.Text, GetString("mem.liveid.fillvalidemail")).Result;

            string password = passStrength.Text.Trim();

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

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

            string siteName = SiteContext.CurrentSiteName;

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

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

            if (errorMessage == String.Empty)
            {
                string userName = txtUserNameNew.Text.Trim();
                // Check if user with given username already exists
                UserInfo ui     = UserInfoProvider.GetUserInfo(userName);
                UserInfo siteui = UserInfoProvider.GetUserInfo(UserInfoProvider.EnsureSitePrefixUserName(userName, SiteContext.CurrentSite));

                // User with given username is already registered
                if ((ui != null) || (siteui != null))
                {
                    plcError.Visible = true;
                    lblError.Text    = GetString("mem.openid.usernameregistered");
                }
                else
                {
                    // Register new user
                    string error = DisplayMessage;
                    ui             = AuthenticationHelper.AuthenticateWindowsLiveUser(liveUser.Id, siteName, false, ref error);
                    DisplayMessage = error;

                    if (ui != null)
                    {
                        // Set additional information
                        ui.UserName = ui.UserNickName = ui.FullName = userName;

                        // Ensure site prefixes
                        if (UserInfoProvider.UserNameSitePrefixEnabled(siteName))
                        {
                            ui.UserName = UserInfoProvider.EnsureSitePrefixUserName(userName, SiteContext.CurrentSite);
                        }

                        ui.Email = txtEmail.Text;

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

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

                        UserInfoProvider.SetUserInfo(ui);

                        // Remove live user object from session, won't be needed
                        Session.Remove("windowsliveloginuser");

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

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

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

                        MembershipActivityLogger.LogRegistration(ui.UserName, DocumentContext.CurrentDocument);

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

                        // Display error message
                        if (!String.IsNullOrEmpty(DisplayMessage))
                        {
                            lblInfo.Visible = true;
                            lblInfo.Text    = DisplayMessage;
                            plcForm.Visible = false;
                        }
                        else
                        {
                            URLHelper.Redirect(ResolveUrl("~/Default.aspx"));
                        }
                    }
                }
            }
            else
            {
                lblError.Text    = errorMessage;
                plcError.Visible = true;
            }
        }
    }