Ejemplo n.º 1
0
    /// <summary>
    /// Provides operations necessary to create and store new attachment.
    /// </summary>
    private void HandleAttachmentUpload(bool fieldAttachment)
    {
        // New attachment
        AttachmentInfo newAttachment = null;

        string message     = string.Empty;
        bool   fullRefresh = false;
        bool   refreshTree = false;

        try
        {
            // Get the existing document
            if (DocumentID != 0)
            {
                // Get document
                node = DocumentHelper.GetDocument(DocumentID, TreeProvider);
                if (node == null)
                {
                    throw new Exception("Given document doesn't exist!");
                }
            }


            #region "Check permissions"

            if (CheckPermissions)
            {
                CheckNodePermissions(node);
            }

            #endregion


            // Check the allowed extensions
            CheckAllowedExtensions();

            // Standard attachments
            if (DocumentID != 0)
            {
                // Check out the document
                if (AutoCheck)
                {
                    // Get original step Id
                    int originalStepId = node.DocumentWorkflowStepID;

                    // Get current step info
                    WorkflowStepInfo si = WorkflowManager.GetStepInfo(node);
                    if (si != null)
                    {
                        // Decide if full refresh is needed
                        bool automaticPublish = wi.WorkflowAutoPublishChanges;
                        // Document is published or archived or uses automatic publish or step is different than original (document was updated)
                        fullRefresh = si.StepIsPublished || si.StepIsArchived || (automaticPublish && !si.StepIsPublished) || (originalStepId != node.DocumentWorkflowStepID);
                    }

                    using (CMSActionContext ctx = new CMSActionContext()
                    {
                        LogEvents = false
                    })
                    {
                        VersionManager.CheckOut(node, node.IsPublished, true);
                    }
                }

                // Handle field attachment
                if (fieldAttachment)
                {
                    // Extension of CMS file before saving
                    string oldExtension = node.DocumentType;

                    newAttachment = DocumentHelper.AddAttachment(node, AttachmentGUIDColumnName, Guid.Empty, Guid.Empty, ucFileUpload.PostedFile, TreeProvider, ResizeToWidth, ResizeToHeight, ResizeToMaxSideSize);
                    // Update attachment field
                    DocumentHelper.UpdateDocument(node, TreeProvider);

                    // Different extension
                    if ((oldExtension != null) && !oldExtension.EqualsCSafe(node.DocumentType, true))
                    {
                        refreshTree = true;
                    }
                }
                // Handle grouped and unsorted attachments
                else
                {
                    // Grouped attachment
                    if (AttachmentGroupGUID != Guid.Empty)
                    {
                        newAttachment = DocumentHelper.AddGroupedAttachment(node, AttachmentGUID, AttachmentGroupGUID, ucFileUpload.PostedFile, TreeProvider, ResizeToWidth, ResizeToHeight, ResizeToMaxSideSize);
                    }
                    // Unsorted attachment
                    else
                    {
                        newAttachment = DocumentHelper.AddUnsortedAttachment(node, AttachmentGUID, ucFileUpload.PostedFile, TreeProvider, ResizeToWidth, ResizeToHeight, ResizeToMaxSideSize);
                    }

                    // Log synchronization task if not under workflow
                    if (wi == null)
                    {
                        DocumentSynchronizationHelper.LogDocumentChange(node, TaskTypeEnum.UpdateDocument, TreeProvider);
                    }
                }

                // Check in the document
                if (AutoCheck)
                {
                    using (CMSActionContext ctx = new CMSActionContext()
                    {
                        LogEvents = false
                    })
                    {
                        VersionManager.CheckIn(node, null, null);
                    }
                }
            }

            // Temporary attachments
            if (FormGUID != Guid.Empty)
            {
                newAttachment = AttachmentInfoProvider.AddTemporaryAttachment(FormGUID, AttachmentGUIDColumnName, AttachmentGUID, AttachmentGroupGUID, ucFileUpload.PostedFile, SiteContext.CurrentSiteID, ResizeToWidth, ResizeToHeight, ResizeToMaxSideSize);
            }

            // Ensure properties update
            if ((newAttachment != null) && !InsertMode)
            {
                AttachmentGUID = newAttachment.AttachmentGUID;
            }

            if (newAttachment == null)
            {
                throw new Exception("The attachment hasn't been created since no DocumentID or FormGUID was supplied.");
            }
        }
        catch (Exception ex)
        {
            // Log the exception
            EventLogProvider.LogException("Content", "UploadAttachment", ex);

            message = ex.Message;
        }
        finally
        {
            string afterSaveScript = string.Empty;

            // Call aftersave javascript if exists
            if (!String.IsNullOrEmpty(AfterSaveJavascript))
            {
                if ((message == string.Empty) && (newAttachment != null))
                {
                    string url      = null;
                    string saveName = URLHelper.GetSafeFileName(newAttachment.AttachmentName, SiteContext.CurrentSiteName);
                    if (node != null)
                    {
                        SiteInfo si = SiteInfoProvider.GetSiteInfo(node.NodeSiteID);
                        if (si != null)
                        {
                            bool usePermanent = SettingsKeyInfoProvider.GetBoolValue(si.SiteName + ".CMSUsePermanentURLs");
                            if (usePermanent)
                            {
                                url = ResolveUrl(AttachmentInfoProvider.GetAttachmentUrl(newAttachment.AttachmentGUID, saveName));
                            }
                            else
                            {
                                url = ResolveUrl(AttachmentInfoProvider.GetAttachmentUrl(saveName, node.NodeAliasPath));
                            }
                        }
                    }
                    else
                    {
                        url = ResolveUrl(AttachmentInfoProvider.GetAttachmentUrl(newAttachment.AttachmentGUID, saveName));
                    }
                    // Calling javascript function with parameters attachments url, name, width, height
                    if (!string.IsNullOrEmpty(AfterSaveJavascript))
                    {
                        Hashtable obj = new Hashtable();
                        if (ImageHelper.IsImage(newAttachment.AttachmentExtension))
                        {
                            obj[DialogParameters.IMG_URL]     = url;
                            obj[DialogParameters.IMG_TOOLTIP] = newAttachment.AttachmentName;
                            obj[DialogParameters.IMG_WIDTH]   = newAttachment.AttachmentImageWidth;
                            obj[DialogParameters.IMG_HEIGHT]  = newAttachment.AttachmentImageHeight;
                        }
                        else if (MediaHelper.IsFlash(newAttachment.AttachmentExtension))
                        {
                            obj[DialogParameters.OBJECT_TYPE]  = "flash";
                            obj[DialogParameters.FLASH_URL]    = url;
                            obj[DialogParameters.FLASH_EXT]    = newAttachment.AttachmentExtension;
                            obj[DialogParameters.FLASH_TITLE]  = newAttachment.AttachmentName;
                            obj[DialogParameters.FLASH_WIDTH]  = DEFAULT_OBJECT_WIDTH;
                            obj[DialogParameters.FLASH_HEIGHT] = DEFAULT_OBJECT_HEIGHT;
                        }
                        else if (MediaHelper.IsAudioVideo(newAttachment.AttachmentExtension))
                        {
                            obj[DialogParameters.OBJECT_TYPE] = "audiovideo";
                            obj[DialogParameters.AV_URL]      = url;
                            obj[DialogParameters.AV_EXT]      = newAttachment.AttachmentExtension;
                            obj[DialogParameters.AV_WIDTH]    = DEFAULT_OBJECT_WIDTH;
                            obj[DialogParameters.AV_HEIGHT]   = DEFAULT_OBJECT_HEIGHT;
                        }
                        else
                        {
                            obj[DialogParameters.LINK_URL]  = url;
                            obj[DialogParameters.LINK_TEXT] = newAttachment.AttachmentName;
                        }

                        // Calling javascript function with parameters attachments url, name, width, height
                        afterSaveScript += ScriptHelper.GetScript(string.Format(@"{5}
                        if (window.{0})
                        {{
                            window.{0}('{1}', '{2}', '{3}', '{4}', obj);
                        }}
                        else if((window.parent != null) && window.parent.{0})
                        {{
                            window.parent.{0}('{1}', '{2}', '{3}', '{4}', obj);
                        }}", AfterSaveJavascript, url, newAttachment.AttachmentName, newAttachment.AttachmentImageWidth, newAttachment.AttachmentImageHeight, CMSDialogHelper.GetDialogItem(obj)));
                    }
                }
                else
                {
                    afterSaveScript += ScriptHelper.GetAlertScript(message);
                }
            }

            // Create attachment info string
            string attachmentInfo = ((newAttachment != null) && (newAttachment.AttachmentGUID != Guid.Empty) && (IncludeNewItemInfo)) ? String.Format("'{0}', ", newAttachment.AttachmentGUID) : "";

            // Ensure message text
            message = HTMLHelper.EnsureLineEnding(message, " ");

            // Call function to refresh parent window
            afterSaveScript += ScriptHelper.GetScript(String.Format(@"
if ((window.parent != null) && (/parentelemid={0}/i.test(window.location.href)) && (window.parent.InitRefresh_{0} != null)){{ 
    window.parent.InitRefresh_{0}({1}, {2}, {3}, {4});
}}",
                                                                    ParentElemID,
                                                                    ScriptHelper.GetString(message.Trim()),
                                                                    (fullRefresh ? "true" : "false"),
                                                                    (refreshTree ? "true" : "false"),
                                                                    attachmentInfo + (InsertMode ? "'insert'" : "'update'")));

            ScriptHelper.RegisterStartupScript(this, typeof(string), "afterSaveScript_" + ClientID, afterSaveScript);
        }
    }
Ejemplo n.º 2
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;
        }
    }
Ejemplo n.º 3
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");
            }
        }
    }
Ejemplo n.º 4
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>
    /// 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);
    }
    /// <summary>
    /// Selects correct value.
    /// </summary>
    private void ReloadData()
    {
        string where = "TranslationServiceEnabled = 1";
        if (!DisplayMachineServices)
        {
            where += " AND TranslationServiceIsMachine = 0";
        }

        // Get services
        var data = TranslationServiceInfoProvider.GetTranslationServices(where, "TranslationServiceIsMachine DESC, TranslationServiceDisplayName ASC", 0, "TranslationServiceDisplayName, TranslationServiceName, TranslationServiceIsMachine, TranslationServiceSupportsPriority, TranslationServiceSupportsInstructions, TranslationServiceSupportsDeadline, TranslationServiceGenerateTargetTag");

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

        bool   allowBinary     = SettingsKeyInfoProvider.GetBoolValue(SiteContext.CurrentSiteName + ".CMSAllowAttachmentTranslation");
        string selected        = SelectedService;
        string lastDisplayName = null;

        int i = 0;

        string machSelectScript = null;

        ltlServices.Text += "<div class=\"radio-list-vertical\">";

        foreach (DataRow dr in data.Tables[0].Rows)
        {
            string codeName = ValidationHelper.GetString(dr["TranslationServiceName"], "");

            // Check availability
            if (!TranslationServiceHelper.IsServiceAvailable(codeName, SiteContext.CurrentSiteName))
            {
                continue;
            }

            if (string.IsNullOrEmpty(selected) && (i == 0))
            {
                selected = codeName;
            }

            bool   isMachine            = ValidationHelper.GetBoolean(dr["TranslationServiceIsMachine"], false);
            string displayName          = ValidationHelper.GetString(dr["TranslationServiceDisplayName"], "");
            bool   supportsInstructions = ValidationHelper.GetBoolean(dr["TranslationServiceSupportsInstructions"], false);
            bool   supportsPriority     = ValidationHelper.GetBoolean(dr["TranslationServiceSupportsPriority"], false);
            bool   supportsDeadline     = ValidationHelper.GetBoolean(dr["TranslationServiceSupportsDeadline"], false);

            if (isMachine && !string.IsNullOrEmpty(MachineServiceSuffix))
            {
                displayName += MachineServiceSuffix;
            }

            string selectScript = string.Format("SelectService({0}, {1}, {2}, {3}, {4}, {5})", ScriptHelper.GetString(codeName), (!isMachine && DisplaySeparateSubmissionOption ? "true" : "false"), (supportsInstructions ? "true" : "false"), (supportsPriority ? "true" : "false"), (!isMachine && allowBinary ? "true" : "false"), (supportsDeadline ? "true" : "false"));

            bool isSelected = selected.Equals(codeName, StringComparison.CurrentCultureIgnoreCase);
            if (isSelected)
            {
                SelectedService = selected;
                if (string.IsNullOrEmpty(machSelectScript))
                {
                    machSelectScript = selectScript;
                }
            }

            string radioBtn = "<div class=\"radio\"><input id=\"rad" + codeName + "\" " + (isSelected ? "checked=\"checked\"" : "") + " type=\"radio\" name=\"services\" value=\"" + codeName + "\" onclick=\"" + selectScript + "\" />";
            radioBtn       += "<label for=\"rad" + codeName + "\">" + HTMLHelper.HTMLEncode(displayName) + "</label></div>";
            lastDisplayName = displayName;

            mAnyServiceAvailable = true;

            ltlServices.Text += radioBtn;
            i++;
        }

        ltlServices.Text += "</div>";

        // If only one service is available, display it in a different way
        if (i == 1)
        {
            DisplayedServiceName = lastDisplayName;
            ltlServices.Text     = DisplayOnlyServiceName ? "<strong>" + HTMLHelper.HTMLEncode(lastDisplayName) + "</strong>" : String.Empty;
        }

        if (!String.IsNullOrEmpty(machSelectScript))
        {
            // Register selection script for first service
            ScriptHelper.RegisterStartupScript(Page, typeof(string), "TranslationServiceSelectorSelection", machSelectScript, true);
        }

        DisplayedServicesCount = i;
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!QueryHelper.ValidateHash("hash") || Parameters == null)
        {
            StopProcessing = true;
            return;
        }

        PageTitle.TitleText = GetString("om.contactrole.select");
        Page.Title          = PageTitle.TitleText;

        // Check if the dialog was opened from mass actions
        isMassAction = Parameters.ContainsKey("ismassaction");
        if (isMassAction)
        {
            siteId = ValidationHelper.GetInteger(Parameters["siteid"], 0);
        }
        else
        {
            int accountContactId = ValidationHelper.GetInteger(Parameters["accountcontactid"], 0);
            aci = AccountContactInfoProvider.GetAccountContactInfo(accountContactId);
            if (aci != null)
            {
                AccountInfo ai = AccountInfoProvider.GetAccountInfo(aci.AccountID);
                if (ai != null)
                {
                    siteId = ai.AccountSiteID;
                }
            }
        }

        // Show all global configuration to authorized users ..
        bool allowGlobal = ConfigurationHelper.AuthorizedReadConfiguration(UniSelector.US_GLOBAL_RECORD, false);

        // .. but just in SiteManager - fake it in CMSDesk so that even Global Admin sees user configuration
        // as Site Admins (depending on settings).
        bool isSiteManager = ValidationHelper.GetBoolean(Parameters["issitemanager"], false);

        allowGlobal &= (isSiteManager || SettingsKeyInfoProvider.GetBoolValue(SiteInfoProvider.GetSiteName(siteId) + ".cmscmglobalconfiguration"));

        bool allowSite;

        if (siteId > 0)
        {
            allowSite = ConfigurationHelper.AuthorizedReadConfiguration(siteId, false);
        }
        else
        {
            allowSite = ConfigurationHelper.AuthorizedReadConfiguration(SiteContext.CurrentSiteID, false);
        }

        // Check read permission
        if ((siteId > 0) && !allowSite && !allowGlobal)
        {
            RedirectToAccessDenied("cms.contactmanagement", "ReadConfiguration");
            return;
        }
        else if ((siteId == 0) && !allowGlobal)
        {
            RedirectToAccessDenied("cms.contactmanagement", "ReadGlobalConfiguration");
            return;
        }

        if (siteId > 0)
        {
            if (allowSite)
            {
                gridElem.WhereCondition = "ContactRoleSiteID = " + siteId;
            }

            // Check if global config is allowed for the site
            if (allowGlobal)
            {
                // Add contact roles from global configuration
                gridElem.WhereCondition = SqlHelper.AddWhereCondition(gridElem.WhereCondition, "ContactRoleSiteID IS NULL", "OR");
            }
        }
        else if ((siteId == 0) && allowGlobal)
        {
            gridElem.WhereCondition = "ContactRoleSiteID IS NULL";
        }

        gridElem.OnExternalDataBound  += gridElem_OnExternalDataBound;
        gridElem.Pager.DefaultPageSize = 10;

        // Display 'Reset' button when 'none' role is allowed
        if (ValidationHelper.GetBoolean(Parameters["allownone"], false))
        {
            btnReset.Visible         = true;
            btnReset.Click          += btn_Click;
            btnReset.CommandArgument = "0";
        }
    }
Ejemplo n.º 8
0
    /// <summary>
    /// OnInit event.
    /// </summary>
    protected override void OnInit(EventArgs e)
    {
        int querySiteID = QueryHelper.GetInteger("siteid", 0);

        // Do not allow other than current site ID out of global scope.
        SiteID = UIContextHelper.IsInGlobalApplicationScope(UIContext.UIElement) ? querySiteID : SiteContext.CurrentSiteID;

        if (File.Exists(HttpContext.Current.Request.MapPath(ResolveUrl(pathToGroupselector))))
        {
            Control ctrl = LoadUserControl(pathToGroupselector);
            if (ctrl != null)
            {
                selectInGroups    = ctrl as FormEngineUserControl;
                ctrl.ID           = "selGroups";
                ctrl              = LoadUserControl(pathToGroupselector);
                selectNotInGroups = ctrl as FormEngineUserControl;
                ctrl.ID           = "selNoGroups";

                plcGroups.Visible = true;
                plcSelectInGroups.Controls.Add(selectInGroups);
                plcSelectNotInGroups.Controls.Add(selectNotInGroups);

                selectNotInGroups.SetValue("UseFriendlyMode", true);
                selectInGroups.IsLiveSite = false;
                selectInGroups.SetValue("UseFriendlyMode", true);
                selectNotInGroups.IsLiveSite = false;
            }
        }

        if (DisplayScore && SettingsKeyInfoProvider.GetBoolValue(SiteContext.CurrentSiteName + ".CMSEnableOnlineMarketing"))
        {
            Control ctrl = LoadUserControl(pathToScoreSelector);
            if (ctrl != null)
            {
                ctrl.ID       = "selectScore";
                scoreSelector = ctrl as FormEngineUserControl;
                if (scoreSelector != null)
                {
                    plcUpdateContent.Controls.Add(scoreSelector);
                    scoreSelector.SetValue("AllowAll", false);
                    scoreSelector.SetValue("AllowEmpty", true);
                }
            }
        }
        else
        {
            plcScore.Visible             = false;
            lblScore.AssociatedControlID = null;
        }

        // Initialize advanced filter dropdownlists
        if (!RequestHelper.IsPostBack())
        {
            InitAllAnyDropDown(drpTypeSelectInRoles);
            InitAllAnyDropDown(drpTypeSelectNotInRoles);
            InitAllAnyDropDown(drpTypeSelectInGroups);
            InitAllAnyDropDown(drpTypeSelectNotInGroups);

            // Init lock account reason DDL
            drpLockReason.Items.Add(new ListItem(GetString("General.selectall"), ""));
            ControlsHelper.FillListControlWithEnum <UserAccountLockEnum>(drpLockReason, "userlist.account");
        }


        base.OnInit(e);

        plcDisplayAnonymous.Visible = ContactManagementPermission && SessionManager.StoreOnlineUsersInDatabase && EnableDisplayingGuests;
        if (!RequestHelper.IsPostBack())
        {
            chkDisplayAnonymous.Checked = DisplayGuestsByDefault;
        }

        siteSelector.DropDownSingleSelect.AutoPostBack = true;
    }
    protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);

        radCopy.Text      = GetString("ContentNewCultureVersion.Copy");
        radEmpty.Text     = GetString("ContentNewCultureVersion.Empty");
        radTranslate.Text = GetString("ContentNewCultureVersion.Translate");

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

        btnCreateDocument.Text   = GetString("ContentNewCultureVersion.Create");
        btnTranslate.Text        = GetString("ContentNewCultureVersion.TranslateButton");
        btnTranslate.Click      += btnTranslate_Click;
        btnCreateDocument.Click += btnCreateDocument_Click;

        if ((NodeID <= 0) || (Node == null))
        {
            return;
        }

        // Fill in the existing culture versions
        bool translationAllowed = SettingsKeyInfoProvider.GetBoolValue(Node.NodeSiteName + ".CMSEnableTranslations") && LicenseHelper.IsFeatureAvailableInUI(FeatureEnum.TranslationServices, ModuleName.TRANSLATIONSERVICES);

        if (translationAllowed)
        {
            var settings = new TranslationSettings();
            settings.TargetLanguages.Add(RequiredCulture);
            translationElem.TranslationSettings = settings;

            translationElem.NodeID = Node.NodeID;
        }
        else
        {
            translationElem.StopProcessing = true;
            plcTranslationServices.Visible = false;
        }

        if (IsAuthorizedToCreateNewDocument())
        {
            EnsureScripts();

            SiteInfo si = SiteInfoProvider.GetSiteInfo(Node.NodeSiteID);
            if (si == null)
            {
                return;
            }

            TreeNode originalNode = Tree.GetOriginalNode(Node);
            copyCulturesElem.UniSelector.DisplayNameFormat = "{% CultureName %}{% if (CultureCode == \"" + CultureHelper.GetDefaultCultureCode(si.SiteName) + "\") { \" \" +\"" + GetString("general.defaultchoice") + "\" } %}";
            copyCulturesElem.AdditionalWhereCondition      = "CultureCode IN (SELECT DocumentCulture FROM CMS_Document WHERE DocumentNodeID = " + originalNode.NodeID + ")";

            if (!MembershipContext.AuthenticatedUser.IsCultureAllowed(RequiredCulture, si.SiteName))
            {
                pnlNewVersion.Visible         = false;
                headNewCultureVersion.Visible = false;
                ShowError(GetString("transman.notallowedcreate"));
            }
        }
        else
        {
            pnlNewVersion.Visible         = false;
            headNewCultureVersion.Visible = false;
            ShowError(GetString("accessdenied.notallowedtocreatenewcultureversion"));
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        int siteID = QueryHelper.GetInteger("siteID", SiteContext.CurrentSiteID);

        bool authorizedForSiteContacts   = CurrentUser.IsAuthorizedPerResource(ModuleName.CONTACTMANAGEMENT, "ReadContacts");
        bool authorizedForGlobalContacts = CurrentUser.IsAuthorizedPerResource(ModuleName.CONTACTMANAGEMENT, "ReadGlobalContacts") && SettingsKeyInfoProvider.GetBoolValue(SiteContext.CurrentSiteName + ".CMSCMGlobalContacts");

        // Check UIProfile
        if (!MembershipContext.AuthenticatedUser.IsAuthorizedPerUIElement("cms.onlinemarketing", "MyContacts", SiteContext.CurrentSiteName))
        {
            RedirectToUIElementAccessDenied("cms.onlinemarketing", "MyContacts");
        }

        // Init site filter when user is authorized for global and site contacts
        if (authorizedForGlobalContacts && authorizedForSiteContacts)
        {
            CurrentMaster.DisplaySiteSelectorPanel = true;

            // Set site selector
            if (!URLHelper.IsPostback())
            {
                siteOrGlobalSelector.SiteID = siteID;
            }

            listContacts.SiteID = siteOrGlobalSelector.SiteID;
        }
        else if (authorizedForSiteContacts)
        {
            // User is authorized only for site contacts so set current site id
            listContacts.SiteID = siteID;
        }
        else if (authorizedForGlobalContacts)
        {
            // User can read only global contacts
            listContacts.SiteID = UniSelector.US_GLOBAL_RECORD;
        }
        else
        {
            // User has no permissions
            RedirectToAccessDenied(ModuleName.CONTACTMANAGEMENT, "ReadContacts|ReadGlobalContacts");
        }

        // Add Refresh button
        PageTitle.HeaderActions.AddAction(new HeaderAction()
        {
            Text        = GetString("general.Refresh"),
            RedirectUrl = "PendingContacts.aspx?siteid=" + listContacts.SiteID
        });
    }
 /// <summary>
 /// Check site settings of all sites.
 /// </summary>
 /// <param name="settingKey">Setting key to be checked for all sites.</param>
 /// <returns> Return true if all sites have that site setting set true. Otherwise returns false.</returns>
 private bool CheckAllSitesSetting(string settingKey)
 {
     return(!SiteInfoProvider.GetSites().Any(site => !SettingsKeyInfoProvider.GetBoolValue(settingKey, site.SiteName)));
 }
 /// <summary>
 /// Returns true if the files are stored in file system on the given site.
 /// </summary>
 /// <param name="siteId">Site ID</param>
 protected bool StoreInFileSystem(int siteId)
 {
     return SettingsKeyInfoProvider.GetBoolValue(GetSiteName(siteId) + ".CMSStoreFilesInFileSystem");
 }
Ejemplo n.º 13
0
    /// <summary>
    /// Translates document(s).
    /// </summary>
    private void Translate(object parameter)
    {
        if (parameter == null || nodeIds.Count < 1)
        {
            return;
        }

        int refreshId = 0;

        TreeProvider tree = new TreeProvider(currentUser);

        tree.AllowAsyncActions = false;

        try
        {
            // Begin log
            AddLog(ResHelper.GetString("contentrequest.starttranslate", currentCulture));

            bool oneSubmission = chkSeparateSubmissions.Checked;

            // Prepare translation settings
            TranslationSettings settings = new TranslationSettings();
            settings.TargetLanguage             = targetCulture;
            settings.TranslateWebpartProperties = SettingsKeyInfoProvider.GetBoolValue(SiteContext.CurrentSiteName + ".CMSTranslateWebpartProperties");
            settings.SourceLanguage             = translationElem.FromLanguage;
            settings.Instructions           = translationElem.Instructions;
            settings.Priority               = translationElem.Priority;
            settings.TranslateAttachments   = translationElem.ProcessBinary;
            settings.ProcessBinary          = translationElem.ProcessBinary;
            settings.TranslationDeadline    = translationElem.Deadline;
            settings.TranslationServiceName = translationElem.SelectedService;

            using (var tr = new CMSTransactionScope())
            {
                // Get the translation provider
                AbstractMachineTranslationService machineService = null;
                AbstractHumanTranslationService   humanService   = null;
                TranslationSubmissionInfo         submission     = null;
                TranslationServiceInfo            ti             = TranslationServiceInfoProvider.GetTranslationServiceInfo(translationElem.SelectedService);
                if (ti != null)
                {
                    // Set if we need target tag (Translations.com workaround)
                    settings.GenerateTargetTag = ti.TranslationServiceGenerateTargetTag;

                    if (oneSubmission)
                    {
                        if (ti.TranslationServiceIsMachine)
                        {
                            machineService = AbstractMachineTranslationService.GetTranslationService(ti, CurrentSiteName);
                        }
                        else
                        {
                            humanService = AbstractHumanTranslationService.GetTranslationService(ti, CurrentSiteName);
                        }
                    }

                    bool langSupported = true;
                    if (humanService != null)
                    {
                        if (!humanService.IsLanguageSupported(settings.TargetLanguage))
                        {
                            AddError(ResHelper.GetString("translationservice.targetlanguagenotsupported"));
                            langSupported = false;
                        }
                        else
                        {
                            submission = TranslationServiceHelper.CreateSubmissionInfo(settings, ti, MembershipContext.AuthenticatedUser.UserID, SiteContext.CurrentSiteID, "Page submission " + DateTime.Now);
                        }
                    }

                    if (langSupported)
                    {
                        if (!oneSubmission || (machineService != null) || (humanService != null))
                        {
                            const string columns            = "NodeID, NodeAliasPath, DocumentCulture, NodeParentID";
                            string       submissionFileName = "";
                            string       submissionName     = "";
                            int          charCount          = 0;
                            int          wordCount          = 0;
                            int          docCount           = 0;

                            // Prepare the where condition
                            var where = new WhereCondition().WhereIn("NodeID", nodeIds);

                            // Get the documents in target culture to be able to check if "Skip already translated" option is on
                            // Combine both, source and target culture (at least one hit has to be found - to find the source of translation)
                            where.WhereIn("DocumentCulture", new[] { settings.SourceLanguage, settings.TargetLanguage });

                            DataSet ds = tree.SelectNodes(SiteContext.CurrentSiteName, "/%", TreeProvider.ALL_CULTURES, true, null, where.ToString(true), "NodeAliasPath DESC", TreeProvider.ALL_LEVELS, false, 0, columns);
                            if (!DataHelper.DataSourceIsEmpty(ds))
                            {
                                List <int> processedNodes = new List <int>();

                                // Translate the documents
                                foreach (DataRow dr in ds.Tables[0].Rows)
                                {
                                    refreshId = ValidationHelper.GetInteger(dr["NodeParentID"], 0);
                                    int nodeId = ValidationHelper.GetInteger(dr["NodeID"], 0);

                                    if (!processedNodes.Contains(nodeId))
                                    {
                                        processedNodes.Add(nodeId);

                                        string aliasPath = ValidationHelper.GetString(dr["NodeAliasPath"], "");
                                        string culture   = ValidationHelper.GetString(dr["DocumentCulture"], "");

                                        if (chkSkipTranslated.Checked)
                                        {
                                            if (culture == settings.TargetLanguage)
                                            {
                                                // Document already exists in requested culture, skip it
                                                AddLog(string.Format(ResHelper.GetString("content.translatedalready"), HTMLHelper.HTMLEncode(aliasPath + " (" + culture + ")")));
                                                continue;
                                            }
                                        }

                                        // Get document in source language
                                        TreeNode node = DocumentHelper.GetDocument(nodeId, settings.SourceLanguage, true, null);
                                        if (node == null)
                                        {
                                            // Document doesn't exist in source culture, skip it
                                            continue;
                                        }

                                        AddLog(string.Format(ResHelper.GetString("content.translating"), HTMLHelper.HTMLEncode(aliasPath + " (" + culture + ")")));

                                        // Save the first document as a base for submission name
                                        if (string.IsNullOrEmpty(submissionName))
                                        {
                                            submissionName = node.GetDocumentName();
                                        }
                                        if (string.IsNullOrEmpty(submissionFileName))
                                        {
                                            submissionFileName = node.NodeAlias;
                                        }

                                        docCount++;

                                        // Submit the document
                                        if (machineService != null)
                                        {
                                            TranslationServiceHelper.Translate(machineService, settings, node);
                                        }
                                        else
                                        {
                                            if (oneSubmission)
                                            {
                                                TreeNode targetNode = TranslationServiceHelper.CreateTargetCultureNode(node, settings.TargetLanguage, true, false, !settings.TranslateAttachments);
                                                TranslationSubmissionItemInfo submissionItem = TranslationServiceHelper.CreateSubmissionItemInfo(settings, submission, node, targetNode.DocumentID);

                                                charCount += submissionItem.SubmissionItemCharCount;
                                                wordCount += submissionItem.SubmissionItemWordCount;
                                            }
                                            else
                                            {
                                                TranslationServiceHelper.SubmitToTranslation(settings, node, out submission);
                                            }
                                        }
                                    }
                                }

                                if (docCount > 0)
                                {
                                    if (oneSubmission && (humanService != null))
                                    {
                                        AddLog(ResHelper.GetString("content.submitingtranslation"));

                                        // Set submission name
                                        int itemCount = docCount;
                                        if (itemCount > 1)
                                        {
                                            submissionName += " " + string.Format(GetString("translationservices.submissionnamesuffix"), itemCount - 1);
                                        }
                                        submission.SubmissionName      = submissionName;
                                        submission.SubmissionCharCount = charCount;
                                        submission.SubmissionWordCount = wordCount;
                                        submission.SubmissionItemCount = itemCount;
                                        submission.SubmissionParameter = submissionFileName;

                                        string err = humanService.CreateSubmission(submission);
                                        if (!string.IsNullOrEmpty(err))
                                        {
                                            AddError(LocalizationHelper.GetString("ContentRequest.TranslationFailed") + " \"" + err + "\"");
                                        }

                                        // Save submission with ticket
                                        TranslationSubmissionInfoProvider.SetTranslationSubmissionInfo(submission);
                                    }
                                }
                                else
                                {
                                    TranslationSubmissionInfoProvider.DeleteTranslationSubmissionInfo(submission);
                                    AddError(ResHelper.GetString("TranslateDocument.DocumentsAlreadyTranslated", currentCulture));
                                }
                            }
                            else
                            {
                                TranslationSubmissionInfoProvider.DeleteTranslationSubmissionInfo(submission);
                                AddError(ResHelper.GetString("TranslateDocument.NoSourceDocuments", currentCulture));
                            }
                        }
                        else
                        {
                            AddError(ResHelper.GetString("TranslateDocument.TranslationServiceNotFound", currentCulture));
                        }
                    }
                }

                tr.Commit();
            }
        }
        catch (ThreadAbortException ex)
        {
            string state = ValidationHelper.GetString(ex.ExceptionState, string.Empty);
            if (state == CMSThread.ABORT_REASON_STOP)
            {
                // When canceled
                AddError(ResHelper.GetString("TranslateDocument.TranslationCanceled", currentCulture));
            }
            else
            {
                // Log error
                LogExceptionToEventLog(ex);
            }
        }
        catch (Exception ex)
        {
            // Log error
            LogExceptionToEventLog(ex);
        }
        finally
        {
            if (IsDialog)
            {
                ctlAsync.Parameter = "wopener.location.replace(wopener.location); CloseDialog(); wopener.RefreshTree(null, null);";
            }
            else
            {
                if (string.IsNullOrEmpty(CurrentError))
                {
                    // Overwrite refreshId variable if sub-levels are visible
                    if (ValidationHelper.GetBoolean(parameter, false) && Parameters.ContainsKey("refreshnodeid"))
                    {
                        refreshId = ValidationHelper.GetInteger(Parameters["refreshnodeid"], 0);
                    }

                    // Refresh tree
                    ctlAsync.Parameter = "RefreshTree(" + refreshId + ", " + refreshId + "); \n" + "SelectNode(" + refreshId + ");";
                }
                else
                {
                    ctlAsync.Parameter = "RefreshTree(null, null);";
                }
            }
        }
    }
Ejemplo n.º 14
0
    protected override void OnInit(EventArgs e)
    {
        SiteID = QueryHelper.GetInteger("siteid", 0);

        if (File.Exists(HttpContext.Current.Request.MapPath(ResolveUrl(pathToGroupselector))))
        {
            Control ctrl = this.LoadUserControl(pathToGroupselector);
            if (ctrl != null)
            {
                selectInGroups    = ctrl as FormEngineUserControl;
                ctrl.ID           = "selGroups";
                ctrl              = this.LoadUserControl(pathToGroupselector);
                selectNotInGroups = ctrl as FormEngineUserControl;
                ctrl.ID           = "selNoGroups";

                plcGroups.Visible = true;
                plcSelectInGroups.Controls.Add(selectInGroups);
                plcSelectNotInGroups.Controls.Add(selectNotInGroups);

                selectNotInGroups.SetValue("UseFriendlyMode", true);
                selectInGroups.IsLiveSite = false;
                selectInGroups.SetValue("UseFriendlyMode", true);
                selectNotInGroups.IsLiveSite = false;
            }
        }

        if (LicenseHelper.CheckFeature(URLHelper.GetCurrentDomain(), FeatureEnum.LeadScoring) &&
            ResourceSiteInfoProvider.IsResourceOnSite("CMS.Scoring", SiteContext.CurrentSiteName) &&
            SettingsKeyInfoProvider.GetBoolValue(SiteContext.CurrentSiteName + ".CMSEnableOnlineMarketing"))
        {
            Control ctrl = this.LoadUserControl(pathToScoreSelector);
            if (ctrl != null)
            {
                ctrl.ID       = "selectScore";
                scoreSelector = ctrl as FormEngineUserControl;
                if (scoreSelector != null)
                {
                    plcUpdateContent.Controls.Add(scoreSelector);
                    scoreSelector.SetValue("AllowAll", false);
                    scoreSelector.SetValue("AllowEmpty", true);
                }
            }
        }
        else
        {
            plcScore.Visible             = false;
            lblScore.AssociatedControlID = null;
        }

        CMSUsersPage usersPage = (CMSUsersPage)Page;

        if (usersPage != null)
        {
            CurrentMode            = usersPage.CurrentMode;
            EnableDisplayingGuests = usersPage.EnableDisplayingGuests;

            if (CurrentMode == "online" && usersPage.DisplayContacts)
            {
                if (usersPage.DisplayScore && (scoreSelector != null))
                {
                    plcScore.Visible = true;
                }
            }
        }

        // Initialize advanced filter dropdownlists
        if (!RequestHelper.IsPostBack())
        {
            InitAllAnyDropDown(drpTypeSelectInRoles);
            InitAllAnyDropDown(drpTypeSelectNotInRoles);
            InitAllAnyDropDown(drpTypeSelectInGroups);
            InitAllAnyDropDown(drpTypeSelectNotInGroups);

            // Init lock account reason DDL
            drpLockReason.Items.Add(new ListItem(GetString("General.selectall"), ""));
            DataHelper.FillListControlWithEnum(typeof(UserAccountLockEnum), drpLockReason, "userlist.account.", null);
        }


        base.OnInit(e);

        plcDisplayAnonymous.Visible = ContactManagementPermission && SessionManager.StoreOnlineUsersInDatabase && EnableDisplayingGuests;
        if (!RequestHelper.IsPostBack())
        {
            chkDisplayAnonymous.Checked = DisplayGuestsByDefault;
        }

        siteSelector.DropDownSingleSelect.AutoPostBack = true;
    }
    /// <summary>
    /// OK click handler (Proceed registration).
    /// </summary>
    protected void btnOK_Click(object sender, EventArgs e)
    {
        if (PortalContext.IsDesignMode(PortalContext.ViewMode) || (HideOnCurrentPage) || (!IsVisible))
        {
            // Do not process
        }
        else
        {
            String siteName = SiteContext.CurrentSiteName;


            #region "Banned IPs"

            // Ban IP addresses which are blocked for registration
            if (!BannedIPInfoProvider.IsAllowed(siteName, BanControlEnum.Registration))
            {
                ShowError(GetString("banip.ipisbannedregistration"));
                return;
            }

            #endregion


            #region "Check Email & password"

            string[] siteList = { siteName };

            // If AssignToSites field set
            if (!String.IsNullOrEmpty(AssignToSites))
            {
                siteList = AssignToSites.Split(';');
            }

            // Check whether another user with this user name (which is effectively email) does not exist
            UserInfo ui     = UserInfoProvider.GetUserInfo(txtEmail.Text);
            SiteInfo si     = SiteContext.CurrentSite;
            UserInfo siteui = UserInfoProvider.GetUserInfo(UserInfoProvider.EnsureSitePrefixUserName(txtEmail.Text, si));

            if ((ui != null) || (siteui != null))
            {
                ShowError(GetString("Webparts_Membership_RegistrationForm.UserAlreadyExists").Replace("%%name%%", HTMLHelper.HTMLEncode(txtEmail.Text)));
                return;
            }

            // Check whether password is same
            if (passStrength.Text != txtConfirmPassword.Text)
            {
                ShowError(GetString("Webparts_Membership_RegistrationForm.PassworDoNotMatch"));
                return;
            }

            if ((PasswordMinLength > 0) && (passStrength.Text.Length < PasswordMinLength))
            {
                ShowError(String.Format(GetString("Webparts_Membership_RegistrationForm.PasswordMinLength"), PasswordMinLength));
                return;
            }

            if (!passStrength.IsValid())
            {
                ShowError(AuthenticationHelper.GetPolicyViolationMessage(SiteContext.CurrentSiteName));
                return;
            }

            if ((!txtEmail.IsValid()) || (txtEmail.Text.Length > EMAIL_MAX_LENGTH))
            {
                ShowError(String.Format(GetString("Webparts_Membership_RegistrationForm.EmailIsNotValid"), EMAIL_MAX_LENGTH));
                return;
            }

            #endregion


            #region "Captcha"

            // Check if captcha is required and verify captcha text
            if (DisplayCaptcha && !scCaptcha.IsValid())
            {
                // Display error message if catcha text is not valid
                ShowError(GetString("Webparts_Membership_RegistrationForm.captchaError"));
                return;
            }

            #endregion


            #region "User properties"

            var userEmail = txtEmail.Text.Trim();

            ui = new UserInfo();
            ui.PreferredCultureCode = "";
            ui.Email          = userEmail;
            ui.FirstName      = txtFirstName.Text.Trim();
            ui.LastName       = txtLastName.Text.Trim();
            ui.FullName       = UserInfoProvider.GetFullName(ui.FirstName, String.Empty, ui.LastName);
            ui.MiddleName     = "";
            ui.UserMFRequired = chkUseMultiFactorAutentization.Checked;

            // User name as put by user (no site prefix included)
            var plainUserName = userEmail;
            ui.UserName = plainUserName;

            // Check if the given email can be used as user name
            if (!ValidationHelper.IsUserName(plainUserName))
            {
                ShowError(String.Format(GetString("Webparts_Membership_RegistrationForm.UserNameNotValid"), HTMLHelper.HTMLEncode(plainUserName)));
                return;
            }

            // Ensure site prefixes
            if (UserInfoProvider.UserNameSitePrefixEnabled(siteName))
            {
                ui.UserName = UserInfoProvider.EnsureSitePrefixUserName(plainUserName, si);
            }

            ui.Enabled         = EnableUserAfterRegistration;
            ui.UserURLReferrer = CookieHelper.GetValue(CookieName.UrlReferrer);
            ui.UserCampaign    = Service.Resolve <ICampaignService>().CampaignCode;

            ui.SiteIndependentPrivilegeLevel = UserPrivilegeLevelEnum.None;

            ui.UserSettings.UserRegistrationInfo.IPAddress = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
            ui.UserSettings.UserRegistrationInfo.Agent     = HttpContext.Current.Request.UserAgent;

            // Check whether confirmation is required
            bool requiresConfirmation = SettingsKeyInfoProvider.GetBoolValue(siteName + ".CMSRegistrationEmailConfirmation");
            bool requiresAdminApprove = false;

            if (!requiresConfirmation)
            {
                // If confirmation is not required check whether administration approval is required
                requiresAdminApprove = SettingsKeyInfoProvider.GetBoolValue(siteName + ".CMSRegistrationAdministratorApproval");
                if (requiresAdminApprove)
                {
                    ui.Enabled = false;
                    ui.UserSettings.UserWaitingForApproval = true;
                }
            }
            else
            {
                // EnableUserAfterRegistration is overridden by requiresConfirmation - user needs to be confirmed before enable
                ui.Enabled = false;
            }

            // Set user's starting alias path
            if (!String.IsNullOrEmpty(StartingAliasPath))
            {
                ui.UserStartingAliasPath = MacroResolver.ResolveCurrentPath(StartingAliasPath);
            }

            #endregion


            #region "Reserved names"

            // Check for reserved user names like administrator, sysadmin, ...
            if (UserInfoProvider.NameIsReserved(siteName, plainUserName))
            {
                ShowError(GetString("Webparts_Membership_RegistrationForm.UserNameReserved").Replace("%%name%%", HTMLHelper.HTMLEncode(Functions.GetFormattedUserName(ui.UserName, true))));
                return;
            }

            if (UserInfoProvider.NameIsReserved(siteName, ui.UserNickName))
            {
                ShowError(GetString("Webparts_Membership_RegistrationForm.UserNameReserved").Replace("%%name%%", HTMLHelper.HTMLEncode(ui.UserNickName)));
                return;
            }

            #endregion


            #region "License limitations"

            string errorMessage = String.Empty;
            UserInfoProvider.CheckLicenseLimitation(ui, ref errorMessage);

            if (!String.IsNullOrEmpty(errorMessage))
            {
                ShowError(errorMessage);
                return;
            }

            #endregion


            // Check whether email is unique if it is required
            if (!UserInfoProvider.IsEmailUnique(userEmail, siteList, 0))
            {
                ShowError(GetString("UserInfo.EmailAlreadyExist"));
                return;
            }

            // Set password
            UserInfoProvider.SetPassword(ui, passStrength.Text);

            #region "Welcome Emails (confirmation, waiting for approval)"

            bool error = false;
            EmailTemplateInfo template = null;

            string emailSubject = null;
            // Send welcome message with username and password, with confirmation link, user must confirm registration
            if (requiresConfirmation)
            {
                template     = EmailTemplateProvider.GetEmailTemplate("RegistrationConfirmation", siteName);
                emailSubject = EmailHelper.GetSubject(template, GetString("RegistrationForm.RegistrationConfirmationEmailSubject"));
            }
            // Send welcome message with username and password, with information that user must be approved by administrator
            else if (SendWelcomeEmail)
            {
                if (requiresAdminApprove)
                {
                    template     = EmailTemplateProvider.GetEmailTemplate("Membership.RegistrationWaitingForApproval", siteName);
                    emailSubject = EmailHelper.GetSubject(template, GetString("RegistrationForm.RegistrationWaitingForApprovalSubject"));
                }
                // Send welcome message with username and password, user can logon directly
                else
                {
                    template     = EmailTemplateProvider.GetEmailTemplate("Membership.Registration", siteName);
                    emailSubject = EmailHelper.GetSubject(template, GetString("RegistrationForm.RegistrationSubject"));
                }
            }

            if (template != null)
            {
                // Create relation between contact and user. This ensures that contact will be correctly recognized when user approves registration (if approval is required)
                // New contact with user data is created in case it is not disabled by Data protection settings, otherwise an anonymous contact is created. Moreover an another
                // anonymous contact could be created during approval process when a new browser is used for approval step (when contact isn't in browser cookies).
                int contactId = ModuleCommands.OnlineMarketingGetCurrentContactID();
                if (contactId > 0)
                {
                    Service.Resolve <IContactRelationAssigner>().Assign(ui.UserID, MembershipType.CMS_USER, contactId, new UserContactDataPropagationChecker());
                }

                // Email message
                EmailMessage email = new EmailMessage();
                email.EmailFormat = EmailFormatEnum.Default;
                email.Recipients  = ui.Email;
                email.From        = SettingsKeyInfoProvider.GetValue(siteName + ".CMSNoreplyEmailAddress");
                email.Subject     = emailSubject;

                try
                {
                    var resolver = MembershipResolvers.GetMembershipRegistrationResolver(ui, AuthenticationHelper.GetRegistrationApprovalUrl(ApprovalPage, ui.UserGUID, siteName, NotifyAdministrator));
                    EmailSender.SendEmailWithTemplateText(siteName, email, template, resolver, true);
                }
                catch (Exception ex)
                {
                    EventLogProvider.LogException("E", "RegistrationForm - SendEmail", ex);
                    error = true;
                }
            }

            // If there was some error, user must be deleted
            if (error)
            {
                ShowError(GetString("RegistrationForm.UserWasNotCreated"));

                // Email was not send, user can't be approved - delete it
                UserInfoProvider.DeleteUser(ui);
                return;
            }

            #endregion


            #region "Administrator notification email"

            // Notify administrator if enabled and e-mail confirmation is not required
            if (!requiresConfirmation && NotifyAdministrator && (FromAddress != String.Empty) && (ToAddress != String.Empty))
            {
                EmailTemplateInfo mEmailTemplate;
                if (SettingsKeyInfoProvider.GetBoolValue(siteName + ".CMSRegistrationAdministratorApproval"))
                {
                    mEmailTemplate = EmailTemplateProvider.GetEmailTemplate("Registration.Approve", siteName);
                }
                else
                {
                    mEmailTemplate = EmailTemplateProvider.GetEmailTemplate("Registration.New", siteName);
                }

                if (mEmailTemplate == null)
                {
                    // Log missing e-mail template
                    EventLogProvider.LogEvent(EventType.ERROR, "RegistrationForm", "GetEmailTemplate", eventUrl: RequestContext.RawURL);
                }
                else
                {
                    EmailMessage message = new EmailMessage();
                    message.EmailFormat = EmailFormatEnum.Default;
                    message.From        = EmailHelper.GetSender(mEmailTemplate, FromAddress);
                    message.Recipients  = ToAddress;
                    message.Subject     = GetString("RegistrationForm.EmailSubject");

                    try
                    {
                        MacroResolver resolver = MembershipResolvers.GetRegistrationResolver(ui);
                        EmailSender.SendEmailWithTemplateText(siteName, message, mEmailTemplate, resolver, false);
                    }
                    catch
                    {
                        EventLogProvider.LogEvent(EventType.ERROR, "Membership", "RegistrationEmail");
                    }
                }
            }

            #endregion


            #region "Web analytics"

            // Track successful registration conversion
            if (TrackConversionName != String.Empty)
            {
                if (AnalyticsHelper.AnalyticsEnabled(siteName) && Service.Resolve <IAnalyticsConsentProvider>().HasConsentForLogging() && !AnalyticsHelper.IsIPExcluded(siteName, RequestContext.UserHostAddress))
                {
                    // Log conversion
                    HitLogProvider.LogConversions(siteName, LocalizationContext.PreferredCultureCode, TrackConversionName, 0, ConversionValue);
                }
            }

            // Log registered user if confirmation is not required
            if (!requiresConfirmation)
            {
                AnalyticsHelper.LogRegisteredUser(siteName, ui);
            }

            #endregion


            #region "On-line marketing - activity"

            // Log registered user if confirmation is not required
            if (!requiresConfirmation)
            {
                IMembershipActivityLogger logger = Service.Resolve <IMembershipActivityLogger>();
                logger.LogRegistration(ui.UserName, DocumentContext.CurrentDocument);
                // Log login activity
                if (ui.Enabled)
                {
                    logger.LogLogin(ui.UserName, DocumentContext.CurrentDocument);
                }
            }

            #endregion


            #region "Roles & authentication"

            string[] roleList = AssignRoles.Split(';');

            foreach (string sn in siteList)
            {
                // Add new user to the current site
                UserInfoProvider.AddUserToSite(ui.UserName, sn);
                foreach (string roleName in roleList)
                {
                    if (!String.IsNullOrEmpty(roleName))
                    {
                        String s = roleName.StartsWith(".", StringComparison.Ordinal) ? "" : sn;

                        // Add user to desired roles
                        if (RoleInfoProvider.RoleExists(roleName, s))
                        {
                            UserInfoProvider.AddUserToRole(ui.UserName, roleName, s);
                        }
                    }
                }
            }

            if (DisplayMessage.Trim() != String.Empty)
            {
                pnlForm.Visible = false;
                lblText.Visible = true;
                lblText.Text    = DisplayMessage;
            }
            else
            {
                if (ui.Enabled)
                {
                    AuthenticationHelper.AuthenticateUser(ui.UserName, true);
                }

                if (RedirectToURL != String.Empty)
                {
                    URLHelper.Redirect(UrlResolver.ResolveUrl(RedirectToURL));
                }

                else if (QueryHelper.GetString("ReturnURL", "") != String.Empty)
                {
                    string url = QueryHelper.GetString("ReturnURL", "");

                    // Do url decode
                    url = Server.UrlDecode(url);

                    // Check that url is relative path or hash is ok
                    if (url.StartsWith("~", StringComparison.Ordinal) || url.StartsWith("/", StringComparison.Ordinal) || QueryHelper.ValidateHash("hash", "aliaspath"))
                    {
                        URLHelper.Redirect(UrlResolver.ResolveUrl(url));
                    }
                    // Absolute path with wrong hash
                    else
                    {
                        URLHelper.Redirect(AdministrationUrlHelper.GetErrorPageUrl("dialogs.badhashtitle", "dialogs.badhashtext"));
                    }
                }
            }

            #endregion

            lblError.Visible = false;
        }
    }
    /// <summary>
    /// Initializes the control properties.
    /// </summary>
    protected void SetupControl()
    {
        if (StopProcessing)
        {
            // Do nothing
        }
        else
        {
            plcOther.Controls.Clear();

            if (MembershipContext.AuthenticatedUser.IsAuthenticated())
            {
                // Set the layout of tab menu
                tabMenu.TabControlLayout = BasicTabControl.GetTabMenuLayout(TabControlLayout);

                // Remove 'saved' parameter from query string
                string absoluteUri = URLHelper.RemoveParameterFromUrl(URLRewriter.CurrentURL, "saved");

                CurrentUserInfo currentUser = MembershipContext.AuthenticatedUser;

                // Get customer info
                GeneralizedInfo customer       = ModuleCommands.ECommerceGetCustomerInfoByUserId(currentUser.UserID);
                bool            userIsCustomer = (customer != null);

                // Get friends enabled setting
                bool friendsEnabled = UIHelper.IsFriendsModuleEnabled(SiteContext.CurrentSiteName);

                // Get customer ID
                int customerId = 0;
                if (userIsCustomer)
                {
                    customerId = ValidationHelper.GetInteger(customer.ObjectID, 0);
                }

                // Selected page URL
                string selectedPage = string.Empty;

                // Menu initialization
                tabMenu.UrlTarget = "_self";
                ArrayList activeTabs = new ArrayList();
                string    tabName    = string.Empty;

                // Set array size of tab control
                int arraySize = 0;
                if (DisplayMyPersonalSettings)
                {
                    arraySize++;
                }
                if (DisplayMyMessages)
                {
                    arraySize++;
                }

                // Handle 'Notifications' tab displaying
                bool hideUnavailableUI       = SettingsKeyInfoProvider.GetBoolValue("CMSHideUnavailableUserInterface");
                bool showNotificationsTab    = (DisplayMyNotifications && ModuleEntryManager.IsModuleLoaded(ModuleEntry.NOTIFICATIONS) && (!hideUnavailableUI || LicenseHelper.CheckFeature(URLHelper.GetCurrentDomain(), FeatureEnum.Notifications)));
                bool isWindowsAuthentication = RequestHelper.IsWindowsAuthentication();

                // Notification tab
                if (showNotificationsTab)
                {
                    arraySize++;
                }

                // Friends tab
                if (DisplayMyFriends && friendsEnabled)
                {
                    arraySize++;
                }

                // User password tab
                if (DisplayChangePassword && !currentUser.IsExternal && !isWindowsAuthentication)
                {
                    arraySize++;
                }

                // Subscriptions tab
                if (DisplayMySubscriptions)
                {
                    arraySize++;
                }

                // Memberships tab
                if (DisplayMyMemberships)
                {
                    arraySize++;
                }

                // Categories tab
                if (DisplayMyCategories)
                {
                    arraySize++;
                }

                // Ecommerce tabs
                if (DisplayMyCredits && userIsCustomer)
                {
                    arraySize++;
                }
                if (DisplayMyDetails && userIsCustomer)
                {
                    arraySize++;
                }
                if (DisplayMyAddresses && userIsCustomer)
                {
                    arraySize++;
                }
                if (DisplayMyOrders && userIsCustomer)
                {
                    arraySize++;
                }
                tabMenu.Tabs = new string[arraySize, 5];

                // Personal tab
                if (DisplayMyPersonalSettings)
                {
                    // Set new tab
                    tabName = personalTab;
                    activeTabs.Add(tabName);
                    tabMenu.Tabs[activeTabs.IndexOf(tabName), 0] = GetString("MyAccount.MyPersonalSettings");
                    tabMenu.Tabs[activeTabs.IndexOf(tabName), 2] = HTMLHelper.HTMLEncode(URLHelper.AddParameterToUrl(absoluteUri, ParameterName, personalTab));

                    if (currentUser != null)
                    {
                        selectedPage = tabName;
                    }
                }

                // These items can be displayed only for customer
                if (userIsCustomer && ModuleEntryManager.IsModuleLoaded(ModuleEntry.ECOMMERCE))
                {
                    if (DisplayMyDetails)
                    {
                        // Try to load the control dynamically (if available)
                        ucMyDetails = Page.LoadUserControl("~/CMSModules/Ecommerce/Controls/MyDetails/MyDetails.ascx") as CMSAdminControl;
                        if (ucMyDetails != null)
                        {
                            ucMyDetails.ID = "ucMyDetails";
                            plcOther.Controls.Add(ucMyDetails);

                            // Set new tab
                            tabName = detailsTab;
                            activeTabs.Add(tabName);
                            tabMenu.Tabs[activeTabs.IndexOf(tabName), 0] = GetString("MyAccount.MyDetails");
                            tabMenu.Tabs[activeTabs.IndexOf(tabName), 2] = HTMLHelper.HTMLEncode(URLHelper.AddParameterToUrl(absoluteUri, ParameterName, detailsTab));

                            if (selectedPage == string.Empty)
                            {
                                selectedPage = tabName;
                            }
                        }
                    }

                    if (DisplayMyAddresses)
                    {
                        // Try to load the control dynamically (if available)
                        ucMyAddresses = Page.LoadUserControl("~/CMSModules/Ecommerce/Controls/MyDetails/MyAddresses.ascx") as CMSAdminControl;
                        if (ucMyAddresses != null)
                        {
                            ucMyAddresses.ID = "ucMyAddresses";
                            plcOther.Controls.Add(ucMyAddresses);

                            // Set new tab
                            tabName = addressesTab;
                            activeTabs.Add(tabName);
                            tabMenu.Tabs[activeTabs.IndexOf(tabName), 0] = GetString("MyAccount.MyAddresses");
                            tabMenu.Tabs[activeTabs.IndexOf(tabName), 2] = HTMLHelper.HTMLEncode(URLHelper.AddParameterToUrl(absoluteUri, ParameterName, addressesTab));

                            if (selectedPage == string.Empty)
                            {
                                selectedPage = tabName;
                            }
                        }
                    }

                    if (DisplayMyOrders)
                    {
                        // Try to load the control dynamically (if available)
                        ucMyOrders = Page.LoadUserControl("~/CMSModules/Ecommerce/Controls/MyDetails/MyOrders.ascx") as CMSAdminControl;
                        if (ucMyOrders != null)
                        {
                            ucMyOrders.ID = "ucMyOrders";
                            plcOther.Controls.Add(ucMyOrders);

                            // Set new tab
                            tabName = ordersTab;
                            activeTabs.Add(tabName);
                            tabMenu.Tabs[activeTabs.IndexOf(tabName), 0] = GetString("MyAccount.MyOrders");
                            tabMenu.Tabs[activeTabs.IndexOf(tabName), 2] = HTMLHelper.HTMLEncode(URLHelper.AddParameterToUrl(absoluteUri, ParameterName, ordersTab));

                            if (selectedPage == string.Empty)
                            {
                                selectedPage = tabName;
                            }
                        }
                    }

                    if (DisplayMyCredits)
                    {
                        // Try to load the control dynamically (if available)
                        ucMyCredit = Page.LoadUserControl("~/CMSModules/Ecommerce/Controls/MyDetails/MyCredit.ascx") as CMSAdminControl;
                        if (ucMyCredit != null)
                        {
                            ucMyCredit.ID = "ucMyCredit";
                            plcOther.Controls.Add(ucMyCredit);

                            // Set new tab
                            tabName = creditTab;
                            activeTabs.Add(tabName);
                            tabMenu.Tabs[activeTabs.IndexOf(tabName), 0] = GetString("MyAccount.MyCredit");
                            tabMenu.Tabs[activeTabs.IndexOf(tabName), 2] = HTMLHelper.HTMLEncode(URLHelper.AddParameterToUrl(absoluteUri, ParameterName, creditTab));

                            if (selectedPage == string.Empty)
                            {
                                selectedPage = tabName;
                            }
                        }
                    }
                }

                if (DisplayChangePassword && !currentUser.IsExternal && !isWindowsAuthentication)
                {
                    // Set new tab
                    tabName = passwordTab;
                    activeTabs.Add(tabName);
                    tabMenu.Tabs[activeTabs.IndexOf(tabName), 0] = GetString("MyAccount.ChangePassword");
                    tabMenu.Tabs[activeTabs.IndexOf(tabName), 2] = HTMLHelper.HTMLEncode(URLHelper.AddParameterToUrl(absoluteUri, ParameterName, passwordTab));

                    if (selectedPage == string.Empty)
                    {
                        selectedPage = tabName;
                    }
                }

                if ((ucMyNotifications == null) && showNotificationsTab)
                {
                    // Try to load the control dynamically (if available)
                    ucMyNotifications = Page.LoadUserControl("~/CMSModules/Notifications/Controls/UserNotifications.ascx") as CMSAdminControl;
                    if (ucMyNotifications != null)
                    {
                        ucMyNotifications.ID = "ucMyNotifications";
                        plcOther.Controls.Add(ucMyNotifications);

                        // Set new tab
                        tabName = notificationsTab;
                        activeTabs.Add(tabName);
                        tabMenu.Tabs[activeTabs.IndexOf(tabName), 0] = GetString("MyAccount.MyNotifications");
                        tabMenu.Tabs[activeTabs.IndexOf(tabName), 2] = HTMLHelper.HTMLEncode(URLHelper.AddParameterToUrl(absoluteUri, ParameterName, notificationsTab));

                        if (selectedPage == string.Empty)
                        {
                            selectedPage = tabName;
                        }
                    }
                }

                if ((ucMyMessages == null) && DisplayMyMessages && ModuleEntryManager.IsModuleLoaded(ModuleEntry.MESSAGING))
                {
                    // Try to load the control dynamically (if available)
                    ucMyMessages = Page.LoadUserControl("~/CMSModules/Messaging/Controls/MyMessages.ascx") as CMSAdminControl;
                    if (ucMyMessages != null)
                    {
                        ucMyMessages.ID = "ucMyMessages";
                        plcOther.Controls.Add(ucMyMessages);

                        // Set new tab
                        tabName = messagesTab;
                        activeTabs.Add(tabName);
                        tabMenu.Tabs[activeTabs.IndexOf(tabName), 0] = GetString("MyAccount.MyMessages");
                        tabMenu.Tabs[activeTabs.IndexOf(tabName), 2] = HTMLHelper.HTMLEncode(URLHelper.AddParameterToUrl(absoluteUri, ParameterName, messagesTab));

                        if (selectedPage == string.Empty)
                        {
                            selectedPage = tabName;
                        }
                    }
                }

                if ((ucMyFriends == null) && DisplayMyFriends && ModuleEntryManager.IsModuleLoaded(ModuleEntry.COMMUNITY) && friendsEnabled)
                {
                    // Try to load the control dynamically (if available)
                    ucMyFriends = Page.LoadUserControl("~/CMSModules/Friends/Controls/MyFriends.ascx") as CMSAdminControl;
                    if (ucMyFriends != null)
                    {
                        ucMyFriends.ID = "ucMyFriends";
                        plcOther.Controls.Add(ucMyFriends);

                        // Set new tab
                        tabName = friendsTab;
                        activeTabs.Add(tabName);
                        tabMenu.Tabs[activeTabs.IndexOf(tabName), 0] = GetString("MyAccount.MyFriends");
                        tabMenu.Tabs[activeTabs.IndexOf(tabName), 2] = HTMLHelper.HTMLEncode(URLHelper.AddParameterToUrl(absoluteUri, ParameterName, friendsTab));

                        if (selectedPage == string.Empty)
                        {
                            selectedPage = tabName;
                        }
                    }
                }

                if ((ucMyAllSubscriptions == null) && DisplayMySubscriptions)
                {
                    // Try to load the control dynamically (if available)
                    ucMyAllSubscriptions = Page.LoadUserControl("~/CMSModules/Membership/Controls/Subscriptions.ascx") as CMSAdminControl;
                    if (ucMyAllSubscriptions != null)
                    {
                        // Set control
                        ucMyAllSubscriptions.Visible = false;

                        ucMyAllSubscriptions.SetValue("ShowBlogs", DisplayBlogs);
                        ucMyAllSubscriptions.SetValue("ShowMessageBoards", DisplayMessageBoards);
                        ucMyAllSubscriptions.SetValue("ShowNewsletters", DisplayNewsletters);
                        ucMyAllSubscriptions.SetValue("ShowForums", DisplayForums);
                        ucMyAllSubscriptions.SetValue("ShowReports", DisplayReports);
                        ucMyAllSubscriptions.SetValue("sendconfirmationemail", SendConfirmationEmails);

                        ucMyAllSubscriptions.ID = "ucMyAllSubscriptions";
                        plcOther.Controls.Add(ucMyAllSubscriptions);

                        // Set new tab
                        tabName = subscriptionsTab;
                        activeTabs.Add(tabName);
                        tabMenu.Tabs[activeTabs.IndexOf(tabName), 0] = GetString("MyAccount.MyAllSubscriptions");
                        tabMenu.Tabs[activeTabs.IndexOf(tabName), 2] = HTMLHelper.HTMLEncode(URLHelper.AddParameterToUrl(absoluteUri, ParameterName, subscriptionsTab));

                        if (selectedPage == string.Empty)
                        {
                            selectedPage = tabName;
                        }
                    }
                }

                // My memberships
                if ((ucMyMemberships == null) && DisplayMyMemberships)
                {
                    // Try to load the control dynamically
                    ucMyMemberships = Page.LoadUserControl("~/CMSModules/Membership/Controls/MyMemberships.ascx") as CMSAdminControl;

                    if (ucMyMemberships != null)
                    {
                        ucMyMemberships.SetValue("UserID", currentUser.UserID);

                        if (!String.IsNullOrEmpty(MembershipsPagePath))
                        {
                            ucMyMemberships.SetValue("BuyMembershipURL", DocumentURLProvider.GetUrl(MembershipsPagePath));
                        }

                        plcOther.Controls.Add(ucMyMemberships);

                        // Set new tab
                        tabName = membershipsTab;
                        activeTabs.Add(tabName);
                        tabMenu.Tabs[activeTabs.IndexOf(tabName), 0] = GetString("myaccount.mymemberships");
                        tabMenu.Tabs[activeTabs.IndexOf(tabName), 2] = HTMLHelper.HTMLEncode(URLHelper.AddParameterToUrl(absoluteUri, ParameterName, membershipsTab));

                        if (selectedPage == String.Empty)
                        {
                            selectedPage = tabName;
                        }
                    }
                }

                if ((ucMyCategories == null) && DisplayMyCategories)
                {
                    // Try to load the control dynamically (if available)
                    ucMyCategories = Page.LoadUserControl("~/CMSModules/Categories/Controls/Categories.ascx") as CMSAdminControl;
                    if (ucMyCategories != null)
                    {
                        ucMyCategories.Visible = false;

                        ucMyCategories.SetValue("DisplaySiteCategories", false);
                        ucMyCategories.SetValue("DisplaySiteSelector", false);

                        ucMyCategories.ID = "ucMyCategories";
                        plcOther.Controls.Add(ucMyCategories);

                        // Set new tab
                        tabName = categoriesTab;
                        activeTabs.Add(tabName);
                        tabMenu.Tabs[activeTabs.IndexOf(tabName), 0] = GetString("MyAccount.MyCategories");
                        tabMenu.Tabs[activeTabs.IndexOf(tabName), 2] = HTMLHelper.HTMLEncode(URLHelper.AddParameterToUrl(absoluteUri, ParameterName, categoriesTab));

                        if (selectedPage == string.Empty)
                        {
                            selectedPage = tabName;
                        }
                    }
                }

                // Set CSS class
                pnlBody.CssClass = CssClass;

                // Get page URL
                page = QueryHelper.GetString(ParameterName, selectedPage);

                // Set controls visibility
                ucChangePassword.Visible        = false;
                ucChangePassword.StopProcessing = true;

                if (ucMyAddresses != null)
                {
                    ucMyAddresses.Visible        = false;
                    ucMyAddresses.StopProcessing = true;
                }

                if (ucMyOrders != null)
                {
                    ucMyOrders.Visible        = false;
                    ucMyOrders.StopProcessing = true;
                }

                if (ucMyDetails != null)
                {
                    ucMyDetails.Visible        = false;
                    ucMyDetails.StopProcessing = true;
                }

                if (ucMyCredit != null)
                {
                    ucMyCredit.Visible        = false;
                    ucMyCredit.StopProcessing = true;
                }

                if (ucMyAllSubscriptions != null)
                {
                    ucMyAllSubscriptions.Visible        = false;
                    ucMyAllSubscriptions.StopProcessing = true;
                    ucMyAllSubscriptions.SetValue("CacheMinutes", CacheMinutes);
                }

                if (ucMyNotifications != null)
                {
                    ucMyNotifications.Visible        = false;
                    ucMyNotifications.StopProcessing = true;
                }

                if (ucMyMessages != null)
                {
                    ucMyMessages.Visible        = false;
                    ucMyMessages.StopProcessing = true;
                }

                if (ucMyFriends != null)
                {
                    ucMyFriends.Visible        = false;
                    ucMyFriends.StopProcessing = true;
                }

                if (ucMyMemberships != null)
                {
                    ucMyMemberships.Visible        = false;
                    ucMyMemberships.StopProcessing = true;
                }

                if (ucMyCategories != null)
                {
                    ucMyCategories.Visible        = false;
                    ucMyCategories.StopProcessing = true;
                }

                tabMenu.SelectedTab = activeTabs.IndexOf(page);

                // Select current page
                switch (page)
                {
                case personalTab:
                    if (myProfile != null)
                    {
                        // Get alternative form info
                        AlternativeFormInfo afi = AlternativeFormInfoProvider.GetAlternativeFormInfo(AlternativeFormName);
                        if (afi != null)
                        {
                            myProfile.StopProcessing      = false;
                            myProfile.Visible             = true;
                            myProfile.AllowEditVisibility = AllowEditVisibility;
                            myProfile.AlternativeFormName = AlternativeFormName;
                        }
                        else
                        {
                            lblError.Text     = String.Format(GetString("altform.formdoesntexists"), AlternativeFormName);
                            lblError.Visible  = true;
                            myProfile.Visible = false;
                        }
                    }
                    break;

                // My details tab
                case detailsTab:
                    if (ucMyDetails != null)
                    {
                        ucMyDetails.Visible        = true;
                        ucMyDetails.StopProcessing = false;
                        ucMyDetails.SetValue("Customer", customer);
                    }
                    break;

                // My addresses tab
                case addressesTab:
                    if (ucMyAddresses != null)
                    {
                        ucMyAddresses.Visible        = true;
                        ucMyAddresses.StopProcessing = false;
                        ucMyAddresses.SetValue("CustomerId", customerId);
                    }
                    break;

                // My orders tab
                case ordersTab:
                    if (ucMyOrders != null)
                    {
                        ucMyOrders.Visible        = true;
                        ucMyOrders.StopProcessing = false;
                        ucMyOrders.SetValue("CustomerId", customerId);
                        ucMyOrders.SetValue("ShowOrderTrackingNumber", ShowOrderTrackingNumber);
                    }
                    break;

                // My credit tab
                case creditTab:
                    if (ucMyCredit != null)
                    {
                        ucMyCredit.Visible        = true;
                        ucMyCredit.StopProcessing = false;
                        ucMyCredit.SetValue("CustomerId", customerId);
                    }
                    break;

                // Password tab
                case passwordTab:
                    ucChangePassword.Visible            = true;
                    ucChangePassword.StopProcessing     = false;
                    ucChangePassword.AllowEmptyPassword = AllowEmptyPassword;
                    break;

                // Notification tab
                case notificationsTab:
                    if (ucMyNotifications != null)
                    {
                        ucMyNotifications.Visible        = true;
                        ucMyNotifications.StopProcessing = false;
                        ucMyNotifications.SetValue("UserId", currentUser.UserID);
                        ucMyNotifications.SetValue("UnigridImageDirectory", UnigridImageDirectory);
                    }
                    break;

                // My messages tab
                case messagesTab:
                    if (ucMyMessages != null)
                    {
                        ucMyMessages.Visible        = true;
                        ucMyMessages.StopProcessing = false;
                    }
                    break;

                // My friends tab
                case friendsTab:
                    if (ucMyFriends != null)
                    {
                        ucMyFriends.Visible        = true;
                        ucMyFriends.StopProcessing = false;
                        ucMyFriends.SetValue("UserID", currentUser.UserID);
                    }
                    break;

                // My subscriptions tab
                case subscriptionsTab:
                    if (ucMyAllSubscriptions != null)
                    {
                        ucMyAllSubscriptions.Visible        = true;
                        ucMyAllSubscriptions.StopProcessing = false;

                        ucMyAllSubscriptions.SetValue("userid", currentUser.UserID);
                        ucMyAllSubscriptions.SetValue("siteid", CMSContext.CurrentSiteID);
                    }
                    break;

                // My memberships tab
                case membershipsTab:
                    if (ucMyMemberships != null)
                    {
                        ucMyMemberships.Visible        = true;
                        ucMyMemberships.StopProcessing = false;
                    }
                    break;

                // My categories tab
                case categoriesTab:
                    if (ucMyCategories != null)
                    {
                        ucMyCategories.Visible        = true;
                        ucMyCategories.StopProcessing = false;
                    }
                    break;
                }
            }
            else
            {
                // Hide control if current user is not authenticated
                Visible = false;
            }
        }
    }
Ejemplo n.º 17
0
    protected void Page_Load(object sender, EventArgs e)
    {
        previewState = GetPreviewStateFromCookies(MASTERPAGE);

        // Keep current user
        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;
                // Remove bootstrap default class
                bodyCss = bodyCss.Replace(" cms-bootstrap", String.Empty);

                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 = CSSHelper.GetCSSFileLink(CSSHelper.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 += CSSHelper.GetCSSFileLink(CSSHelper.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 = UIContextHelper.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%', false);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) && !UIContext.DisplaySplitMode),
                Tooltip       = GetString("preview.tooltip")
            };
            headerActions.ActionsList.Add(preview);

            headerActions.ActionPerformed += headerActions_ActionPerformed;
        }

        RegisterInitScripts(pnlBody.ClientID, pnlMenu.ClientID, false);
    }
Ejemplo n.º 18
0
    /// <summary>
    /// OK click handler (Proceed registration).
    /// </summary>
    private void btnRegister_Click(object sender, EventArgs e)
    {
        string currentSiteName = SiteContext.CurrentSiteName;

        string[] siteList = { currentSiteName };

        // If AssignToSites field set
        if (!String.IsNullOrEmpty(AssignToSites))
        {
            siteList = AssignToSites.Split(';');
        }

        if ((PageManager.ViewMode == ViewModeEnum.Design) || (HideOnCurrentPage) || (!IsVisible))
        {
            // Do not process
        }
        else
        {
            // Ban IP addresses which are blocked for registration
            if (!BannedIPInfoProvider.IsAllowed(currentSiteName, BanControlEnum.Registration))
            {
                lblError.Visible = true;
                lblError.Text    = GetString("banip.ipisbannedregistration");
                return;
            }

            // Check if captcha is required and verify captcha text
            if (DisplayCaptcha && !captchaElem.IsValid())
            {
                // Display error message if captcha text is not valid
                lblError.Visible = true;
                lblError.Text    = GetString("Webparts_Membership_RegistrationForm.captchaError");
                return;
            }

            string userName       = String.Empty;
            string nickName       = String.Empty;
            string firstName      = String.Empty;
            string lastName       = String.Empty;
            string emailValue     = String.Empty;
            string pwd            = string.Empty;
            string confPassword   = string.Empty;
            string educationLevel = String.Empty;
            string interestArea   = String.Empty;
            string industry       = String.Empty;
            string referralSource = string.Empty;

            // Check duplicate user
            // 1. Find appropriate control and get its value (i.e. user name)
            // 2. Try to find user info
            //FormEngineUserControl txtUserName = formUser.FieldControls["UserName"];
            //if (txtUserName != null)
            //{
            //    userName = ValidationHelper.GetString(txtUserName.Value, String.Empty);
            //}

            FormEngineUserControl txtEmail = formUser.FieldControls["Email"];
            if (txtEmail != null)
            {
                emailValue = ValidationHelper.GetString(txtEmail.Value, String.Empty);
                userName   = emailValue;
            }

            // If user name and e-mail aren't filled stop processing and display error.
            if (string.IsNullOrEmpty(userName) && String.IsNullOrEmpty(emailValue))
            {
                formUser.StopProcessing = true;
                lblError.Visible        = true;
                lblError.Text           = GetString("customregistrationform.usernameandemail");
                return;
            }
            else
            {
                formUser.Data.SetValue("UserName", userName);
            }

            //check if email is valid
            if (!ValidationHelper.IsEmail(txtEmail.Text.ToLowerCSafe()))
            {
                lblError.Visible = true;
                lblError.Text    = GetString("Webparts_Membership_RegistrationForm.EmailIsNotValid");
                return;
            }

            FormEngineUserControl txtNickName = formUser.FieldControls["UserNickName"];
            if (txtNickName != null)
            {
                nickName = ValidationHelper.GetString(txtNickName.Value, String.Empty);
            }

            FormEngineUserControl txtFirstName = formUser.FieldControls["FirstName"];
            if (txtFirstName != null)
            {
                firstName = ValidationHelper.GetString(txtFirstName.Value, String.Empty);
            }

            FormEngineUserControl txtLastName = formUser.FieldControls["LastName"];
            if (txtLastName != null)
            {
                lastName = ValidationHelper.GetString(txtLastName.Value, String.Empty);
            }

            FormEngineUserControl txtPwd = formUser.FieldControls["UserPassword"];
            if (txtPwd != null)
            {
                pwd = ValidationHelper.GetString(txtPwd.Value, String.Empty);
            }

            FormEngineUserControl txtConfPassword = formUser.FieldControls["ReenterPassword"];
            if (txtConfPassword != null)
            {
                confPassword = ValidationHelper.GetString(txtConfPassword.Value, String.Empty);
            }

            if (string.IsNullOrEmpty(pwd) || string.IsNullOrEmpty(confPassword))
            {
                lblError.Visible = true;
                lblError.Text    = "please enter password with confirmation";
                return;
            }

            if (pwd != confPassword)
            {
                lblError.Visible = true;
                lblError.Text    = "Password doesn't match";
                return;
            }


            if (validateFields(formUser.FieldControls["UserPassword"].Value.ToString()))
            {
                // Test if "global" or "site" user exists.
                SiteInfo si     = SiteContext.CurrentSite;
                UserInfo siteui = UserInfoProvider.GetUserInfo(UserInfoProvider.EnsureSitePrefixUserName(userName, si));
                if ((UserInfoProvider.GetUserInfo(userName) != null) || (siteui != null))
                {
                    lblError.Visible = true;
                    lblError.Text    = GetString("Webparts_Membership_RegistrationForm.UserAlreadyExists").Replace("%%name%%", HTMLHelper.HTMLEncode(Functions.GetFormattedUserName(userName, true)));
                    return;
                }

                // Check for reserved user names like administrator, sysadmin, ...
                if (UserInfoProvider.NameIsReserved(currentSiteName, userName))
                {
                    lblError.Visible = true;
                    lblError.Text    = GetString("Webparts_Membership_RegistrationForm.UserNameReserved").Replace("%%name%%", HTMLHelper.HTMLEncode(Functions.GetFormattedUserName(userName, true)));
                    return;
                }

                if (UserInfoProvider.NameIsReserved(currentSiteName, nickName))
                {
                    lblError.Visible = true;
                    lblError.Text    = GetString("Webparts_Membership_RegistrationForm.UserNameReserved").Replace("%%name%%", HTMLHelper.HTMLEncode(nickName));
                    return;
                }

                // Check limitations for site members
                if (!UserInfoProvider.LicenseVersionCheck(RequestContext.CurrentDomain, FeatureEnum.SiteMembers, ObjectActionEnum.Insert, false))
                {
                    lblError.Visible = true;
                    lblError.Text    = GetString("License.MaxItemsReachedSiteMember");
                    return;
                }

                // Check whether email is unique if it is required
                if (!UserInfoProvider.IsEmailUnique(emailValue, siteList, 0))
                {
                    lblError.Visible = true;
                    lblError.Text    = GetString("UserInfo.EmailAlreadyExist");
                    return;
                }

                // Validate and save form with new user data
                if (!formUser.Save())
                {
                    // Return if saving failed
                    return;
                }

                // Get user info from form
                UserInfo ui = (UserInfo)formUser.Info;

                // Add user prefix if settings is on
                // Ensure site prefixes
                if (UserInfoProvider.UserNameSitePrefixEnabled(currentSiteName))
                {
                    ui.UserName = UserInfoProvider.EnsureSitePrefixUserName(userName, si);
                }

                ui.Enabled         = EnableUserAfterRegistration;
                ui.UserURLReferrer = MembershipContext.AuthenticatedUser.URLReferrer;
                ui.UserCampaign    = AnalyticsHelper.Campaign;

                ui.SetPrivilegeLevel(UserPrivilegeLevelEnum.None);

                // Fill optionally full user name
                if (String.IsNullOrEmpty(ui.FullName))
                {
                    ui.FullName = UserInfoProvider.GetFullName(ui.FirstName, ui.MiddleName, ui.LastName);
                }

                // Ensure nick name
                if (ui.UserNickName.Trim() == String.Empty)
                {
                    ui.UserNickName = Functions.GetFormattedUserName(ui.UserName, true);
                }

                ui.UserSettings.UserRegistrationInfo.IPAddress = RequestContext.UserHostAddress;
                ui.UserSettings.UserRegistrationInfo.Agent     = HttpContext.Current.Request.UserAgent;
                ui.UserSettings.UserLogActivities        = true;
                ui.UserSettings.UserShowIntroductionTile = true;

                // Check whether confirmation is required
                bool requiresConfirmation = SettingsKeyInfoProvider.GetBoolValue(currentSiteName + ".CMSRegistrationEmailConfirmation");
                bool requiresAdminApprove = SettingsKeyInfoProvider.GetBoolValue(currentSiteName + ".CMSRegistrationAdministratorApproval");
                if (!requiresConfirmation)
                {
                    // If confirmation is not required check whether administration approval is reqiures
                    if (requiresAdminApprove)
                    {
                        ui.Enabled = false;
                        ui.UserSettings.UserWaitingForApproval = true;
                    }
                }
                else
                {
                    // EnableUserAfterRegistration is overrided by requiresConfirmation - user needs to be confirmed before enable
                    ui.Enabled = false;
                }

                // Set user's starting alias path
                if (!String.IsNullOrEmpty(StartingAliasPath))
                {
                    ui.UserStartingAliasPath = MacroResolver.ResolveCurrentPath(StartingAliasPath);
                }

                // Get user password and save it in apropriate format after form save
                string password = ValidationHelper.GetString(ui.GetValue("UserPassword"), String.Empty);
                UserInfoProvider.SetPassword(ui, password);

                var customerToken = PersonifyRegistered(emailValue, password, firstName, lastName);
                if (string.IsNullOrEmpty(customerToken))
                {
                    UserInfoProvider.DeleteUser(ui);
                    return;
                }
                else
                {
                    var    roles      = GetImsroles(customerToken);
                    string groupslist = "";
                    if (roles.Length > 0)
                    {
                        foreach (string s in roles)
                        {
                            if (s.Length > 0)
                            {
                                groupslist += s + ",";
                            }
                        }
                    }

                    //we need this mispelling.
                    groupslist += "peronifyUser" + ",";

                    new LoginUsertokentico().AddUserToRole(ui, groupslist, true, false);
                }


                // Prepare macro data source for email resolver
                UserInfo userForMail = ui.Clone();
                userForMail.SetValue("UserPassword", string.Empty);

                object[] data = new object[1];
                data[0] = userForMail;

                // Prepare resolver for notification and welcome emails
                MacroResolver resolver = MacroContext.CurrentResolver;
                resolver.SetAnonymousSourceData(data);

                #region "Welcome Emails (confirmation, waiting for approval)"

                bool error = false;
                EmailTemplateInfo template = null;

                // Prepare macro replacements
                string[,] replacements = new string[6, 2];
                replacements[0, 0]     = "confirmaddress";
                replacements[0, 1]     = AuthenticationHelper.GetRegistrationApprovalUrl(ApprovalPage, ui.UserGUID, currentSiteName, NotifyAdministrator);
                replacements[1, 0]     = "username";
                replacements[1, 1]     = userName;
                replacements[2, 0]     = "password";
                replacements[2, 1]     = password;
                replacements[3, 0]     = "Email";
                replacements[3, 1]     = emailValue;
                replacements[4, 0]     = "FirstName";
                replacements[4, 1]     = firstName;
                replacements[5, 0]     = "LastName";
                replacements[5, 1]     = lastName;

                // Set resolver
                resolver.SetNamedSourceData(replacements);

                // Email message
                EmailMessage emailMessage = new EmailMessage();
                emailMessage.EmailFormat = EmailFormatEnum.Default;
                emailMessage.Recipients  = ui.Email;

                // Send welcome message with username and password, with confirmation link, user must confirm registration
                if (requiresConfirmation)
                {
                    template             = EmailTemplateProvider.GetEmailTemplate("RegistrationConfirmation", currentSiteName);
                    emailMessage.Subject = GetString("RegistrationForm.RegistrationConfirmationEmailSubject");
                }
                // Send welcome message with username and password, with information that user must be approved by administrator
                else if (SendWelcomeEmail)
                {
                    if (requiresAdminApprove)
                    {
                        template             = EmailTemplateProvider.GetEmailTemplate("Membership.RegistrationWaitingForApproval", currentSiteName);
                        emailMessage.Subject = GetString("RegistrationForm.RegistrationWaitingForApprovalSubject");
                    }
                    // Send welcome message with username and password, user can logon directly
                    else
                    {
                        template             = EmailTemplateProvider.GetEmailTemplate("Membership.Registration", currentSiteName);
                        emailMessage.Subject = GetString("RegistrationForm.RegistrationSubject");
                    }
                }

                if (template != null)
                {
                    emailMessage.From = EmailHelper.GetSender(template, SettingsKeyInfoProvider.GetStringValue(currentSiteName + ".CMSNoreplyEmailAddress"));
                    // Enable macro encoding for body
                    resolver.Settings.EncodeResolvedValues = true;
                    emailMessage.Body = resolver.ResolveMacros(template.TemplateText);
                    // Disable macro encoding for plaintext body and subject
                    resolver.Settings.EncodeResolvedValues = false;
                    emailMessage.PlainTextBody             = resolver.ResolveMacros(template.TemplatePlainText);
                    emailMessage.Subject = resolver.ResolveMacros(EmailHelper.GetSubject(template, emailMessage.Subject));

                    emailMessage.CcRecipients  = template.TemplateCc;
                    emailMessage.BccRecipients = template.TemplateBcc;

                    try
                    {
                        EmailHelper.ResolveMetaFileImages(emailMessage, template.TemplateID, EmailTemplateInfo.OBJECT_TYPE, ObjectAttachmentsCategories.TEMPLATE);
                        // Send the e-mail immediately
                        EmailSender.SendEmail(currentSiteName, emailMessage, true);
                    }
                    catch (Exception ex)
                    {
                        EventLogProvider.LogException("E", "RegistrationForm - SendEmail", ex);
                        error = true;
                    }
                }

                // If there was some error, user must be deleted
                if (error)
                {
                    lblError.Visible = true;
                    lblError.Text    = GetString("RegistrationForm.UserWasNotCreated");

                    // Email was not send, user can't be approved - delete it
                    UserInfoProvider.DeleteUser(ui);
                    return;
                }

                #endregion


                #region "Administrator notification email"

                // Notify administrator if enabled and email confirmation is not required
                if (!requiresConfirmation && NotifyAdministrator && (FromAddress != String.Empty) && (ToAddress != String.Empty))
                {
                    EmailTemplateInfo mEmailTemplate = null;

                    if (requiresAdminApprove)
                    {
                        mEmailTemplate = EmailTemplateProvider.GetEmailTemplate("Registration.Approve", currentSiteName);
                    }
                    else
                    {
                        mEmailTemplate = EmailTemplateProvider.GetEmailTemplate("Registration.New", currentSiteName);
                    }

                    if (mEmailTemplate == null)
                    {
                        EventLogProvider.LogEvent(EventType.ERROR, "RegistrationForm", "GetEmailTemplate", eventUrl: RequestContext.RawURL);
                    }
                    else
                    {
                        // E-mail template ok
                        replacements       = new string[4, 2];
                        replacements[0, 0] = "firstname";
                        replacements[0, 1] = ui.FirstName;
                        replacements[1, 0] = "lastname";
                        replacements[1, 1] = ui.LastName;
                        replacements[2, 0] = "email";
                        replacements[2, 1] = ui.Email;
                        replacements[3, 0] = "username";
                        replacements[3, 1] = userName;

                        // Set resolver
                        resolver.SetNamedSourceData(replacements);
                        // Enable macro encoding for body
                        resolver.Settings.EncodeResolvedValues = true;

                        EmailMessage message = new EmailMessage();
                        message.EmailFormat = EmailFormatEnum.Default;
                        message.From        = EmailHelper.GetSender(mEmailTemplate, FromAddress);
                        message.Recipients  = ToAddress;
                        message.Body        = resolver.ResolveMacros(mEmailTemplate.TemplateText);
                        // Disable macro encoding for plaintext body and subject
                        resolver.Settings.EncodeResolvedValues = false;
                        message.Subject       = resolver.ResolveMacros(EmailHelper.GetSubject(mEmailTemplate, GetString("RegistrationForm.EmailSubject")));
                        message.PlainTextBody = resolver.ResolveMacros(mEmailTemplate.TemplatePlainText);

                        message.CcRecipients  = mEmailTemplate.TemplateCc;
                        message.BccRecipients = mEmailTemplate.TemplateBcc;

                        try
                        {
                            // Attach template meta-files to e-mail
                            EmailHelper.ResolveMetaFileImages(message, mEmailTemplate.TemplateID, EmailTemplateInfo.OBJECT_TYPE, ObjectAttachmentsCategories.TEMPLATE);
                            EmailSender.SendEmail(currentSiteName, message);
                        }
                        catch
                        {
                            EventLogProvider.LogEvent(EventType.ERROR, "Membership", "RegistrationEmail");
                        }
                    }
                }

                #endregion


                #region "Web analytics"

                // Track successful registration conversion
                if (TrackConversionName != String.Empty)
                {
                    if (AnalyticsHelper.AnalyticsEnabled(currentSiteName) && AnalyticsHelper.TrackConversionsEnabled(currentSiteName) && !AnalyticsHelper.IsIPExcluded(currentSiteName, RequestContext.UserHostAddress))
                    {
                        HitLogProvider.LogConversions(currentSiteName, LocalizationContext.PreferredCultureCode, TrackConversionName, 0, ConversionValue);
                    }
                }

                // Log registered user if confirmation is not required
                if (!requiresConfirmation)
                {
                    AnalyticsHelper.LogRegisteredUser(currentSiteName, ui);
                }

                #endregion


                #region "On-line marketing - activity"

                // Log registered user if confirmation is not required
                if (!requiresConfirmation)
                {
                    Activity activity = new ActivityRegistration(ui, DocumentContext.CurrentDocument, AnalyticsContext.ActivityEnvironmentVariables);
                    if (activity.Data != null)
                    {
                        activity.Data.ContactID = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui);
                        activity.Log();
                    }

                    // Log login activity
                    if (ui.Enabled)
                    {
                        // Log activity
                        int      contactID     = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui);
                        Activity activityLogin = new ActivityUserLogin(contactID, ui, DocumentContext.CurrentDocument, AnalyticsContext.ActivityEnvironmentVariables);
                        activityLogin.Log();
                    }
                }

                #endregion

                #region "Site and roles addition and authentication"

                string[] roleList = AssignRoles.Split(';');

                foreach (string siteName in siteList)
                {
                    // Add new user to the current site
                    UserInfoProvider.AddUserToSite(ui.UserName, siteName);
                    foreach (string roleName in roleList)
                    {
                        if (!String.IsNullOrEmpty(roleName))
                        {
                            String sn = roleName.StartsWithCSafe(".") ? String.Empty : siteName;

                            // Add user to desired roles
                            if (RoleInfoProvider.RoleExists(roleName, sn))
                            {
                                UserInfoProvider.AddUserToRole(ui.UserName, roleName, sn);
                            }
                        }
                    }
                }
                if (ui.Enabled)
                {
                    if (this.AutoLoginAfterRegistration)
                    {
                        Session["UserName"]   = userName;
                        Session["Password"]   = password;
                        Session["RememberMe"] = true;
                        Session["RetryCount"] = null;

                        if (this.Request.QueryString["ReturnURL"] != null)
                        {
                            var returnURL = this.Request.QueryString["ReturnURL"];

                            Session["ReturnURL"] = returnURL;
                        }
                        else if (!String.IsNullOrEmpty(this.RedirectToURL))
                        {
                            var returnURL = this.Request.QueryString["ReturnURL"];

                            Session["ReturnURL"] = returnURL;
                        }
                        Response.Redirect("~/sso/ssohandler.aspx", true);
                    }
                    else if (!String.IsNullOrEmpty(this.LoginURL))
                    {
                        Response.Redirect(string.Format(this.LoginURL, userName), true);
                    }
                    else if (!String.IsNullOrEmpty(this.RedirectToURL))
                    {
                        Response.Redirect(this.RedirectToURL, true);
                    }
                }
                #endregion

                lblError.Visible = false;
            }
        }
    }
    /// <summary>
    /// Process additional department tasks.
    /// </summary>
    public void ProcessDepartment(object sender, EventArgs e)
    {
        TreeNode editedNode = Form.EditedObject as TreeNode;

        // Get department template source document
        TreeNode sourceNode = DocumentHelper.GetDocument(SiteContext.CurrentSiteName, DepartmentTemplatePath, null, true, null, null, null, TreeProvider.ALL_LEVELS, false, null, TreeProvider);

        // Copy relevant template data to department document. Proceed only when creating a department, updating a department must not rewrite its data with template's data.
        if (Form.IsInsertMode && (sourceNode != null))
        {
            var excludeColumns = new []
            {
                "DocumentName",
                "NodeAlias",
                "DocumentTagGroupID",
                "DocumentStylesheetID",
                "DocumentPublishFrom",
                "DocumentPublishTo"
            };
            DocumentHelper.CopyNodeData(sourceNode, editedNode, new CopyNodeDataSettings(true, true, false, true, true, false, false, false, excludeColumns));
            DocumentHelper.UpdateDocument(editedNode, TreeProvider);
        }


        #region "Create department tag group"

        // Get tag group info
        TagGroupInfo tgi = TagGroupInfoProvider.GetTagGroupInfo(editedNode.DocumentTagGroupID);

        // If not exist, create new tag group and set it to document
        if (tgi == null)
        {
            // Populate tag group info fields
            tgi = new TagGroupInfo();
            tgi.TagGroupDisplayName = editedNode.GetDocumentName();
            tgi.TagGroupName        = editedNode.NodeGUID.ToString();
            tgi.TagGroupDescription = "";
            tgi.TagGroupSiteID      = SiteContext.CurrentSiteID;
            tgi.TagGroupIsAdHoc     = false;

            // Store tag group info to DB
            TagGroupInfoProvider.SetTagGroupInfo(tgi);

            // Update document Tag group ID
            editedNode.DocumentTagGroupID = tgi.TagGroupID;
            DocumentHelper.UpdateDocument(editedNode, TreeProvider);
        }

        #endregion


        if (!DataHelper.DataSourceIsEmpty(TemplateDocuments))
        {
            // List of selected documents
            string selectedDocs = ";" + Value + ";";

            // Get already created documents under edited document
            DataSet       dsExistingDocs = DocumentHelper.GetDocuments(SiteContext.CurrentSiteName, editedNode.NodeAliasPath + "/%", editedNode.DocumentCulture, true, null, null, null, 1, false, 0, "NodeAlias, " + DocumentColumnLists.SELECTNODES_REQUIRED_COLUMNS, null);
            StringBuilder sbExistDocs    = new StringBuilder();

            // Process existing documents to obtain list of aliases
            foreach (DataRow drExistDoc in dsExistingDocs.Tables[0].Rows)
            {
                sbExistDocs.Append(";");
                sbExistDocs.Append(drExistDoc["NodeAlias"].ToString().ToLowerCSafe());
            }
            sbExistDocs.Append(";");
            string existingDocs = sbExistDocs.ToString();

            // Set same ordering as for original template documents
            bool orgUseAutomaticOrdering = TreeProvider.UseAutomaticOrdering;
            TreeProvider.UseAutomaticOrdering = false;

            // Process template documents
            foreach (DataRow drDoc in TemplateDocuments.Tables[0].Rows)
            {
                if (DocumentHelper.IsDocumentTypeAllowed(editedNode, ValidationHelper.GetInteger(drDoc["NodeClassID"], 0)))
                {
                    string nodeAlias     = drDoc["NodeAlias"].ToString().ToLowerCSafe();
                    string contNodeAlias = ";" + nodeAlias + ";";

                    // Set marks
                    bool existing = existingDocs.Contains(contNodeAlias);
                    bool selected = selectedDocs.Contains(contNodeAlias);

                    int      nodeId     = ValidationHelper.GetInteger(drDoc["NodeID"], 0);
                    string   docCulture = ValidationHelper.GetString(drDoc["DocumentCulture"], "");
                    TreeNode srcNode    = DocumentHelper.GetDocument(nodeId, docCulture, editedNode.TreeProvider);

                    // Check if section exists
                    if (srcNode != null)
                    {
                        // Copy or remove marked document sections
                        if (selected)
                        {
                            if (!existing)
                            {
                                CopyDocumentSection(srcNode, editedNode, TreeProvider);
                            }
                        }
                        else
                        {
                            if (existing)
                            {
                                // Select node to delete
                                var aliasPath = editedNode.NodeAliasPath + "/" + nodeAlias;
                                var combineWithDefaultCulture = SettingsKeyInfoProvider.GetBoolValue(SiteContext.CurrentSiteName + ".CMSCombineWithDefaultCulture");

                                TreeProvider tree    = new TreeProvider(MembershipContext.AuthenticatedUser);
                                TreeNode     delNode = tree.SelectSingleNode(SiteContext.CurrentSiteName, aliasPath, LocalizationContext.PreferredCultureCode, combineWithDefaultCulture);

                                if (delNode != null)
                                {
                                    DeleteDocumentSection(delNode, TreeProvider);
                                }
                            }
                        }

                        // Process additional operations
                        if (selected && !existing)
                        {
                            switch (nodeAlias)
                            {
                            // Create department forum
                            case FORUM_DOCUMENT_ALIAS:
                                CreateDepartmentForumGroup(editedNode);
                                CreateDepartmentForumSearchIndex(editedNode);
                                break;

                            // Create media library
                            case MEDIA_DOCUMENT_ALIAS:
                                CreateDepartmentMediaLibrary(editedNode);
                                break;
                            }
                        }
                    }
                }
            }

            // Set previous ordering
            TreeProvider.UseAutomaticOrdering = orgUseAutomaticOrdering;
        }
        mDocumentSaved = true;
    }
    private void sendconf2(UserInfo ui, string emailtype, string[,] macros)
    {
        SiteInfo         currentSite          = SiteContext.CurrentSite;
        ContextResolver  resolver             = MacroContext.CurrentResolver;
        EventLogProvider ev                   = new EventLogProvider();
        bool             requiresConfirmation = SettingsKeyInfoProvider.GetBoolValue(currentSite.SiteName + ".CMSRegistrationEmailConfirmation");
        bool             requiresAdminApprove = false;
        bool             SendWelcomeEmail     = true;

        #region "Welcome Emails (confirmation, waiting for approval)"

        bool error = false;
        //  EventLogProvider ev = new EventLogProvider();
        // EmailTemplateInfo template = null;

        string            emailSubject = null;
        string            templateName = null;
        EmailTemplateInfo template     = null;

        // Send welcome message with username and password, with confirmation link, user must confirm registration
        template     = EmailTemplateProvider.GetEmailTemplate("E-commerce-OrderNotificationToCustomerBO", currentSite.SiteName);
        emailSubject = EmailHelper.GetSubject(template, "Votre commande: " + ShoppingCart.Order.OrderID);

        //mail type

        if (template != null)
        {
            EventLogProvider p = new EventLogProvider();
            p.LogEvent("I", DateTime.Now, "test 11", "code BO");
            // Set resolver
            resolver.SourceParameters = macros;

            // Email message
            EmailMessage email = new EmailMessage();
            email.EmailFormat = EmailFormatEnum.Default;
            email.Recipients  = ShoppingCart.Customer.CustomerEmail;

            p.LogEvent("I", DateTime.Now, "MAIL: " + ShoppingCart.Customer.CustomerEmail, "code BO");
            email.From = SettingsKeyInfoProvider.GetStringValue(currentSite.SiteName + ".CMSStoreSendEmailsFrom");//EmailHelper.GetSender(template, SettingsKeyProvider.GetStringValue(currentSite.SiteName + ".CMSStoreSendEmailsTo"));
            p.LogEvent("I", DateTime.Now, "MAIL: " + SettingsKeyInfoProvider.GetStringValue(currentSite.SiteName + ".CMSStoreSendEmailsTo"), "code BO");
            //string templatetext = template.TemplateText.Replace("\r\n\t\tVotre compte 2MAD a �t� cr��. Veuillez valider votre inscription en cliquant sur le lien ci-dessous.  <br />\r\n<a href=\"{%confirmaddress%}\">{%confirmaddress%}</a>\r\n<br />\r\n<br />\r\nVos identifiants :", " ");


            int n = ShoppingCart.ShoppingCartBillingAddressID; //ECommerceContext.CurrentShoppingCart.ShoppingCartBillingAddressID

            //take address info
            SqlConnection con3 = new SqlConnection(ConfigurationManager.ConnectionStrings["CMSConnectionString"].ConnectionString);
            con3.Open();
            var         stringQuery = "select * from COM_Address WHERE AddressID  = " + n;
            SqlCommand  cmd3        = new SqlCommand(stringQuery, con3);
            IDataReader reader      = cmd3.ExecuteReader();
            AddressInfo ai2         = new AddressInfo();
            var         temp        = "";
            while (reader.Read())
            {
                ai2.AddressLine1     = Convert.ToString(reader.GetValue(2));
                ai2.AddressLine2     = Convert.ToString(reader.GetValue(3));
                temp                 = ai2.GetStringValue(Convert.ToString(reader.GetValue(17)), Convert.ToString(reader.GetValue(17)));
                ai2.AddressZip       = Convert.ToString(reader.GetValue(5));
                ai2.AddressCity      = Convert.ToString(reader.GetValue(4));
                ai2.AddressCountryID = Convert.ToInt32(reader.GetValue(8));
            }
            con3.Dispose();
            // Take country name
            SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["CMSConnectionString"].ConnectionString);
            con.Open();
            var        stringQuery2 = " select CountryName from CMS_Country where CountryID = " + ai2.AddressCountryID;
            SqlCommand cmd2         = new SqlCommand(stringQuery2, con);
            string     c            = (string)cmd2.ExecuteScalar();
            con.Dispose();

            // take sous total {%(TotalPrice-TotalShipping).Format(Currency.CurrencyFormatString)#%}
            var    s1 = ShoppingCart.TotalPrice - ShoppingCart.TotalShipping;
            string s  = CurrencyInfoProvider.GetFormattedPrice(s1, ShoppingCart.Currency).ToString();

            // take frais d'envoi {%TotalShipping.Format(Currency.CurrencyFormatString)#%}
            var    fr    = ShoppingCart.TotalShipping;
            string frais = CurrencyInfoProvider.GetFormattedPrice(fr, ShoppingCart.Currency).ToString();

            // take {%TotalPrice.Format(Currency.CurrencyFormatString)#%}
            var    pr   = ShoppingCart.TotalPrice;
            string prix = CurrencyInfoProvider.GetFormattedPrice(pr, ShoppingCart.Currency).ToString();

            // take items
            string panier = "<table cellpadding='0' cellspacing='0'> <tbody>";

            foreach (ShoppingCartItemInfo item in ShoppingCart.CartItems)
            {
                var    t1    = item.TotalPrice;
                string total = CurrencyInfoProvider.GetFormattedPrice(t1, ShoppingCart.Currency).ToString();
                panier = panier + "<tr valign='top'>";
                panier = panier + "<td style='background-color:#e4e4e4;padding:8px 10px;margin-bottom:10px;display:block'> <table cellpadding='0' cellspacing='0'> <tbody> <tr valign='middle'> <td style='color:#3c3341;font-size:11px;font-family:Arial,Helvetica,sans-serif;text-transform:uppercase;border-right:#b3b3b3 1px solid' width='265' height='30'>" + item.SKU.SKUName + "</td> <td style='background-color:#fff;color:#241d29;font-size:16px;font-family:Arial,Helvetica,sans-serif;font-weight:bold;text-align:center;margin:0 10px;display:block;vertical-align:middle;line-height:30px' width='37' height='30'>" + item.CartItemUnits + "</td><td style='color:#241d29;font-size:16px;font-family:Arial,Helvetica,sans-serif;text-transform:uppercase;font-weight:bold;border-left:#b3b3b3 1px solid;text-align:center' width='70' height='30'> " + total + "</td></tr></tbody></table></td>";
                panier = panier + "</tr>";
            }
            panier = panier + "</tbody> </table >";

            string templatetext = template.TemplateText.Replace("#number", ShoppingCart.Order.OrderInvoiceNumber).Replace("#facturation", "<b>" + ShoppingCart.Customer.CustomerFirstName + " " + ShoppingCart.Customer.CustomerLastName + "</b><br/>" + temp + " " + ai2.AddressLine1 + "<br/>" + ai2.AddressLine2 + "<br/>" + ai2.AddressZip + " " + ai2.AddressCity + "<br/>" + c).Replace("#shipping", ShoppingCart.ShippingOption.ShippingOptionDisplayName).Replace("#payment", ShoppingCart.PaymentOption.PaymentOptionDisplayName).Replace("#soustotal", s).Replace("#prixtotal", prix).Replace("#fraisdenvoi", frais).Replace("#items", panier);

            email.Body = resolver.ResolveMacros(templatetext);

            resolver.EncodeResolvedValues = false;
            email.PlainTextBody           = resolver.ResolveMacros(template.TemplatePlainText);
            email.Subject = resolver.ResolveMacros(emailSubject);
            //email.CcRecipients = "*****@*****.**";
            //p.LogEvent("I",DateTime.Now,"mail admin"+ShoppingCart,"code BO");
            email.CcRecipients  = template.TemplateCc;
            email.BccRecipients = template.TemplateBcc;

            try
            {
                MetaFileInfoProvider.ResolveMetaFileImages(email, template.TemplateID, EmailObjectType.EMAILTEMPLATE, MetaFileInfoProvider.OBJECT_CATEGORY_TEMPLATE);
                // Send the e-mail immediately
                EmailSender.SendEmail(currentSite.SiteName, email, true);
                p.LogEvent("I", DateTime.Now, "after try ttt", "code BO");
            }
            catch (Exception ex)
            {
                ev.LogEvent("E", "EMAIL NON ENVOYE", ex);
            }
        }

        #endregion
    }
    /// <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;
            }
        }
    }
Ejemplo n.º 22
0
 /// <summary>
 /// Returns true, if site condition should be included in the filter.
 /// Site condition should not be applied, if the user is global admin as well as the filter is placed
 /// in online marketing UI within 'Users' application with 'sharing site accounts amongst sites' setting turned on.
 /// </summary>
 private bool IncludeSiteCondition()
 {
     return(!(IsOnlineUsersUI() &&
              (CMSActionContext.CurrentUser?.CheckPrivilegeLevel(UserPrivilegeLevelEnum.GlobalAdmin) ?? false) &&
              SettingsKeyInfoProvider.GetBoolValue("CMSSiteSharedAccounts")));
 }
Ejemplo n.º 23
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;
                }
            }
        }
    }
Ejemplo n.º 24
0
    /// <summary>
    /// OnInit event.
    /// </summary>
    protected override void OnInit(EventArgs e)
    {
        int querySiteID = QueryHelper.GetInteger("siteid", 0);

        // Do not allow other than current site ID out of global scope.
        var uiContext = UIContextHelper.GetUIContext(this);

        SiteID = ApplicationUIHelper.IsAccessibleOnlyByGlobalAdministrator(uiContext.UIElement) ? querySiteID : SiteContext.CurrentSiteID;

        if (ModuleEntryManager.IsModuleLoaded(ModuleName.COMMUNITY))
        {
            Control ctrl = LoadUserControl(GROUP_SELECTOR_PATH);
            if (ctrl != null)
            {
                mSelectInGroups    = ctrl as FormEngineUserControl;
                ctrl.ID            = "selGroups";
                ctrl               = LoadUserControl(GROUP_SELECTOR_PATH);
                mSelectNotInGroups = ctrl as FormEngineUserControl;
                ctrl.ID            = "selNoGroups";

                plcGroups.Visible = true;
                plcSelectInGroups.Controls.Add(mSelectInGroups);
                plcSelectNotInGroups.Controls.Add(mSelectNotInGroups);

                mSelectNotInGroups.SetValue("UseFriendlyMode", true);
                mSelectInGroups.IsLiveSite = false;
                mSelectInGroups.SetValue("UseFriendlyMode", true);
                mSelectNotInGroups.IsLiveSite = false;
            }
        }

        if (DisplayScore && SettingsKeyInfoProvider.GetBoolValue(SiteContext.CurrentSiteName + ".CMSEnableOnlineMarketing"))
        {
            Control ctrl = LoadUserControl(SCORE_SELECTOR_PATH);
            if (ctrl != null)
            {
                ctrl.ID        = "selectScore";
                mScoreSelector = ctrl as FormEngineUserControl;
                if (mScoreSelector != null)
                {
                    plcUpdateContent.Controls.Add(mScoreSelector);
                    mScoreSelector.SetValue("AllowAll", false);
                    mScoreSelector.SetValue("AllowEmpty", true);
                }
            }
        }
        else
        {
            plcScore.Visible             = false;
            lblScore.AssociatedControlID = null;
        }

        InitializeDropDownLists();

        base.OnInit(e);

        plcDisplayAnonymous.Visible = ContactManagementPermission && SessionManager.StoreOnlineUsersInDatabase && EnableDisplayingGuests;
        if (!RequestHelper.IsPostBack())
        {
            chkDisplayAnonymous.Checked = DisplayGuestsByDefault;
        }

        siteSelector.DropDownSingleSelect.AutoPostBack = true;
    }
 /// <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"));
 }
Ejemplo n.º 26
0
    protected void SetupControl()
    {
        // Check permissions
        var  user = MembershipContext.AuthenticatedUser;
        bool siteContactsAllowed   = user.IsAuthorizedPerResource(ModuleName.CONTACTMANAGEMENT, "ReadContacts");
        bool globalContactsAllowed = user.IsAuthorizedPerResource(ModuleName.CONTACTMANAGEMENT, "ReadGlobalContacts") && SettingsKeyInfoProvider.GetBoolValue(SiteContext.CurrentSiteName + ".CMSCMGlobalContacts");

        if (!siteContactsAllowed && !globalContactsAllowed)
        {
            lblInfo.Visible = true;
            lblInfo.Text    = GetString("om.myaccounts.notallowedtoreadcontacts");
            return;
        }

        // Create additional restriction if only site or global objects are allowed
        string where = null;
        if (!globalContactsAllowed)
        {
            where = SqlHelper.AddWhereCondition(where, "ContactSiteID IS NOT NULL");
        }
        if (!siteContactsAllowed)
        {
            where = SqlHelper.AddWhereCondition(where, "ContactSiteID IS NULL");
        }

        // Display accounts on current site or global site (if one of those shouldn't be displayed, it's filtered above)
        where = SqlHelper.AddWhereCondition(where, "ContactSiteID = " + SiteContext.CurrentSiteID + " OR ContactSiteID IS NULL");

        gridElem.Visible               = true;
        gridElem.WhereCondition        = SqlHelper.AddWhereCondition("ContactOwnerUserID=" + user.UserID + " AND ContactMergedWithContactID IS NULL", where);
        gridElem.OnExternalDataBound  += gridElem_OnExternalDataBound;
        gridElem.Pager.DefaultPageSize = PageSize;

        ScriptHelper.RegisterDialogScript(Page);

        SetVisibleColumns();
    }
Ejemplo n.º 27
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;
            }
        }
    }
Ejemplo n.º 28
0
    /// <summary>
    /// Loads data.
    /// </summary>
    public void ReloadData(bool forceReload)
    {
        if (!StopProcessing)
        {
            SetContext();

            lblInfo.Text    = string.Empty;
            lblInfo.Visible = false;

            if (pi == null)
            {
                pi            = PollInfoProvider.GetPollInfo(PollCodeName, PollSiteID, PollGroupID);
                hasPermission = HasPermission();
                isOpened      = IsOpened();
            }

            // Show poll if current user has permission or if poll should be displayed even if user is not authorized
            // and if poll is opened or if poll should be opened even if it is not opened
            // ... and show group poll if it is poll of current group
            bool showPoll = (pi != null) && (hasPermission || !HideWhenNotAuthorized) && (isOpened || !HideWhenNotOpened);
            // Show site poll only if it is poll of current site
            if (showPoll && (pi.PollSiteID > 0) && (pi.PollSiteID != SiteContext.CurrentSiteID))
            {
                showPoll = false;
            }

            // Show global poll only if it is allowed for current site
            if (showPoll && (pi.PollSiteID == 0))
            {
                showPoll = SettingsKeyInfoProvider.GetBoolValue(SiteContext.CurrentSiteName + ".CMSPollsAllowGlobal");
            }

            if (showPoll)
            {
                Visible = true;

                // Load title
                lblTitle.Text = HTMLHelper.HTMLEncode(pi.PollTitle);
                // Load question
                lblQuestion.Text = HTMLHelper.HTMLEncode(pi.PollQuestion);

                if ((!forceReload) || ((forceReload) && (ShowResultsAfterVote)))
                {
                    // Add answer section
                    CreateAnswerSection(forceReload, CheckVoted && PollInfoProvider.HasVoted(pi.PollID));
                }
                else
                {
                    // Hide answer panel
                    pnlAnswer.Visible = false;
                }

                if ((forceReload) && (isOpened))
                {
                    // Hide footer with vote button
                    pnlFooter.Visible = false;

                    // Add poll response after voting
                    if ((errMessage != null) && (errMessage.Trim() != ""))
                    {
                        // Display message if error occurs
                        lblInfo.Text     = errMessage;
                        lblInfo.CssClass = "ErrorMessage";
                    }
                    else
                    {
                        // Display poll response message
                        lblResult.Text = HTMLHelper.HTMLEncode(pi.PollResponseMessage);
                    }
                }
                else if (isOpened)
                {
                    if (hasPermission && !(CheckVoted && (PollInfoProvider.HasVoted(pi.PollID))))
                    {
                        // Display footer wiht vote button
                        pnlFooter.Visible = true;
                        btnVote.Text      = ButtonText;
                    }
                    else
                    {
                        pnlFooter.Visible = false;
                    }
                }
                else
                {
                    pnlFooter.Visible = false;
                    lblInfo.Text      = GetString("Polls.Closed");
                }
            }
            else
            {
                Visible = false;
            }

            ReleaseContext();
        }
    }
    /// <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);
    }
    /// <summary>
    /// Saves the changed settings
    /// </summary>
    /// <param name="isSite">Indicates whether changed settings is global or site</param>
    private void Save(bool isSite)
    {
        // This action is permitted only for global administrators
        if (MembershipContext.AuthenticatedUser.IsGlobalAdministrator)
        {
            if (!String.IsNullOrEmpty(SettingsKeys))
            {
                String[] keys = SettingsKeys.Split(';');
                foreach (String key in keys)
                {
                    if (key != String.Empty)
                    {
                        String objectKey    = ";" + key + ";";
                        String siteKeyName  = SiteName + "." + key;
                        bool   globalObject = (GlobalObjects.Contains(objectKey) || KeyScope == DisabledModuleScope.Global);
                        bool   siteObject   = SiteObjects.Contains(objectKey);

                        // If setting is global or site (or both), set global(site) settings no matter what button (site or global) was clicked
                        if (globalObject || siteObject)
                        {
                            if (globalObject)
                            {
                                if (!SettingsKeyInfoProvider.GetBoolValue(key))
                                {
                                    SettingsKeyInfoProvider.SetValue(key, true);
                                }
                            }

                            if (siteObject)
                            {
                                if (!SettingsKeyInfoProvider.GetBoolValue(siteKeyName))
                                {
                                    SettingsKeyInfoProvider.SetValue(siteKeyName, true);
                                }
                            }

                            continue;
                        }

                        // Test first if settings is disabled
                        if (!SettingsKeyInfoProvider.GetBoolValue(siteKeyName))
                        {
                            String keyName = isSite ? siteKeyName : key;
                            try
                            {
                                SettingsKeyInfoProvider.SetValue(keyName, true);
                            }
                            catch (Exception)
                            {
                                if (isSite)
                                {
                                    // Site settings does not exists. Save as global then
                                    SettingsKeyInfoProvider.SetValue(key, true);
                                }
                            }

                            // If global enabled and site still disabled - enable it also
                            if (!isSite && (KeyScope != DisabledModuleScope.Global))
                            {
                                // If settings not enabled, inherit from global
                                if (!SettingsKeyInfoProvider.GetBoolValue(siteKeyName))
                                {
                                    SettingsKeyInfoProvider.SetValue(siteKeyName, null);
                                }
                            }
                        }
                    }
                }
            }

            // Reload UI if necessary
            if (ReloadUIWhenModuleEnabled)
            {
                URLHelper.Redirect(RequestContext.CurrentURL);
            }
        }
    }