/// <summary>
    /// Check whether current user is allowed to modify another user. Return "" or error message.
    /// </summary>
    /// <param name="userId">Modified user</param>
    protected string ValidateGlobalAndDeskAdmin(int userId)
    {
        string result = String.Empty;

        if (MembershipContext.AuthenticatedUser.IsGlobalAdministrator)
        {
            return(result);
        }

        UserInfo userInfo = UserInfoProvider.GetUserInfo(userId);

        if (userInfo == null)
        {
            result = GetString("Administration-User.WrongUserId");
        }
        else
        {
            if (userInfo.IsGlobalAdministrator)
            {
                result = GetString("Administration-User.NotAllowedToModify");
            }
        }
        return(result);
    }
Exemplo n.º 2
0
        public HttpResponseMessage EditUser([FromBody] JObject postData)
        {
            string username, firstName, surname;

            //parsing postdata
            try
            {
                username  = postData["username"].ToObject <string>();
                firstName = postData["firstName"].ToObject <string>();
                surname   = postData["surname"].ToObject <string>();
            }
            catch (Exception e)
            {
                return(Request.CreateResponse(HttpStatusCode.ServiceUnavailable, new { errorMessage = e.Message }));
            }
            try
            {
                //gets the user by username
                UserInfo updateUser = UserInfoProvider.GetUserInfo(username);
                if (updateUser != null)
                {
                    // Updates the user's properties
                    updateUser.FirstName = firstName;
                    updateUser.LastName  = surname;

                    // Saves the changes
                    UserInfoProvider.SetUserInfo(updateUser);
                    //everything is OK, the updated user is also returned
                    return(Request.CreateResponse(HttpStatusCode.OK, new { user = updateUser }));
                }
            } catch (Exception e)
            {
                return(Request.CreateResponse(HttpStatusCode.ServiceUnavailable, new { errorMessage = e.Message }));
            }
            return(Request.CreateResponse(HttpStatusCode.ServiceUnavailable, new { errorMessage = "User is null" }));
        }
Exemplo n.º 3
0
    /// <summary>
    /// Check whether current user is allowed to modify another user. Return "" or error message.
    /// </summary>
    /// <param name="userId">Modified user</param>
    protected string ValidateGlobalAndDeskAdmin(int userId)
    {
        string result = String.Empty;

        if (CMSContext.CurrentUser.IsGlobalAdministrator)
        {
            return(result);
        }

        UserInfo userInfo = UserInfoProvider.GetUserInfo(userId);

        if (userInfo == null)
        {
            result = GetString("Administration-User.WrongUserId");
        }
        else
        {
            if (userInfo.IsGlobalAdministrator)
            {
                result = String.Format(GetString("Administration-User.NotAllowedToModifySpecific"), userInfo.FullName + " (" + userInfo.UserName + ")");
            }
        }
        return(result);
    }
    /// <summary>
    /// Undoes checkout for given node.
    /// </summary>
    /// <param name="node">Node to undo checkout</param>
    /// <returns>FALSE when document is checked out and checkbox for undoing checkout is not checked</returns>
    private bool UndoPossibleCheckOut(TreeNode node)
    {
        if (!node.IsCheckedOut)
        {
            return(true);
        }

        string nodeAliasPath = HTMLHelper.HTMLEncode(node.NodeAliasPath + " (" + node.DocumentCulture + ")");

        if (CurrentUser.UserID != node.DocumentCheckedOutByUserID)
        {
            // Get checked out message
            var    user     = UserInfoProvider.GetUserInfo(node.DocumentCheckedOutByUserID);
            string userName = user != null?user.GetFormattedUserName(false) : "";

            AddError(String.Format(GetString("editcontent.documentnamecheckedoutbyanother"), nodeAliasPath, userName));
        }
        else
        {
            AddError(String.Format(GetString("content.checkedoutdocument"), nodeAliasPath));
        }

        return(false);
    }
Exemplo n.º 5
0
    /// <summary>
    /// Decides whether enable generate new password e-mail.
    /// </summary>
    private string GetGeneratePasswordScript()
    {
        string clientClick = null;

        if (ui == null)
        {
            ui = UserInfoProvider.GetUserInfo(UserID);
        }

        if (ui != null)
        {
            if (string.IsNullOrEmpty(ui.Email))
            {
                clientClick = "var flag = confirm('" + GetString("user.showpasswarning") + "');" + ((ui.UserID == MembershipContext.AuthenticatedUser.UserID) ? "if(flag) {window.top.HideWarning();}" : "") + "return flag;";
            }
            // Set hide action if user extend validity of his own account
            else if (ui.UserID == MembershipContext.AuthenticatedUser.UserID)
            {
                clientClick += "window.top.HideWarning()";
            }
        }

        return(clientClick);
    }
    /// <summary>
    /// Check whether current user is allowed to modify another user. Return "" or error message.
    /// </summary>
    /// <param name="userId">Modified user</param>
    protected string ValidateGlobalAndDeskAdmin(int userId)
    {
        string result = String.Empty;

        if (MembershipContext.AuthenticatedUser.CheckPrivilegeLevel(UserPrivilegeLevelEnum.Admin))
        {
            return(result);
        }

        UserInfo userInfo = UserInfoProvider.GetUserInfo(userId);

        if (userInfo == null)
        {
            result = GetString("Administration-User.WrongUserId");
        }
        else
        {
            if (userInfo.CheckPrivilegeLevel(UserPrivilegeLevelEnum.Admin))
            {
                result = String.Format(GetString("Administration-User.NotAllowedToModifySpecific"), $"{HTMLHelper.HTMLEncode(userInfo.FullName)} ({userInfo.UserName})");
            }
        }
        return(result);
    }
Exemplo n.º 7
0
    /// <summary>
    /// Indicates whether the 'Send password' button should be enabled or not.
    /// </summary>
    private bool DisplaySendPaswd()
    {
        if (ui == null)
        {
            ui = UserInfoProvider.GetUserInfo(UserID);
        }

        if (ui != null)
        {
            // Password is stored in plain text, allow sending
            if (string.IsNullOrEmpty(ui.UserPasswordFormat) && !string.IsNullOrEmpty(ui.Email))
            {
                return(true);
            }

            // Set hide action if user extend validity of his own account
            if (ui.UserID == MembershipContext.AuthenticatedUser.UserID)
            {
                ButtonSetPassword.OnClientClick += "window.top.HideWarning()";
            }
        }

        return(false);
    }
Exemplo n.º 8
0
    /// <summary>
    /// Returns true if custom settings are valid against given clone setting.
    /// </summary>
    /// <param name="settings">Clone settings</param>
    public override bool IsValid(CloneSettings settings)
    {
        if (!chkGeneratePassword.Checked)
        {
            if (!txtPassword.IsValid())
            {
                ShowError(AuthenticationHelper.GetPolicyViolationMessage(SiteContext.CurrentSiteName));
                return(false);
            }
        }

        // Get sites of original user
        var user      = (UserInfo)InfoToClone;
        var siteTable = UserInfoProvider.GetUserSites(user.UserID).Column("SiteName");
        var sites     = siteTable.Select(s => s["SiteName"].ToString());

        // Check that e-mail is unique
        if (!UserInfoProvider.IsEmailUnique(txtEmail.Text.Trim(), sites, 0))
        {
            throw new Exception(GetString("cloneUser.uniqueEmailRequired"));
        }

        return(true);
    }
Exemplo n.º 9
0
    /// <summary>
    /// Check whether current user is allowed to modify another user.
    /// </summary>
    /// <param name="userId">Modified user</param>
    /// <returns>"" or error message.</returns>
    protected static string ValidateGlobalAndDeskAdmin(int userId)
    {
        string result = String.Empty;

        if (CMSContext.CurrentUser.IsGlobalAdministrator)
        {
            return(result);
        }

        UserInfo userInfo = UserInfoProvider.GetUserInfo(userId);

        if (userInfo == null)
        {
            result = ResHelper.GetString("Administration-User.WrongUserId");
        }
        else
        {
            if (userInfo.IsGlobalAdministrator)
            {
                result = ResHelper.GetString("Administration-User.NotAllowedToModify");
            }
        }
        return(result);
    }
Exemplo n.º 10
0
    /// <summary>
    /// Check whether current user is allowed to modify another user.
    /// </summary>
    /// <param name="userId">Modified user</param>
    /// <returns>"" or error message.</returns>
    protected static string ValidateGlobalAndDeskAdmin(int userId)
    {
        string result = String.Empty;

        if (MembershipContext.AuthenticatedUser.CheckPrivilegeLevel(UserPrivilegeLevelEnum.Admin))
        {
            return(result);
        }

        UserInfo userInfo = UserInfoProvider.GetUserInfo(userId);

        if (userInfo == null)
        {
            result = ResHelper.GetString("Administration-User.WrongUserId");
        }
        else
        {
            if (userInfo.CheckPrivilegeLevel(UserPrivilegeLevelEnum.Admin))
            {
                result = ResHelper.GetString("Administration-User.NotAllowedToModify");
            }
        }
        return(result);
    }
Exemplo n.º 11
0
    /// <summary>
    /// Signs in given user.
    /// </summary>
    /// <param name="ui">User that will be signed in.</param>
    /// <param name="facebookUserId">The user's Facebook ID</param>
    /// <param name="facebookAccessToken">The user's access token retrieved from Facebook</param>
    /// <param name="mapFacebookProfile">Indicates whether the user's Facebook profile is mapped to user info or not</param>
    private void SignInUser(UserInfo ui, string facebookUserId, string facebookAccessToken, bool mapFacebookProfile = true)
    {
        // Login existing user
        if (ui.Enabled)
        {
            if (mapFacebookProfile)
            {
                MapFacebookUserProfile(FacebookUserProfileMappingTriggerEnum.Login, ui, facebookUserId, facebookAccessToken);
            }

            // Ban IP addresses which are blocked for login
            BannedIPInfoProvider.CheckIPandRedirect(SiteContext.CurrentSiteName, BanControlEnum.Login);

            // Create autentification cookie
            AuthenticationHelper.SetAuthCookieWithUserData(ui.UserName, true, Session.Timeout, new string[] { "facebooklogon" });
            UserInfoProvider.SetPreferredCultures(ui);

            int      contactId = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui);
            Activity activity  = new ActivityUserLogin(contactId, ui, DocumentContext.CurrentDocument, AnalyticsContext.ActivityEnvironmentVariables);
            activity.Log();

            // Redirect user
            string returnUrl = QueryHelper.GetString("returnurl", null);
            if (String.IsNullOrEmpty(returnUrl))
            {
                returnUrl = URLHelper.RemoveParameterFromUrl(RequestContext.CurrentURL, CONFIRMATION_URLPARAMETER);
            }
            URLHelper.Redirect(returnUrl);
        }
        else
        {
            // User is disabled
            lblError.Text    = GetString("membership.userdisabled");
            lblError.Visible = true;
        }
    }
Exemplo n.º 12
0
    private UserInfo VerifyKenticoUser(string userName, string emailAddress)
    {
        UserInfo user = CMS.Membership.UserInfoProvider.GetUserInfo(userName);

        if (user == null)
        {
            user           = new UserInfo();
            user.UserName  = userName;
            user.FirstName = "Temp";
            user.LastName  = "Temp";
            user.FullName  = "Temp";
            user.Email     = emailAddress;

            user.PreferredCultureCode = "en-us";
            user.PasswordFormat       = "SHA1";
            user.Enabled = true;

            CMS.Membership.UserInfoProvider.SetUserInfo(user);
            CMS.Membership.UserInfoProvider.SetPassword(userName, userName);
            UserInfoProvider.AddUserToSite(userName, CMS.SiteProvider.SiteContext.CurrentSiteName);
        }

        return(user);
    }
    /// <summary>
    /// Sets password of current user.
    /// </summary>
    protected void btnSetPassword_Click(object sender, EventArgs e)
    {
        if (UserInfo == null)
        {
            return;
        }

        if (txtConfirmPassword.Text != passStrength.Text)
        {
            ShowError(GetString("Administration-User_Edit_Password.PasswordsDoNotMatch"));
            return;
        }

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

        if (!UserInfo.CheckPermissions(PermissionsEnum.Modify, SiteContext.CurrentSiteName, MembershipContext.AuthenticatedUser))
        {
            RedirectToAccessDenied(GetString("general.actiondenied"));
        }

        // Password has been changed
        string password = passStrength.Text;

        UserInfoProvider.SetPassword(UserInfo, password);

        ShowChangesSaved();

        if (SettingsKeyInfoProvider.GetBoolValue(SiteContext.CurrentSiteName + ".CMSSendPasswordResetConfirmation"))
        {
            AuthenticationHelper.SendPasswordResetConfirmation(UserInfo, SiteContext.CurrentSiteName, "USERSAPP", "Membership.PasswordResetConfirmation");
        }
    }
Exemplo n.º 14
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 = CMSContext.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(CMSContext.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, password, true, SendWelcomeEmail);

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

                        // Log registration into analytics
                        AuthenticationHelper.TrackUserRegistration(TrackConversionName, ConversionValue, siteName, ui);

                        Activity activity = new ActivityRegistration(ui, CMSContext.CurrentDocument, CMSContext.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;
            }
        }
    }
Exemplo n.º 15
0
    /// <summary>
    /// Saves modified image data.
    /// </summary>
    /// <param name="name">Image name</param>
    /// <param name="extension">Image extension</param>
    /// <param name="mimetype">Image mimetype</param>
    /// <param name="title">Image title</param>
    /// <param name="description">Image description</param>
    /// <param name="binary">Image binary data</param>
    /// <param name="width">Image width</param>
    /// <param name="height">Image height</param>
    private void SaveImage(string name, string extension, string mimetype, string title, string description, byte[] binary, int width, int height)
    {
        LoadInfos();

        // Save image data depending to image type
        switch (baseImageEditor.ImageType)
        {
        // Process attachment
        case ImageHelper.ImageTypeEnum.Attachment:
            if (ai != null)
            {
                // Save new data
                try
                {
                    // Get the node
                    TreeNode node = DocumentHelper.GetDocument(ai.AttachmentDocumentID, baseImageEditor.Tree);

                    // Check Create permission when saving temporary attachment, check Modify permission else
                    NodePermissionsEnum permissionToCheck = (ai.AttachmentFormGUID == Guid.Empty) ? NodePermissionsEnum.Modify : NodePermissionsEnum.Create;

                    // Check permission
                    if (MembershipContext.AuthenticatedUser.IsAuthorizedPerDocument(node, permissionToCheck) != AuthorizationResultEnum.Allowed)
                    {
                        baseImageEditor.ShowError(GetString("attach.actiondenied"));
                        SavingFailed = true;

                        return;
                    }

                    if (!IsNameUnique(name, extension))
                    {
                        baseImageEditor.ShowError(GetString("img.namenotunique"));
                        SavingFailed = true;

                        return;
                    }


                    // Ensure automatic check-in/ check-out
                    bool            useWorkflow = false;
                    bool            autoCheck   = false;
                    WorkflowManager workflowMan = WorkflowManager.GetInstance(baseImageEditor.Tree);
                    if (node != null)
                    {
                        // Get workflow info
                        WorkflowInfo wi = workflowMan.GetNodeWorkflow(node);

                        // Check if the document uses workflow
                        if (wi != null)
                        {
                            useWorkflow = true;
                            autoCheck   = !wi.UseCheckInCheckOut(CurrentSiteName);
                        }

                        // Check out the document
                        if (autoCheck)
                        {
                            VersionManager.CheckOut(node, node.IsPublished, true);
                            VersionHistoryID = node.DocumentCheckedOutVersionHistoryID;
                        }

                        // Workflow has been lost, get published attachment
                        if (useWorkflow && (VersionHistoryID == 0))
                        {
                            ai = AttachmentInfoProvider.GetAttachmentInfo(ai.AttachmentGUID, CurrentSiteName);
                        }

                        // If extension changed update CMS.File extension
                        if ((node.NodeClassName.ToLowerCSafe() == "cms.file") && (node.DocumentExtensions != extension))
                        {
                            // Update document extensions if no custom are used
                            if (!node.DocumentUseCustomExtensions)
                            {
                                node.DocumentExtensions = extension;
                            }
                            node.SetValue("DocumentType", extension);

                            DocumentHelper.UpdateDocument(node, baseImageEditor.Tree);
                        }
                    }

                    if (ai != null)
                    {
                        // Test all parameters to empty values and update new value if available
                        if (name != "")
                        {
                            if (!name.EndsWithCSafe(extension))
                            {
                                ai.AttachmentName = name + extension;
                            }
                            else
                            {
                                ai.AttachmentName = name;
                            }
                        }
                        if (extension != "")
                        {
                            ai.AttachmentExtension = extension;
                        }
                        if (mimetype != "")
                        {
                            ai.AttachmentMimeType = mimetype;
                        }

                        ai.AttachmentTitle       = title;
                        ai.AttachmentDescription = description;

                        if (binary != null)
                        {
                            ai.AttachmentBinary = binary;
                            ai.AttachmentSize   = binary.Length;
                        }
                        if (width > 0)
                        {
                            ai.AttachmentImageWidth = width;
                        }
                        if (height > 0)
                        {
                            ai.AttachmentImageHeight = height;
                        }
                        // Ensure object
                        ai.MakeComplete(true);
                        if (VersionHistoryID > 0)
                        {
                            VersionManager.SaveAttachmentVersion(ai, VersionHistoryID);
                        }
                        else
                        {
                            AttachmentInfoProvider.SetAttachmentInfo(ai);

                            // Log the synchronization and search task for the document
                            if (node != null)
                            {
                                // Update search index for given document
                                if (DocumentHelper.IsSearchTaskCreationAllowed(node))
                                {
                                    SearchTaskInfoProvider.CreateTask(SearchTaskTypeEnum.Update, TreeNode.OBJECT_TYPE, SearchFieldsConstants.ID, node.GetSearchID(), node.DocumentID);
                                }

                                DocumentSynchronizationHelper.LogDocumentChange(node, TaskTypeEnum.UpdateDocument, baseImageEditor.Tree);
                            }
                        }

                        // Check in the document
                        if ((autoCheck) && (VersionManager != null) && (VersionHistoryID > 0) && (node != null))
                        {
                            VersionManager.CheckIn(node, null);
                        }
                    }
                }
                catch (Exception ex)
                {
                    baseImageEditor.ShowError(GetString("img.errors.processing"), tooltipText: ex.Message);
                    EventLogProvider.LogException("Image editor", "SAVEIMAGE", ex);
                    SavingFailed = true;
                }
            }
            break;

        case ImageHelper.ImageTypeEnum.PhysicalFile:
            if (!String.IsNullOrEmpty(filePath))
            {
                var currentUser = MembershipContext.AuthenticatedUser;
                if ((currentUser != null) && currentUser.IsGlobalAdministrator)
                {
                    try
                    {
                        string physicalPath = Server.MapPath(filePath);
                        string newPath      = physicalPath;

                        // Write binary data to the disk
                        File.WriteAllBytes(physicalPath, binary);

                        // Handle rename of the file
                        if (!String.IsNullOrEmpty(name))
                        {
                            newPath = DirectoryHelper.CombinePath(Path.GetDirectoryName(physicalPath), name);
                        }
                        if (!String.IsNullOrEmpty(extension))
                        {
                            string oldExt = Path.GetExtension(physicalPath);
                            newPath = newPath.Substring(0, newPath.Length - oldExt.Length) + extension;
                        }

                        // Move the file
                        if (newPath != physicalPath)
                        {
                            File.Move(physicalPath, newPath);
                        }
                    }
                    catch (Exception ex)
                    {
                        baseImageEditor.ShowError(GetString("img.errors.processing"), tooltipText: ex.Message);
                        EventLogProvider.LogException("Image editor", "SAVEIMAGE", ex);
                        SavingFailed = true;
                    }
                }
                else
                {
                    baseImageEditor.ShowError(GetString("img.errors.rights"));
                    SavingFailed = true;
                }
            }
            break;

        // Process metafile
        case ImageHelper.ImageTypeEnum.Metafile:

            if (mf != null)
            {
                if (UserInfoProvider.IsAuthorizedPerObject(mf.MetaFileObjectType, mf.MetaFileObjectID, PermissionsEnum.Modify, CurrentSiteName, MembershipContext.AuthenticatedUser))
                {
                    try
                    {
                        // Test all parameters to empty values and update new value if available
                        if (name.CompareToCSafe("") != 0)
                        {
                            if (!name.EndsWithCSafe(extension))
                            {
                                mf.MetaFileName = name + extension;
                            }
                            else
                            {
                                mf.MetaFileName = name;
                            }
                        }
                        if (extension.CompareToCSafe("") != 0)
                        {
                            mf.MetaFileExtension = extension;
                        }
                        if (mimetype.CompareToCSafe("") != 0)
                        {
                            mf.MetaFileMimeType = mimetype;
                        }

                        mf.MetaFileTitle       = title;
                        mf.MetaFileDescription = description;

                        if (binary != null)
                        {
                            mf.MetaFileBinary = binary;
                            mf.MetaFileSize   = binary.Length;
                        }
                        if (width > 0)
                        {
                            mf.MetaFileImageWidth = width;
                        }
                        if (height > 0)
                        {
                            mf.MetaFileImageHeight = height;
                        }

                        // Save new data
                        MetaFileInfoProvider.SetMetaFileInfo(mf);

                        if (RefreshAfterAction)
                        {
                            if (String.IsNullOrEmpty(externalControlID))
                            {
                                baseImageEditor.LtlScript.Text = ScriptHelper.GetScript("Refresh();");
                            }
                            else
                            {
                                baseImageEditor.LtlScript.Text = ScriptHelper.GetScript(String.Format("InitRefresh({0}, false, false, '{1}', 'refresh')", ScriptHelper.GetString(externalControlID), mf.MetaFileGUID));
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        baseImageEditor.ShowError(GetString("img.errors.processing"), tooltipText: ex.Message);
                        EventLogProvider.LogException("Image editor", "SAVEIMAGE", ex);
                        SavingFailed = true;
                    }
                }
                else
                {
                    baseImageEditor.ShowError(GetString("img.errors.rights"));
                    SavingFailed = true;
                }
            }
            break;
        }
    }
Exemplo n.º 16
0
    /// <summary>
    /// Initializes common properties used for processing image.
    /// </summary>
    private void baseImageEditor_InitializeProperties()
    {
        var currentUser = MembershipContext.AuthenticatedUser;

        // Process attachment
        switch (baseImageEditor.ImageType)
        {
        // Process physical file
        case ImageHelper.ImageTypeEnum.PhysicalFile:
        {
            if (!String.IsNullOrEmpty(filePath))
            {
                if ((currentUser != null) && currentUser.IsGlobalAdministrator)
                {
                    try
                    {
                        // Load the file from disk
                        string physicalPath = Server.MapPath(filePath);
                        byte[] data         = File.ReadAllBytes(physicalPath);
                        baseImageEditor.ImgHelper = new ImageHelper(data);
                    }
                    catch
                    {
                        baseImageEditor.LoadingFailed = true;
                        baseImageEditor.ShowError(GetString("img.errors.loading"));
                    }
                }
                else
                {
                    baseImageEditor.LoadingFailed = true;
                    baseImageEditor.ShowError(GetString("img.errors.rights"));
                }
            }
            else
            {
                baseImageEditor.LoadingFailed = true;
                baseImageEditor.ShowError(GetString("img.errors.loading"));
            }
        }
        break;

        // Process metafile
        case ImageHelper.ImageTypeEnum.Metafile:
        {
            // Get metafile
            mf = MetaFileInfoProvider.GetMetaFileInfoWithoutBinary(metafileGuid, CurrentSiteName, true);

            // If file is not null and current user is global administrator then set image
            if (mf != null)
            {
                if (UserInfoProvider.IsAuthorizedPerObject(mf.MetaFileObjectType, mf.MetaFileObjectID, PermissionsEnum.Modify, CurrentSiteName, MembershipContext.AuthenticatedUser))
                {
                    // Ensure metafile binary data
                    mf.MetaFileBinary = MetaFileInfoProvider.GetFile(mf, CurrentSiteName);
                    if (mf.MetaFileBinary != null)
                    {
                        baseImageEditor.ImgHelper = new ImageHelper(mf.MetaFileBinary);
                    }
                    else
                    {
                        baseImageEditor.LoadingFailed = true;
                        baseImageEditor.ShowError(GetString("img.errors.loading"));
                    }
                }
                else
                {
                    baseImageEditor.LoadingFailed = true;
                    baseImageEditor.ShowError(GetString("img.errors.rights"));
                }
            }
            else
            {
                baseImageEditor.LoadingFailed = true;
                baseImageEditor.ShowError(GetString("img.errors.loading"));
            }
        }
        break;

        default:
        {
            baseImageEditor.Tree = new TreeProvider(currentUser);

            // If using workflow then get versioned attachment
            if (VersionHistoryID != 0)
            {
                // Get the versioned attachment
                AttachmentHistoryInfo attachmentVersion = VersionManager.GetAttachmentVersion(VersionHistoryID, attachmentGuid);
                if (attachmentVersion != null)
                {
                    // Create new attachment object
                    ai = new AttachmentInfo(attachmentVersion.Generalized.DataClass);
                    if (ai != null)
                    {
                        AttachmentHistoryID           = attachmentVersion.AttachmentHistoryID;
                        ai.AttachmentVersionHistoryID = VersionHistoryID;
                    }
                }
            }
            // Else get file without binary data
            else
            {
                ai = AttachmentInfoProvider.GetAttachmentInfoWithoutBinary(attachmentGuid, CurrentSiteName);
            }

            // If file is not null and current user is set
            if (ai != null)
            {
                TreeNode node;
                if (ai.AttachmentDocumentID > 0)
                {
                    node = baseImageEditor.Tree.SelectSingleDocument(ai.AttachmentDocumentID);
                }
                else
                {
                    // Get parent node ID in case attachment is edited for document not created yet
                    int parentNodeId = QueryHelper.GetInteger("parentId", 0);

                    node = baseImageEditor.Tree.SelectSingleNode(parentNodeId);
                }

                // If current user has appropriate permissions then set image - check hash fro live site otherwise check node permissions
                if ((currentUser != null) && (node != null) && ((IsLiveSite && QueryHelper.ValidateHash("hash")) || (!IsLiveSite && (currentUser.IsAuthorizedPerDocument(node, NodePermissionsEnum.Modify) == AuthorizationResultEnum.Allowed))))
                {
                    // Ensure attachment binary data
                    if (VersionHistoryID == 0)
                    {
                        ai.AttachmentBinary = AttachmentInfoProvider.GetFile(ai, CurrentSiteName);
                    }

                    if (ai.AttachmentBinary != null)
                    {
                        baseImageEditor.ImgHelper = new ImageHelper(ai.AttachmentBinary);
                    }
                    else
                    {
                        baseImageEditor.LoadingFailed = true;
                        baseImageEditor.ShowError(GetString("img.errors.loading"));
                    }
                }
                else
                {
                    baseImageEditor.LoadingFailed = true;
                    baseImageEditor.ShowError(GetString("img.errors.filemodify"));
                }
            }
            else
            {
                baseImageEditor.LoadingFailed = true;
                baseImageEditor.ShowError(GetString("img.errors.loading"));
            }
        }
        break;
        }

        // Check that image is in supported formats
        if ((!baseImageEditor.LoadingFailed) && (baseImageEditor.ImgHelper.ImageFormatToString() == null))
        {
            baseImageEditor.LoadingFailed = true;
            baseImageEditor.ShowError(GetString("img.errors.format"));
        }

        // Disable editor if loading failed
        if (baseImageEditor.LoadingFailed)
        {
            Enabled = false;
        }
    }
Exemplo n.º 17
0
    /// <summary>
    /// Reload data.
    /// </summary>
    public override void ReloadData()
    {
        ForumPostInfo fpi = null;
        ForumInfo     fi  = null;


        #region "Load data"

        if (PostData != null)
        {
            fpi = new ForumPostInfo(PostData);
        }

        if (fpi == null)
        {
            fpi = PostInfo;
        }

        if (fpi != null)
        {
            PostData = fpi.Generalized.DataClass;
            fi       = ForumInfoProvider.GetForumInfo(fpi.PostForumID);
        }
        else
        {
            return;
        }

        #endregion


        if (fi.ForumEnableAdvancedImage)
        {
            ltlText.AllowedControls = ControlsHelper.ALLOWED_FORUM_CONTROLS;
        }
        else
        {
            ltlText.AllowedControls = "none";
        }

        lnkUserName.Text = HTMLHelper.HTMLEncode(fpi.PostUserName);

        // Display converted datetime for live site
        lblDate.Text = " (" + CMSContext.ConvertDateTime(ValidationHelper.GetDateTime(fpi.PostTime, DateTimeHelper.ZERO_TIME), this).ToString() + ")";

        lblSubject.Text = HTMLHelper.HTMLEncode(fpi.PostSubject);
        DiscussionMacroHelper dmh = new DiscussionMacroHelper();
        dmh.EnableBold          = fi.ForumEnableFontBold;
        dmh.EnableItalics       = fi.ForumEnableFontItalics;
        dmh.EnableStrikeThrough = fi.ForumEnableFontStrike;
        dmh.EnableUnderline     = fi.ForumEnableFontUnderline;
        dmh.EnableCode          = fi.ForumEnableCodeSnippet;
        dmh.EnableColor         = fi.ForumEnableFontColor;
        dmh.EnableImage         = fi.ForumEnableImage || fi.ForumEnableAdvancedImage;
        dmh.EnableQuote         = fi.ForumEnableQuote;
        dmh.EnableURL           = fi.ForumEnableURL || fi.ForumEnableAdvancedURL;
        dmh.MaxImageSideSize    = fi.ForumImageMaxSideSize;
        dmh.QuotePostText       = GetString("DiscussionMacroResolver.QuotePostText");

        if (fi.ForumHTMLEditor)
        {
            dmh.EncodeText = false;
            dmh.ConvertLineBreaksToHTML = false;
        }
        else
        {
            dmh.EncodeText = true;
            dmh.ConvertLineBreaksToHTML = true;
        }

        ltlText.Text = "<div class=\"PostText\">" + dmh.ResolveMacros(fpi.PostText) + "</div>";

        userAvatar.Text = AvatarImage(fpi);

        if (DisplayBadgeInfo)
        {
            if (fpi.PostUserID > 0)
            {
                UserInfo ui = UserInfoProvider.GetUserInfo(fpi.PostUserID);
                if ((ui != null) && !ui.IsPublic())
                {
                    BadgeInfo bi = BadgeInfoProvider.GetBadgeInfo(ui.UserSettings.UserBadgeID);
                    if (bi != null)
                    {
                        ltlBadge.Text = "<div class=\"Badge\">" + HTMLHelper.HTMLEncode(bi.BadgeDisplayName) + "</div>";
                    }
                }
            }

            // Set public badge if no badge is set
            if (String.IsNullOrEmpty(ltlBadge.Text))
            {
                ltlBadge.Text = "<div class=\"Badge\">" + GetString("Forums.PublicBadge") + "</div>";
            }
        }

        if (EnableSignature)
        {
            if (fpi.PostUserSignature.Trim() != "")
            {
                plcSignature.Visible = true;
                ltrSignature.Text    = HTMLHelper.HTMLEncode(fpi.PostUserSignature);
            }
        }

        if (!DisplayOnly)
        {
            string threadId = ForumPostInfoProvider.GetPostRootFromIDPath(ValidationHelper.GetString(GetData(PostData, "PostIdPath"), "")).ToString();

            // Reply
            if (IsAvailable(PostData, ForumActionType.Reply))
            {
                lnkReply.Visible     = true;
                lnkReply.Text        = GetString("Forums_WebInterface_ForumPost.replyLinkText");
                lnkReply.NavigateUrl = URLHelper.UpdateParameterInUrl(GetURL(PostData, ForumActionType.Reply), "threadid", threadId);
            }
            else
            {
                lnkReply.Visible = false;
            }

            // Quote
            if (IsAvailable(PostData, ForumActionType.Quote))
            {
                lnkQuote.Visible     = true;
                lnkQuote.Text        = GetString("Forums_WebInterface_ForumPost.quoteLinkText");
                lnkQuote.NavigateUrl = URLHelper.UpdateParameterInUrl(GetURL(PostData, ForumActionType.Quote), "threadid", threadId);
            }
            else
            {
                lnkQuote.Visible = false;
            }

            // Display subscribe link
            if (IsAvailable(PostData, ForumActionType.SubscribeToPost))
            {
                lnkSubscribe.Visible     = true;
                lnkSubscribe.Text        = GetString("Forums_WebInterface_ForumPost.Subscribe");
                lnkSubscribe.NavigateUrl = URLHelper.UpdateParameterInUrl(GetURL(PostData, ForumActionType.SubscribeToPost), "threadid", threadId);
            }
            else
            {
                lnkSubscribe.Visible = false;
            }

            lnkUserName.CssClass = "PostUserLink";

            if (!String.IsNullOrEmpty(fpi.PostUserMail) && (fi.ForumDisplayEmails))
            {
                lnkUserName.NavigateUrl = "mailto:" + HTMLHelper.HTMLEncode(fpi.PostUserMail) + "?subject=" + HTMLHelper.HTMLEncode(fpi.PostSubject);
                lnkUserName.CssClass    = "PostUser";
            }
        }

        // Display action panel only if reply to link or subscription link are visible
        plcActions.Visible = ((lnkReply.Visible || lnkSubscribe.Visible || lnkQuote.Visible) & !DisplayOnly);

        if ((lnkReply.Visible) && (lnkQuote.Visible || lnkSubscribe.Visible))
        {
            lblActionSeparator.Visible = true;
        }

        if ((lnkQuote.Visible) && (lnkSubscribe.Visible))
        {
            lblActionSeparator2.Visible = true;
        }
    }
Exemplo n.º 18
0
    /// <summary>
    /// Save subscriber.
    /// </summary>
    /// <returns>Subscriver info object</returns>
    private SubscriberInfo SaveSubscriber()
    {
        // Check if a subscriber exists first
        SubscriberInfo sb = null;

        if (AllowUserSubscribers && (MembershipContext.AuthenticatedUser != null) && AuthenticationHelper.IsAuthenticated())
        {
            sb = SubscriberInfoProvider.GetSubscriberInfo(UserInfo.OBJECT_TYPE, MembershipContext.AuthenticatedUser.UserID, SiteContext.CurrentSiteID);
        }
        else
        {
            sb = SubscriberInfoProvider.GetSubscriberInfo(txtEmail.Text, SiteContext.CurrentSiteID);
        }

        if ((sb == null) || ((chooseMode) && (sb != null)))
        {
            // Create subscriber
            if (sb == null)
            {
                sb = new SubscriberInfo();
            }

            // Handle authenticated user
            if (AllowUserSubscribers && (MembershipContext.AuthenticatedUser != null) && AuthenticationHelper.IsAuthenticated())
            {
                // Get user info and copy first name, last name or full name to new subscriber
                UserInfo ui = UserInfoProvider.GetUserInfo(MembershipContext.AuthenticatedUser.UserID);
                if (ui != null)
                {
                    if (!DataHelper.IsEmpty(ui.FirstName) && !DataHelper.IsEmpty(ui.LastName))
                    {
                        sb.SubscriberFirstName = ui.FirstName;
                        sb.SubscriberLastName  = ui.LastName;
                    }
                    else
                    {
                        sb.SubscriberFirstName = ui.FullName;
                    }
                    // Full name consists of "user " and user full name
                    sb.SubscriberFullName = new SubscriberFullNameFormater().GetUserSubscriberName(ui.FullName);
                }
                else
                {
                    return(null);
                }

                sb.SubscriberType      = UserInfo.OBJECT_TYPE;
                sb.SubscriberRelatedID = MembershipContext.AuthenticatedUser.UserID;
            }
            // Work with non-authenticated user
            else
            {
                sb.SubscriberEmail = txtEmail.Text.Trim();

                // First name
                if (DisplayFirstName)
                {
                    sb.SubscriberFirstName = txtFirstName.Text;
                }
                else
                {
                    sb.SubscriberFirstName = string.Empty;
                }

                // Last name
                if (DisplayLastName)
                {
                    sb.SubscriberLastName = txtLastName.Text;
                }
                else
                {
                    sb.SubscriberLastName = string.Empty;
                }

                // Full name
                sb.SubscriberFullName = (sb.SubscriberFirstName + " " + sb.SubscriberLastName).Trim();
            }

            // Set site ID
            sb.SubscriberSiteID = SiteContext.CurrentSiteID;

            // Check subscriber limits
            if (!SubscriberInfoProvider.LicenseVersionCheck(RequestContext.CurrentDomain, FeatureEnum.Subscribers, ObjectActionEnum.Insert))
            {
                lblError.Visible = true;
                lblError.Text    = GetString("LicenseVersionCheck.Subscribers");
                return(null);
            }

            // Save subscriber info
            SubscriberInfoProvider.SetSubscriberInfo(sb);
        }

        if (sb != null)
        {
            // Create membership between current contact and subscriber
            ModuleCommands.OnlineMarketingCreateRelation(sb.SubscriberID, MembershipType.NEWSLETTER_SUBSCRIBER, ModuleCommands.OnlineMarketingGetCurrentContactID());
        }

        // Hide all
        visibleLastName  = false;
        visibleFirstName = false;
        visibleEmail     = false;

        pnlButtonSubmit.Visible = false;
        pnlImageSubmit.Visible  = false;

        plcNwsList.Visible = false;

        // Clear the form
        txtEmail.Text     = string.Empty;
        txtFirstName.Text = string.Empty;
        txtLastName.Text  = string.Empty;

        // Return subscriber info object
        return(sb);
    }
Exemplo n.º 19
0
    /// <summary>
    /// Saves webpart properties.
    /// </summary>
    public bool Save()
    {
        // Check MVT/CP security
        if (VariantID > 0)
        {
            // Check OnlineMarketing permissions.
            if (!CheckPermissions("Manage"))
            {
                ShowError(GetString("general.modifynotallowed"));
                return(false);
            }
        }

        // Save the data
        if ((pi != null) && (pti != null) && (templateInstance != null) && SaveForm(form))
        {
            if (SynchronizationHelper.IsCheckedOutByOtherUser(pti))
            {
                string   userName = null;
                UserInfo ui       = UserInfoProvider.GetUserInfo(pti.Generalized.IsCheckedOutByUserID);
                if (ui != null)
                {
                    userName = HTMLHelper.HTMLEncode(ui.GetFormattedUserName(IsLiveSite));
                }

                ShowError(string.Format(GetString("ObjectEditMenu.CheckedOutByAnotherUser"), pti.TypeInfo.ObjectType, pti.DisplayName, userName));
                return(false);
            }

            // Add web part if new
            if (IsNewWebPart)
            {
                int webpartId = ValidationHelper.GetInteger(WebPartID, 0);

                // Ensure layout zone flag
                if (QueryHelper.GetBoolean("layoutzone", false))
                {
                    WebPartZoneInstance zone = pti.TemplateInstance.EnsureZone(ZoneID);
                    zone.LayoutZone = true;
                }

                webPartInstance = PortalHelper.AddNewWebPart(webpartId, ZoneID, false, ZoneVariantID, Position, templateInstance);

                // Set default layout
                if (wpi.WebPartParentID > 0)
                {
                    WebPartLayoutInfo wpli = WebPartLayoutInfoProvider.GetDefaultLayout(wpi.WebPartID);
                    if (wpli != null)
                    {
                        webPartInstance.SetValue("WebPartLayout", wpli.WebPartLayoutCodeName);
                    }
                }
            }

            webPartInstance.XMLVersion = 1;
            if (IsNewVariant)
            {
                webPartInstance             = webPartInstance.Clone();
                webPartInstance.VariantMode = VariantModeFunctions.GetVariantModeEnum(QueryHelper.GetString("variantmode", String.Empty).ToLowerInvariant());
            }

            // Get basic form's data row and update web part
            SaveFormToWebPart(form);

            // Set new position if set
            if (PositionLeft > 0)
            {
                webPartInstance.SetValue("PositionLeft", PositionLeft);
            }
            if (PositionTop > 0)
            {
                webPartInstance.SetValue("PositionTop", PositionTop);
            }

            bool isWebPartVariant = (VariantID > 0) || (ZoneVariantID > 0) || IsNewVariant;
            if (!isWebPartVariant)
            {
                // Save the changes
                CMSPortalManager.SaveTemplateChanges(pi, templateInstance, WidgetZoneTypeEnum.None, ViewModeEnum.Design, tree);
            }
            else
            {
                Hashtable varProperties = WindowHelper.GetItem("variantProperties") as Hashtable;
                // Save changes to the web part variant
                VariantHelper.SaveWebPartVariantChanges(webPartInstance, VariantID, ZoneVariantID, VariantMode, varProperties);
            }

            // Reload the form (because of macro values set only by JS)
            form.ReloadData();

            // Clear the cached web part
            CacheHelper.TouchKey("webpartinstance|" + InstanceGUID.ToString().ToLowerInvariant());

            ShowChangesSaved();

            return(true);
        }

        if (webPartInstance?.ParentZone?.ParentTemplateInstance != null)
        {
            // Reload the zone/web part variants when saving of the form fails
            webPartInstance.ParentZone.ParentTemplateInstance.LoadVariants(true, VariantModeEnum.None);
        }

        return(false);
    }
    /// <summary>
    /// Setup edit values.
    /// </summary>
    private void SetupEdit()
    {
        if (FileInfo != null)
        {
            // Fill edit form
            txtEditName.Text        = FileInfo.FileName;
            txtEditDescription.Text = FileInfo.FileDescription;
            txtEditTitle.Text       = FileInfo.FileTitle;
            UserInfo currentUserInfo = CMSContext.CurrentUser;
            SiteInfo currentSiteInfo = CMSContext.CurrentSite;

            // Created by
            string userName = null;

            UserInfo ui = UserInfoProvider.GetFullUserInfo(FileInfo.FileCreatedByUserID);
            if (ui != null)
            {
                if (ui.IsPublic())
                {
                    userName = GetString("general.na");
                }
                else
                {
                    userName = ui.FullName;
                }
            }
            else
            {
                userName = GetString("general.na");
            }
            lblCreatedByVal.Text = userName;

            // Created when
            DateTime dtCreated = ValidationHelper.GetDateTime(FileInfo.FileCreatedWhen, DateTimeHelper.ZERO_TIME);
            lblCreatedWhenVal.Text = TimeZoneHelper.ConvertToUserTimeZone(dtCreated, false, currentUserInfo, currentSiteInfo);

            // Modified when
            DateTime dtModified = ValidationHelper.GetDateTime(FileInfo.FileModifiedWhen, DateTimeHelper.ZERO_TIME);
            lblModifiedVal.Text = TimeZoneHelper.ConvertToUserTimeZone(dtModified, false, currentUserInfo, currentSiteInfo);

            // Get system file info
            string filePath = MediaFileInfoProvider.GetMediaFilePath(FileInfo.FileLibraryID, FileInfo.FilePath);
            if (File.Exists(filePath))
            {
                FileInfo sysFileInfo = CMS.IO.FileInfo.New(filePath);

                // File modified when
                DateTime dtFileModified = ValidationHelper.GetDateTime(sysFileInfo.LastWriteTime, DateTimeHelper.ZERO_TIME);
                // Display only if system time is
                if ((dtFileModified - dtModified).TotalSeconds > 5)
                {
                    lblFileModifiedVal.Text = TimeZoneHelper.ConvertToUserTimeZone(dtFileModified, false, currentUserInfo, currentSiteInfo);

                    plcFileModified.Visible = true;
                    plcRefresh.Visible      = true;
                }
                else
                {
                    plcFileModified.Visible = false;
                    plcRefresh.Visible      = false;
                }

                // File size
                if (sysFileInfo.Length != FileInfo.FileSize)
                {
                    lblFileSizeVal.Text = DataHelper.GetSizeString(sysFileInfo.Length);
                    plcFileSize.Visible = true;
                    plcRefresh.Visible  = true;
                }
                else
                {
                    plcFileSize.Visible = false;
                    plcRefresh.Visible  = false;
                }
            }

            // Size
            lblSizeVal.Text = DataHelper.GetSizeString(FileInfo.FileSize);

            // Extension
            lblExtensionVal.Text = FileInfo.FileExtension.TrimStart('.').ToLowerCSafe();

            // Dimensions
            if (ImageHelper.IsImage(FileInfo.FileExtension))
            {
                lblDimensionsVal.Text = FileInfo.FileImageWidth + " x " + FileInfo.FileImageHeight;
                plcDimensions.Visible = true;
            }
            else
            {
                plcDimensions.Visible = false;
            }
        }
        else
        {
            txtEditName.Text        = "";
            txtEditDescription.Text = "";
            txtEditTitle.Text       = "";
        }
    }
Exemplo n.º 21
0
        public override ImportResult Process(byte[] importFileData, ExcelType type, int siteId)
        {
            if ((UserIds?.Count() ?? 0) == 0)
            {
                throw new ArgumentOutOfRangeException("No users selected to upload addresses to");
            }

            var rows      = GetExcelRows(importFileData, type);
            var addresses = GetDtosFromExcelRows <AddressDto>(rows);

            statusMessages.Clear();

            foreach (var userId in UserIds)
            {
                var user = UserInfoProvider.GetUserInfo(userId);

                if (user == null)
                {
                    statusMessages.Add($"Nonexisting user : {userId}");
                    continue;
                }

                var customer = EnsureCustomer(user, siteId);

                var currentItemNumber = 1;
                foreach (var addressDto in addresses)
                {
                    try
                    {
                        List <string> validationResults;
                        if (!ValidatorHelper.ValidateDto(addressDto, out validationResults, "field {0} - {1}"))
                        {
                            validationResults.Sort();

                            statusMessages.Add($"Item number {currentItemNumber} has invalid values ({ string.Join("; ", validationResults) })");
                            continue;
                        }

                        CreateCustomerAddress(customer.CustomerID, new UserDto
                        {
                            Country      = addressDto.Country,
                            State        = addressDto.State,
                            AddressLine  = addressDto.AddressLine,
                            AddressLine2 = addressDto.AddressLine2,
                            City         = addressDto.City,
                            ContactName  = addressDto.ContactName,
                            PostalCode   = addressDto.PostalCode,
                            PhoneNumber  = addressDto.PhoneNumber
                        });
                    }
                    catch (Exception ex)
                    {
                        statusMessages.Add("There was an error when processing item number " + currentItemNumber);
                        EventLogProvider.LogException("Import addresses", "EXCEPTION", ex);
                    }

                    currentItemNumber++;
                }
            }

            return(new ImportResult
            {
                AllMessagesCount = statusMessages.AllMessagesCount,
                ErrorMessages = statusMessages.ToArray()
            });
        }
Exemplo n.º 22
0
    protected void Page_Load(object sender, EventArgs e)
    {
        // Check license
        if (DataHelper.GetNotEmpty(RequestContext.CurrentDomain, string.Empty) != string.Empty)
        {
            LicenseHelper.CheckFeatureAndRedirect(RequestContext.CurrentDomain, FeatureEnum.Friends);
        }

        userId      = QueryHelper.GetInteger("userid", 0);
        currentUser = MembershipContext.AuthenticatedUser;
        int requestedId  = QueryHelper.GetInteger("requestid", 0);
        int friendshipId = 0;

        // Check if request is for current user or another user with permission to manage it
        if (currentUser.IsPublic() || ((currentUser.UserID != userId) && !currentUser.IsAuthorizedPerResource("CMS.Friends", "Manage")))
        {
            RedirectToAccessDenied("CMS.Friends", "Manage");
        }

        FriendsApprove.SelectedFriends = null;
        FriendsApprove.IsLiveSite      = true;

        PageTitle.TitleText = GetString("friends.approvefriendship");
        // Multiple selection
        if (Request["ids"] != null)
        {
            string[] items = Request["ids"].Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
            if (items.Length > 0)
            {
                ArrayList friends = new ArrayList();
                foreach (string item in items)
                {
                    friends.Add(ValidationHelper.GetInteger(item, 0));
                }
                FriendsApprove.SelectedFriends = friends;
                if (friends.Count == 1)
                {
                    friendshipId = Convert.ToInt32(friends[0]);
                }
            }
        }
        // For one user
        else
        {
            FriendsApprove.RequestedUserID = requestedId;
        }

        FriendInfo fi = null;

        if (friendshipId != 0)
        {
            fi = FriendInfoProvider.GetFriendInfo(friendshipId);
            // Set edited object
            EditedObject = fi;
        }
        else if (requestedId != 0)
        {
            fi = FriendInfoProvider.GetFriendInfo(userId, requestedId);
            // Set edited object
            EditedObject = fi;
        }

        if (fi != null)
        {
            UserInfo requestedUser = (userId == fi.FriendRequestedUserID) ? UserInfoProvider.GetFullUserInfo(fi.FriendUserID) : UserInfoProvider.GetFullUserInfo(fi.FriendRequestedUserID);
            string   fullUserName  = Functions.GetFormattedUserName(requestedUser.UserName, requestedUser.FullName, requestedUser.UserNickName, true);
            Page.Title          = GetString("friends.approvefriendshipwith") + " " + HTMLHelper.HTMLEncode(fullUserName);
            PageTitle.TitleText = Page.Title;
        }

        // Set current user
        FriendsApprove.UserID = userId;
    }
Exemplo n.º 23
0
    /// <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 <ICampaignService> .Entry().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)
                int contactId = ModuleCommands.OnlineMarketingGetCurrentContactID();
                if (contactId > 0)
                {
                    ModuleCommands.OnlineMarketingCreateRelation(ui.UserID, MembershipType.CMS_USER, contactId);
                }

                // 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) && !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)
            {
                MembershipActivityLogger.LogRegistration(ui.UserName, DocumentContext.CurrentDocument);
                // Log login activity
                if (ui.Enabled)
                {
                    MembershipActivityLogger.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;
        }
    }
Exemplo n.º 24
0
    protected void Page_Load(object sender, EventArgs e)
    {
        userId      = QueryHelper.GetInteger("userid", 0);
        currentUser = MembershipContext.AuthenticatedUser;

        // Check license
        if (DataHelper.GetNotEmpty(RequestContext.CurrentDomain, string.Empty) != string.Empty)
        {
            LicenseHelper.CheckFeatureAndRedirect(RequestContext.CurrentDomain, FeatureEnum.Friends);
        }

        FriendsReject.SelectedFriends     = null;
        FriendsReject.OnCheckPermissions += FriendsReject_OnCheckPermissions;

        int requestedId  = QueryHelper.GetInteger("requestid", 0);
        int friendshipId = 0;

        Page.Title          = GetString("friends.rejectfriendship");
        PageTitle.TitleText = Page.Title;
        // Multiple selection
        if (Request["ids"] != null)
        {
            string[] items = Request["ids"].Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
            if (items.Length > 0)
            {
                ArrayList friends = new ArrayList();
                foreach (string item in items)
                {
                    friends.Add(ValidationHelper.GetInteger(item, 0));
                }
                FriendsReject.SelectedFriends = friends;
                if (friends.Count == 1)
                {
                    friendshipId = Convert.ToInt32(friends[0]);
                }
            }
        }
        // For one user
        else
        {
            FriendsReject.RequestedUserID = requestedId;
        }

        FriendInfo fi = null;

        if (friendshipId != 0)
        {
            fi = FriendInfoProvider.GetFriendInfo(friendshipId);
            // Set edited object
            EditedObject = fi;
        }
        else if (requestedId != 0)
        {
            fi = FriendInfoProvider.GetFriendInfo(userId, requestedId);
            // Set edited object
            EditedObject = fi;
        }

        if (fi != null)
        {
            UserInfo requestedUser = (userId == fi.FriendRequestedUserID) ? UserInfoProvider.GetFullUserInfo(fi.FriendUserID) : UserInfoProvider.GetFullUserInfo(fi.FriendRequestedUserID);
            string   fullUserName  = Functions.GetFormattedUserName(requestedUser.UserName, requestedUser.FullName, requestedUser.UserNickName, false);
            Page.Title          = GetString("friends.rejectfriendshipwith") + " " + HTMLHelper.HTMLEncode(fullUserName);
            PageTitle.TitleText = Page.Title;
        }

        // Set current user
        FriendsReject.UserID = userId;
    }
    /// <summary>
    /// Process valid values of this step.
    /// </summary>
    public override bool ProcessStep()
    {
        if (plcAccount.Visible)
        {
            string siteName = SiteContext.CurrentSiteName;

            // Existing account
            if (radSignIn.Checked)
            {
                // Authenticate user
                UserInfo ui = AuthenticationHelper.AuthenticateUser(txtUsername.Text.Trim(), txtPsswd1.Text, SiteContext.CurrentSiteName, false);
                if (ui == null)
                {
                    lblError.Text    = GetString("ShoppingCartCheckRegistration.LoginFailed");
                    lblError.Visible = true;
                    return(false);
                }

                // Sign in customer with existing account
                AuthenticationHelper.AuthenticateUser(ui.UserName, false);

                // Registered user has already started shopping as anonymous user -> Drop his stored shopping cart
                ShoppingCartInfoProvider.DeleteShoppingCartInfo(ui.UserID, siteName);

                // Assign current user to the current shopping cart
                ShoppingCart.User = ui;

                // Save changes to database
                if (!ShoppingCartControl.IsInternalOrder)
                {
                    ShoppingCartInfoProvider.SetShoppingCartInfo(ShoppingCart);
                }

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

                LoadStep(true);

                // Return false to get to Edit customer page
                return(false);
            }
            // New registration
            else if (radNewReg.Checked)
            {
                txtEmail2.Text             = txtEmail2.Text.Trim();
                pnlCompanyAccount1.Visible = chkCorporateBody.Checked;

                string[] siteList = { siteName };

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

                // Check if user exists
                UserInfo ui = UserInfoProvider.GetUserInfo(txtEmail2.Text);
                if (ui != null)
                {
                    lblError.Visible = true;
                    lblError.Text    = GetString("ShoppingCartUserRegistration.ErrorUserExists");
                    return(false);
                }

                // Check all sites where user will be assigned
                if (!UserInfoProvider.IsEmailUnique(txtEmail2.Text.Trim(), siteList, 0))
                {
                    lblError.Visible = true;
                    lblError.Text    = GetString("UserInfo.EmailAlreadyExist");
                    return(false);
                }

                // Create new customer and user account and sign in
                // User
                ui           = new UserInfo();
                ui.UserName  = txtEmail2.Text.Trim();
                ui.Email     = txtEmail2.Text.Trim();
                ui.FirstName = txtFirstName1.Text.Trim();
                ui.LastName  = txtLastName1.Text.Trim();
                ui.FullName  = ui.FirstName + " " + ui.LastName;
                ui.Enabled   = true;
                ui.SiteIndependentPrivilegeLevel = UserPrivilegeLevelEnum.None;
                ui.UserURLReferrer = CookieHelper.GetValue(CookieName.UrlReferrer);
                ui.UserCampaign    = Service <ICampaignService> .Entry().CampaignCode;

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

                try
                {
                    UserInfoProvider.SetPassword(ui, passStrength.Text);

                    foreach (string site in siteList)
                    {
                        UserInfoProvider.AddUserToSite(ui.UserName, site);

                        // Add user to roles
                        if (ShoppingCartControl.AssignToRoles != "")
                        {
                            AssignUserToRoles(ui.UserName, ShoppingCartControl.AssignToRoles, site);
                        }
                    }

                    // Log registered user
                    AnalyticsHelper.LogRegisteredUser(siteName, ui);

                    MembershipActivityLogger.LogRegistration(ui.UserName, DocumentContext.CurrentDocument);
                }
                catch (Exception ex)
                {
                    lblError.Visible = true;
                    lblError.Text    = ex.Message;
                    return(false);
                }

                // Customer
                CustomerInfo ci = new CustomerInfo();
                ci.CustomerFirstName = txtFirstName1.Text.Trim();
                ci.CustomerLastName  = txtLastName1.Text.Trim();
                ci.CustomerEmail     = txtEmail2.Text.Trim();

                ci.CustomerCompany           = "";
                ci.CustomerOrganizationID    = "";
                ci.CustomerTaxRegistrationID = "";
                if (chkCorporateBody.Checked)
                {
                    ci.CustomerCompany = txtCompany1.Text.Trim();
                    if (mShowOrganizationIDField)
                    {
                        ci.CustomerOrganizationID = txtOrganizationID.Text.Trim();
                    }
                    if (mShowTaxRegistrationIDField)
                    {
                        ci.CustomerTaxRegistrationID = txtTaxRegistrationID.Text.Trim();
                    }
                }

                ci.CustomerUserID  = ui.UserID;
                ci.CustomerSiteID  = 0;
                ci.CustomerCreated = DateTime.Now;
                CustomerInfoProvider.SetCustomerInfo(ci);

                // Track successful registration conversion
                string name = ShoppingCartControl.RegistrationTrackConversionName;
                ECommerceHelper.TrackRegistrationConversion(ShoppingCart.SiteName, name);

                CreateContactRelation(ci);

                // Sign in
                if (ui.Enabled)
                {
                    AuthenticationHelper.AuthenticateUser(ui.UserName, false);
                    ShoppingCart.User = ui;

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

                ShoppingCart.ShoppingCartCustomerID = ci.CustomerID;

                // Send new registration notification email
                if (ShoppingCartControl.SendNewRegistrationNotificationToAddress != "")
                {
                    SendRegistrationNotification(ui);
                }
            }
            // Anonymous customer
            else if (radAnonymous.Checked)
            {
                CustomerInfo ci = null;
                if (ShoppingCart.ShoppingCartCustomerID > 0)
                {
                    // Update existing customer account
                    ci = CustomerInfoProvider.GetCustomerInfo(ShoppingCart.ShoppingCartCustomerID);
                }
                if (ci == null)
                {
                    // Create new customer account
                    ci = new CustomerInfo();
                }

                ci.CustomerFirstName = txtFirstName2.Text.Trim();
                ci.CustomerLastName  = txtLastName2.Text.Trim();
                ci.CustomerEmail     = txtEmail3.Text.Trim();

                ci.CustomerCompany           = "";
                ci.CustomerOrganizationID    = "";
                ci.CustomerTaxRegistrationID = "";

                if (chkCorporateBody2.Checked)
                {
                    ci.CustomerCompany = txtCompany2.Text.Trim();
                    if (mShowOrganizationIDField)
                    {
                        ci.CustomerOrganizationID = txtOrganizationID2.Text.Trim();
                    }
                    if (mShowTaxRegistrationIDField)
                    {
                        ci.CustomerTaxRegistrationID = txtTaxRegistrationID2.Text.Trim();
                    }
                }

                ci.CustomerCreated = DateTime.Now;
                ci.CustomerSiteID  = SiteContext.CurrentSiteID;
                CustomerInfoProvider.SetCustomerInfo(ci);

                CreateContactRelation(ci);

                // Assign customer to shoppingcart
                ShoppingCart.ShoppingCartCustomerID = ci.CustomerID;
            }
            else
            {
                return(false);
            }
        }
        else
        {
            // Save the customer data
            bool         newCustomer = false;
            CustomerInfo ci          = CustomerInfoProvider.GetCustomerInfoByUserID(ShoppingCartControl.UserInfo.UserID);
            if (ci == null)
            {
                ci = new CustomerInfo();
                ci.CustomerUserID = ShoppingCartControl.UserInfo.UserID;
                ci.CustomerSiteID = 0;
                newCustomer       = true;
            }

            // Old email address
            string oldEmail = ci.CustomerEmail.ToLowerCSafe();

            ci.CustomerFirstName = txtEditFirst.Text.Trim();
            ci.CustomerLastName  = txtEditLast.Text.Trim();
            ci.CustomerEmail     = txtEditEmail.Text.Trim();

            pnlCompanyAccount2.Visible = chkEditCorpBody.Checked;

            ci.CustomerCompany           = "";
            ci.CustomerOrganizationID    = "";
            ci.CustomerTaxRegistrationID = "";
            if (chkEditCorpBody.Checked)
            {
                ci.CustomerCompany = txtEditCompany.Text.Trim();
                if (mShowOrganizationIDField)
                {
                    ci.CustomerOrganizationID = txtEditOrgID.Text.Trim();
                }
                if (mShowTaxRegistrationIDField)
                {
                    ci.CustomerTaxRegistrationID = txtEditTaxRegID.Text.Trim();
                }
            }

            // Update customer data
            CustomerInfoProvider.SetCustomerInfo(ci);

            // Update corresponding user email when required
            if (oldEmail != ci.CustomerEmail.ToLowerCSafe())
            {
                UserInfo user = UserInfoProvider.GetUserInfo(ci.CustomerUserID);
                if (user != null)
                {
                    user.Email = ci.CustomerEmail;
                    UserInfoProvider.SetUserInfo(user);
                }
            }

            if (newCustomer)
            {
                CreateContactRelation(ci);
            }

            // Set the shopping cart customer ID
            ShoppingCart.ShoppingCartCustomerID = ci.CustomerID;
        }

        try
        {
            if (!ShoppingCartControl.IsInternalOrder)
            {
                ShoppingCartInfoProvider.SetShoppingCartInfo(ShoppingCart);
            }

            ShoppingCart.InvalidateCalculations();
            return(true);
        }
        catch
        {
            return(false);
        }
    }
Exemplo n.º 26
0
    /// <summary>
    /// Reload data.
    /// </summary>
    public void LoadData()
    {
        if (mCommentsDataRow != null)
        {
            // Load comment data
            BlogCommentInfo bci = new BlogCommentInfo(mCommentsDataRow);
            if (bci != null)
            {
                CommentID = bci.CommentID;

                // Set user picture
                if (BlogpPoperties.EnableUserPictures)
                {
                    userPict.UserID           = bci.CommentUserID;
                    userPict.Width            = BlogpPoperties.UserPictureMaxWidth;
                    userPict.Height           = BlogpPoperties.UserPictureMaxHeight;
                    userPict.Visible          = true;
                    userPict.RenderOuterDiv   = true;
                    userPict.OuterDivCSSClass = "CommentUserPicture";

                    // Gravatar support
                    string avType = SettingsKeyInfoProvider.GetStringValue(SiteContext.CurrentSiteName + ".CMSAvatarType");
                    if (avType == AvatarInfoProvider.USERCHOICE)
                    {
                        UserInfo ui = UserInfoProvider.GetUserInfo(bci.CommentUserID);
                        if (ui != null)
                        {
                            avType = ui.UserSettings.UserAvatarType;
                        }
                        else
                        {
                            avType = AvatarInfoProvider.GRAVATAR;
                        }
                    }

                    userPict.UserEmail      = bci.CommentEmail;
                    userPict.UserAvatarType = avType;
                }
                else
                {
                    userPict.Visible = false;
                }

                if (!String.IsNullOrEmpty(bci.CommentUrl))
                {
                    lnkName.Text        = HTMLHelper.HTMLEncode(bci.CommentUserName);
                    lnkName.NavigateUrl = bci.CommentUrl;
                    // Add no follow attribute if it is required
                    if (HTMLHelper.UseNoFollowForUsersLinks(SiteContext.CurrentSiteName))
                    {
                        lnkName.Attributes.Add("rel", "nofollow");
                    }
                    lblName.Visible = false;
                }
                else
                {
                    lblName.Text    = HTMLHelper.HTMLEncode(bci.CommentUserName);
                    lnkName.Visible = false;
                }

                lblText.Text = GetHTMLEncodedCommentText(bci);
                lblDate.Text = TimeZoneMethods.ConvertDateTime(bci.CommentDate, this).ToString();

                string url = "~/CMSModules/Blogs/Controls/Comment_Edit.aspx";
                if (IsLiveSite)
                {
                    url = "~/CMSModules/Blogs/CMSPages/Comment_Edit.aspx";
                }

                lnkEdit.OnClientClick = "EditComment('" + ResolveUrl(url) + "?commentID=" + CommentID + "');return false;";

                // Initialize report abuse
                ucInlineAbuseReport.ReportTitle             = ResHelper.GetString("BlogCommentDetail.AbuseReport", SettingsKeyInfoProvider.GetStringValue(SiteContext.CurrentSiteName + ".CMSDefaultCulture")) + bci.CommentText;
                ucInlineAbuseReport.ReportObjectID          = CommentID;
                ucInlineAbuseReport.CMSPanel.Roles          = AbuseReportRoles;
                ucInlineAbuseReport.CMSPanel.SecurityAccess = AbuseReportSecurityAccess;
                ucInlineAbuseReport.CMSPanel.OwnerID        = AbuseReportOwnerID;
            }
        }
    }
    public override bool ProcessStep()
    {
        string siteName = SiteContext.CurrentSiteName;

        if (IsExistingAccount())
        {
            // Sign in customer with existing account

            // Authenticate user
            //UserInfo ui = UserInfoProvider.GetUserInfo(txtLogin.Text);

            UserInfo ui = AuthenticationHelper.AuthenticateUser(txtLogin.Text.Trim(), txtMotDePasse.Text, SiteContext.CurrentSiteName);

            if (ui == null)
            {
                // ShowError(ResHelper.GetString("ShoppingCartCheckRegistration.LoginFailed"));
                return(false);
            }

            // Set current user
            MembershipContext.AuthenticatedUser = new CurrentUserInfo(ui, true);
            UserInfoProvider.SetPreferredCultures(ui);

            // Sign in
            FormsAuthentication.SetAuthCookie(ui.UserName, false);

            // Registered user has already started shopping as anonymous user -> Drop his stored shopping cart
            ShoppingCartInfoProvider.DeleteShoppingCartInfo(ui.UserID, siteName);

            // Assign current user to the current shopping cart
            ShoppingCart.User = ui;

            // Save changes to database // Already done in the end of this method
            if (!this.ShoppingCartControl.IsInternalOrder)
            {
                ShoppingCartInfoProvider.SetShoppingCartInfo(this.ShoppingCartInfObj);
            }

            //Create a customer for the user if do not yet exist
            CustomerInfo ci = CustomerInfoProvider.GetCustomerInfoByUserID(this.ShoppingCartControl.UserInfo.UserID);
            if (ci == null)
            {
                ci = new CustomerInfo();
                ci.CustomerUserID  = this.ShoppingCartControl.UserInfo.UserID;
                ci.CustomerEnabled = true;
            }

            // Old email address
            //string oldEmail = ci.CustomerEmail.ToLower(); ;

            ci.CustomerFirstName = ui.FirstName;
            ci.CustomerLastName  = ui.LastName;
            ci.CustomerEmail     = ui.Email;

            ci.CustomerCompany           = "";
            ci.CustomerOrganizationID    = "";
            ci.CustomerTaxRegistrationID = "";

            // Update customer data
            CustomerInfoProvider.SetCustomerInfo(ci);

            // Set the shopping cart customer ID
            this.ShoppingCart.ShoppingCartCustomerID = ci.CustomerID;
        }
        else if (IsNewAccount())
        {
            txtEmail2.Text             = txtEmail2.Text.Trim();
            pnlCompanyAccount1.Visible = chkCorporateBody.Checked;

            // Check if user exists
            UserInfo ui = UserInfoProvider.GetUserInfo(txtEmail2.Text);
            if (ui != null)
            {
                lblError.Visible = true;
                lblError.Text    = GetString("ShoppingCartUserRegistration.ErrorUserExists");
                return(false);
            }

            // Check all sites where user will be assigned
            string checkSites = (String.IsNullOrEmpty(ShoppingCartControl.AssignToSites)) ? SiteContext.CurrentSiteName : ShoppingCartControl.AssignToSites;
            if (!UserInfoProvider.IsEmailUnique(txtEmail2.Text.Trim(), checkSites, 0))
            {
                lblError.Visible = true;
                lblError.Text    = GetString("UserInfo.EmailAlreadyExist");
                return(false);
            }

            // Create new customer and user account and sign in
            // User



            ui = new UserInfo();


            ui.UserName  = txtEmailRegistration.Text.Trim();
            ui.Email     = txtEmailRegistration.Text.Trim();
            ui.FirstName = txtFirstName.Text.Trim();
            ui.FullName  = UserInfoProvider.GetFullName(txtFirstName.Text.Trim(), String.Empty, txtLastName.Text.Trim());
            ui.LastName  = txtLastName.Text.Trim();
            ui.Enabled   = true;
            ui.UserIsGlobalAdministrator = false;
            ui.UserURLReferrer           = MembershipContext.AuthenticatedUser.URLReferrer;
            ui.UserCampaign = AnalyticsHelper.Campaign;
            ui.UserSettings.UserRegistrationInfo.IPAddress = RequestContext.UserHostAddress;
            ui.UserSettings.UserRegistrationInfo.Agent     = HttpContext.Current.Request.UserAgent;

            try
            {
                UserInfoProvider.SetPassword(ui, txtMotDePasseRegistration.Text);

                string[] siteList;

                // If AssignToSites field set
                if (!String.IsNullOrEmpty(ShoppingCartControl.AssignToSites))
                {
                    siteList = ShoppingCartControl.AssignToSites.Split(';');
                }
                else // If not set user current site
                {
                    siteList = new string[] { siteName };
                }

                foreach (string site in siteList)
                {
                    UserInfoProvider.AddUserToSite(ui.UserName, site);

                    // Add user to roles
                    if (ShoppingCartControl.AssignToRoles != "")
                    {
                        AssignUserToRoles(ui.UserName, ShoppingCartControl.AssignToRoles, site);
                    }
                }

                // Log registered user
                AnalyticsHelper.LogRegisteredUser(siteName, ui);

                Activity activity = new ActivityRegistration(ui, DocumentContext.CurrentDocument, AnalyticsContext.ActivityEnvironmentVariables);
                if (activity.Data != null)
                {
                    activity.Data.ContactID = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui);
                    activity.Log();
                }
            }
            catch (Exception ex)
            {
                lblError.Visible = true;
                lblError.Text    = ex.Message;
                return(false);
            }

            // Customer
            CustomerInfo ci = new CustomerInfo();
            ci.CustomerFirstName = txtFirstName.Text.Trim();
            ci.CustomerLastName  = txtLastName.Text.Trim();
            ci.CustomerEmail     = txtEmailRegistration.Text.Trim();

            ci.CustomerCompany           = "";
            ci.CustomerOrganizationID    = "";
            ci.CustomerTaxRegistrationID = "";
            if (chkCorporateBody.Checked)
            {
                ci.CustomerCompany = txtCompany1.Text.Trim();
                if (mShowOrganizationIDField)
                {
                    ci.CustomerOrganizationID = txtOrganizationID.Text.Trim();
                }
                if (mShowTaxRegistrationIDField)
                {
                    ci.CustomerTaxRegistrationID = txtTaxRegistrationID.Text.Trim();
                }
            }

            ci.CustomerUserID  = ui.UserID;
            ci.CustomerSiteID  = 0;
            ci.CustomerEnabled = true;
            ci.CustomerCreated = DateTime.Now;
            CustomerInfoProvider.SetCustomerInfo(ci);

            // Track successful registration conversion
            string name = ShoppingCartControl.RegistrationTrackConversionName;
            ECommerceHelper.TrackRegistrationConversion(ShoppingCart.SiteName, name);

            // Log "customer registration" activity and update profile
            var activityCustomerRegistration = new ActivityCustomerRegistration(ci, MembershipContext.AuthenticatedUser, AnalyticsContext.ActivityEnvironmentVariables);
            if (activityCustomerRegistration.Data != null)
            {
                if (ContactID <= 0)
                {
                    activityCustomerRegistration.Data.ContactID = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui);
                }
                activityCustomerRegistration.Log();
            }

            // Sign in
            if (ui.UserEnabled)
            {
                CMSContext.AuthenticateUser(ui.UserName, false);
                ShoppingCart.User = ui;

                ContactID = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui);
                Activity activity = new ActivityUserLogin(ContactID, ui, DocumentContext.CurrentDocument, AnalyticsContext.ActivityEnvironmentVariables);
                activity.Log();
            }

            ShoppingCart.ShoppingCartCustomerID = ci.CustomerID;

            // Send new registration notification email
            if (ShoppingCartControl.SendNewRegistrationNotificationToAddress != "")
            {
                SendRegistrationNotification(ui);
            }
            /**aadrresse*/
            // Process billing address
            //------------------------
            int         CountryID  = ValidationHelper.GetInteger(ddlShippingCountry.SelectedValue, 0);
            AddressInfo ai         = null;
            bool        newAddress = true;
            ai = new AddressInfo();
            string mCustomerName = ci.CustomerFirstName + " " + ci.CustomerLastName;
            // newAddress.AddressName = mCustomerName + " , " + txtAdresse.Text + " - " + txtCodePostale.Text + " " + txtVille.Text;


            ai.AddressPersonalName = mCustomerName + " , " + txtAdresse.Text + " - " + txtCodePostale.Text + " " + txtVille.Text;
            ai.AddressLine1        = txtAdresse.Text.Trim();
            ai.AddressLine2        = txtAdresse.Text.Trim();
            ai.AddressCity         = txtVille.Text.Trim();
            ai.AddressZip          = txtCodePostale.Text.Trim();
            ai.AddressCountryID    = CountryID;


            if (newAddress)
            {
                ai.AddressIsBilling  = true;
                ai.AddressIsShipping = !chkShippingAddr.Checked;
                ai.AddressEnabled    = true;
            }
            ai.AddressCustomerID = ci.CustomerID;
            ai.AddressName       = AddressInfoProvider.GetAddressName(ai);

            // Save address and set it's ID to ShoppingCartInfoObj
            AddressInfoProvider.SetAddressInfo(ai);

            // Update current contact's address
            ModuleCommands.OnlineMarketingMapAddress(ai, ContactID);

            ShoppingCart.ShoppingCartBillingAddressID = ai.AddressID;

            // If shopping cart does not need shipping
            if (!ShippingOptionInfoProvider.IsShippingNeeded(ShoppingCart))
            {
                ShoppingCart.ShoppingCartShippingAddressID = 0;
            }
            // If shipping address is different from billing address
            else if (chkShippingAddr.Checked)
            {
                //// Check country presence
                //if (CountrySelector2.CountryID <= 0)
                //{
                //    lblError.Visible = true;
                //    lblError.Text = GetString("countryselector.selectedcountryerr");
                //    return false;
                //}

                //if (!CountrySelector2.StateSelectionIsValid)
                //{
                //    lblError.Visible = true;
                //    lblError.Text = GetString("countryselector.selectedstateerr");
                //    return false;
                //}

                //newAddress = false;
                //// Process shipping address
                ////-------------------------
                //ai = AddressInfoProvider.GetAddressInfo(Convert.ToInt32(drpShippingAddr.SelectedValue));
                //if (ai == null)
                //{
                //    ai = new AddressInfo();
                //    newAddress = true;
                //}

                ai.AddressPersonalName = txtadresseshipping.Text.Trim();
                ai.AddressLine1        = txtadresseshipping.Text.Trim();
                ai.AddressLine2        = txtadresseshipping.Text.Trim();
                ai.AddressCity         = txtvilleshipping.Text.Trim();
                ai.AddressZip          = txtcpshipping.Text.Trim();
                ai.AddressCountryID    = CountryID;

                if (newAddress)
                {
                    ai.AddressIsShipping = true;
                    ai.AddressEnabled    = true;
                    ai.AddressIsBilling  = false;
                    ai.AddressIsCompany  = false;
                    ai.AddressEnabled    = true;
                }
                ai.AddressCustomerID = ci.CustomerID;
                ai.AddressName       = AddressInfoProvider.GetAddressName(ai);

                // Save address and set it's ID to ShoppingCartInfoObj
                AddressInfoProvider.SetAddressInfo(ai);
                ShoppingCart.ShoppingCartShippingAddressID = ai.AddressID;
            }
            // Shipping address is the same as billing address
            else
            {
                ShoppingCart.ShoppingCartShippingAddressID = ShoppingCart.ShoppingCartBillingAddressID;
            }
            /**finadrress*/
            this.ShoppingCartControl.ButtonNextClickAction();
        }

        try
        {
            if (!this.ShoppingCartControl.IsInternalOrder)
            {
                ShoppingCartInfoProvider.SetShoppingCartInfo(this.ShoppingCart);
            }
            return(true);
        }
        catch
        {
            return(false);
        }
    }
Exemplo n.º 28
0
    /// <summary>
    /// Reloads all data.
    /// </summary>
    public override void ReloadData(bool forceLoad)
    {
        if (CurrentReport != null)
        {
            // Load labels
            if (!RequestHelper.IsPostBack() || forceLoad)
            {
                // Create query parameters
                string query = "?ObjectID=" + CurrentReport.ReportObjectID;

                // Set link value
                string url = CurrentReport.ReportURL;
                if (CurrentReport.ReportCulture != String.Empty)
                {
                    url = URLHelper.AddParameterToUrl(url, URLHelper.LanguageParameterName, CurrentReport.ReportCulture);
                }
                lnkUrlValue.Text        = HTMLHelper.HTMLEncode(url);
                lnkUrlValue.NavigateUrl = url;
                lnkUrlValue.ToolTip     = HTMLHelper.HTMLEncode(url);
                lnkUrlValue.Target      = "_blank";

                // Set culture value
                var cultureInfo = CultureHelper.GetCultureInfo(CurrentReport.ReportCulture);
                lblCultureValue.Text = (cultureInfo != null) ? cultureInfo.DisplayName : ResHelper.Dash;

                // Set site value
                SiteInfo si = SiteInfoProvider.GetSiteInfo(CurrentReport.ReportSiteID);
                lblSiteValue.Text = (si != null) ? HTMLHelper.HTMLEncode(si.DisplayName) : ResHelper.Dash;

                // Set title
                lblTitleValue.Text = HTMLHelper.HTMLEncode(CurrentReport.ReportTitle);

                // Set labels
                if (!string.IsNullOrEmpty(CurrentReport.ReportObjectType))
                {
                    lblObjectTypeValue.Text = GetString("ObjectType." + ImportExportHelper.GetSafeObjectTypeName(CurrentReport.ReportObjectType));
                    query += "&ObjectType=" + CurrentReport.ReportObjectType;
                }
                else
                {
                    lblObjectTypeValue.Text = ResHelper.Dash;
                }

                // Get object display name
                lblObjectNameValue.Text = ResHelper.Dash;

                string objectType = CurrentReport.ReportObjectType;
                int    objectId   = CurrentReport.ReportObjectID;

                if ((objectId > 0) && !string.IsNullOrEmpty(objectType) && !DocumentHelper.IsDocumentObjectType(objectType))
                {
                    GeneralizedInfo obj = ProviderHelper.GetInfoById(objectType, objectId);
                    if ((obj != null) && !string.IsNullOrEmpty(obj.ObjectDisplayName))
                    {
                        lblObjectNameValue.Text = HTMLHelper.HTMLEncode(obj.ObjectDisplayName);
                    }
                }

                // Set Reported by label
                lblReportedByValue.Text = ResHelper.Dash;
                if (CurrentReport.ReportUserID != 0)
                {
                    UserInfo ui = UserInfoProvider.GetUserInfo(CurrentReport.ReportUserID);
                    lblReportedByValue.Text = (ui != null) ? HTMLHelper.HTMLEncode(ui.FullName) : GetString("general.NA");
                }

                // Set other parameters
                lblReportedWhenValue.Text = CurrentReport.ReportWhen.ToString();

                CMSPage page = Page as CMSPage;

                if ((CurrentReport.ReportObjectID > 0) && (!string.IsNullOrEmpty(CurrentReport.ReportObjectType)) && AbuseReportInfoProvider.IsObjectTypeSupported(CurrentReport.ReportObjectType))
                {
                    // Add Object details button
                    string detailUrl = "~/CMSModules/AbuseReport/AbuseReport_ObjectDetails.aspx" + query;
                    detailUrl = URLHelper.AddParameterToUrl(detailUrl, "hash", QueryHelper.GetHash(detailUrl));
                    var onClientClickScript = ScriptHelper.GetModalDialogScript(UrlResolver.ResolveUrl(detailUrl), "objectdetails", 960, 600);

                    if (page != null)
                    {
                        var headerActions = page.HeaderActions;
                        headerActions.AddAction(new HeaderAction
                        {
                            Text          = GetString("abuse.details"),
                            OnClientClick = onClientClickScript,
                            ButtonStyle   = ButtonStyle.Default
                        });
                        btnObjectDetails.Visible = false;
                    }
                    else
                    {
                        btnObjectDetails.OnClientClick = onClientClickScript;
                        ScriptHelper.RegisterDialogScript(Page);
                    }
                }
                else
                {
                    btnObjectDetails.Visible = false;
                }

                Control postback = ControlsHelper.GetPostBackControl(Page);

                // Not post-back not caused by OK button or Save action in header
                if ((postback != btnOk) && ((page == null) || (postback != page.HeaderActions)))
                {
                    txtCommentValue.Text = CurrentReport.ReportComment;
                    LoadStatus((int)CurrentReport.ReportStatus);
                }
            }
        }
    }
    /// <summary>
    /// Get user information and logs user (register if no user found)
    /// </summary>
    private void ProcessLiveIDLogin()
    {
        // Get authorization code from URL
        String code = QueryHelper.GetString("code", String.Empty);

        // Additional info page for login
        string additionalInfoPage = SettingsKeyInfoProvider.GetValue(siteName + ".CMSLiveIDRequiredUserDataPage");

        // Create windows login object
        WindowsLiveLogin wwl = new WindowsLiveLogin(siteName);

        // Windows live User
        WindowsLiveLogin.User liveUser = null;
        if (!WindowsLiveLogin.UseServerSideAuthorization)
        {
            if (!RequestHelper.IsPostBack())
            {
                // If client authentication, get token displayed in url after # from window.location
                String script = ControlsHelper.GetPostBackEventReference(this, "#").Replace("'#'", "window.location");
                ScriptHelper.RegisterClientScriptBlock(this, typeof(string), "PostbackScript", ScriptHelper.GetScript(script));
            }
            else
            {
                // Try to get full url from event argument
                string fullurl = Request[postEventArgumentID];

                // Authentication token - use to get uid
                String token = ParseToken(fullurl, @"authentication_token=([\w\d.-]+)&");

                // User token - this token is used in server auth. scenario. It's stored in user object (for possible further use) so parse it too and store it
                String accessToken = ParseToken(fullurl, @"access_token=([%\w\d.-/]+)&");

                if (token != String.Empty)
                {
                    // Return context from session
                    GetLoginInformation();

                    // Authenticate user by found token
                    liveUser = wwl.AuthenticateClientToken(token, relativeURL, accessToken);
                    if (liveUser != null)
                    {
                        // Set info to refresh to parent page
                        ScriptHelper.RegisterWOpenerScript(Page);
                        CreateCloseScript("");
                    }
                }
            }
        }
        else
        {
            GetLoginInformation();

            // Process login via Live ID
            liveUser = wwl.ProcessLogin(code, relativeURL);
        }

        // Authorization successful
        if (liveUser != null)
        {
            // Find user by ID
            UserInfo winUser = UserInfoProvider.GetUserInfoByWindowsLiveID(liveUser.Id);

            string error = String.Empty;

            // Register new user
            if (winUser == null)
            {
                // Check whether additional user info page is set
                // No page set, user can be created/sign
                if (additionalInfoPage == String.Empty)
                {
                    // Create new user
                    UserInfo ui = AuthenticationHelper.AuthenticateWindowsLiveUser(liveUser.Id, siteName, true, ref error);

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

                    // If user was found or successfully created
                    if ((ui != null) && (ui.Enabled))
                    {
                        double resolvedConversionValue = ValidationHelper.GetDouble(MacroResolver.Resolve(conversionValue), 0);

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

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

                        SetAuthCookieAndRedirect(ui);
                    }
                    // User not created
                    else
                    {
                        if (WindowsLiveLogin.UseServerSideAuthorization)
                        {
                            WindowsLiveLogin.ClearCookieAndRedirect(loginPage);
                        }
                        else
                        {
                            CreateCloseScript("clearcookieandredirect");
                        }
                    }
                }
                // Required data page exists
                else
                {
                    // Store user object in session for additional info page
                    SessionHelper.SetValue("windowsliveloginuser", liveUser);

                    if (WindowsLiveLogin.UseServerSideAuthorization)
                    {
                        // Redirect to additional info page
                        URLHelper.Redirect(UrlResolver.ResolveUrl(additionalInfoPage));
                    }
                    else
                    {
                        CreateCloseScript("redirectToAdditionalPage");
                    }
                }
            }
            else
            {
                UserInfo ui = AuthenticationHelper.AuthenticateWindowsLiveUser(liveUser.Id, siteName, true, ref error);

                // If user was found
                if ((ui != null) && (ui.Enabled))
                {
                    SetAuthCookieAndRedirect(ui);
                }
            }
        }
    }
Exemplo n.º 30
0
    protected void UIFormOnOnBeforeValidate(object sender, EventArgs e)
    {
        int selectedCMSUserId = ValidationHelper.GetInteger(fUserSelector.Value, 0);

        UserInfo user = UserInfoProvider.GetUserInfo(selectedCMSUserId);

        // Validate form - both fields must be filled
        if ((user == null) || (fNickname.EditingControl.Text == ""))
        {
            ShowErrorAndStopProcessing("chat.user.erroridnickname");
            return;
        }

        if (user.IsPublic())
        {
            ShowErrorAndStopProcessing("chat.cantassociatechatusertopublic");
            return;
        }


        // Editing
        if (TypedEditedObject != null)
        {
            if (!TypedEditedObject.ChatUserUserID.HasValue)
            {
                ShowErrorAndStopProcessing("chat.user.cannoteditanonymoususer");
                return;
            }
        }
        else
        {
            // New object

            // Check if userID is unique in ChatUser table if adding a new user
            if (ChatUserInfoProvider.GetChatUserByUserID(selectedCMSUserId) != null)
            {
                ShowErrorAndStopProcessing("chat.user.erroridunique");
                return;
            }
        }

        string newNickname = fNickname.EditingControl.Text;

        // Check nickname only if text has been changed
        if ((TypedEditedObject == null) || (newNickname != TypedEditedObject.ChatUserNickname))
        {
            try
            {
                ChatUserHelper.VerifyNicknameIsValid(ref newNickname);
            }
            catch (ChatServiceException ex)
            {
                ShowErrorAndStopProcessing(ex.StatusMessage);
                return;
            }


            // Check if Nickname is unique in registered users
            if (!ChatUserHelper.IsNicknameAvailable(newNickname))
            {
                ShowErrorAndStopProcessing("chat.user.errornickunique");
                return;
            }
        }

        fNickname.EditingControl.Text = newNickname;
    }