コード例 #1
0
 public HomeController(ObjectFactory objectFactory)
 {
     this.photoManager = new UserPhotoManager(objectFactory);
 }
コード例 #2
0
 public static bool HasAvatar(this UserInfo userInfo)
 {
     return(UserPhotoManager.UserHasAvatar(userInfo.ID));
 }
コード例 #3
0
 public static string GetPhotoURL(this UserInfo userInfo)
 {
     return(UserPhotoManager.GetPhotoAbsoluteWebPath(userInfo.ID));
 }
コード例 #4
0
 public string GetHTMLImgUserAvatar(Guid userID)
 {
     return("<img alt=\"\" class='userPhoto' src=\"" + UserPhotoManager.GetBigPhotoURL(userID) + "\"/>");
 }
コード例 #5
0
        protected override IEnumerable <KeyValuePair <string, object> > GetClientVariables(HttpContext context)
        {
            var curQuota = TenantExtra.GetTenantQuota();
            var tenant   = CoreContext.TenantManager.GetCurrentTenant();
            var helpLink = CommonLinkUtility.GetHelpLink();

            var result = new List <KeyValuePair <string, object> >(4)
            {
                RegisterObject(
                    new {
                    ApiPath         = SetupInfo.WebApiBaseUrl,
                    IsAuthenticated = SecurityContext.IsAuthenticated,
                    IsAdmin         = CoreContext.UserManager.IsUserInGroup(SecurityContext.CurrentAccount.ID, Constants.GroupAdmin.ID),
                    IsVisitor       = CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID).IsVisitor(),
                    //CurrentTenantId = tenant.TenantId,
                    CurrentTenantCreatedDate = tenant.CreatedDateTime,
                    CurrentTenantVersion     = tenant.Version,
                    CurrentTenantTimeZone    = new
                    {
                        Id            = tenant.TimeZone.Id,
                        DisplayName   = Common.Utils.TimeZoneConverter.GetTimeZoneName(tenant.TimeZone),
                        BaseUtcOffset = tenant.TimeZone.GetOffset(true).TotalMinutes,
                        UtcOffset     = tenant.TimeZone.GetOffset().TotalMinutes
                    },
                    TenantIsPremium = curQuota.Trial ? "No" : "Yes",
                    TenantTariff    = curQuota.Id,
                    EmailRegExpr    = @"^(([^<>()[\]\\.,;:\s@\""]+(\.[^<>()[\]\\.,;:\s@\""]+)*)|(\"".+\""))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$",
                    UserNameRegExpr = UserFormatter.UserNameRegex,
                    GroupSelector_MobileVersionGroup = new { Id = -1, Name = UserControlsCommonResource.LblSelect.HtmlEncode().ReplaceSingleQuote() },
                    GroupSelector_WithGroupEveryone  = new { Id = Constants.GroupEveryone.ID, Name = UserControlsCommonResource.Everyone.HtmlEncode().ReplaceSingleQuote() },
                    GroupSelector_WithGroupAdmin     = new { Id = Constants.GroupAdmin.ID, Name = UserControlsCommonResource.Admin.HtmlEncode().ReplaceSingleQuote() },
                    SetupInfoNotifyAddress           = SetupInfo.NotifyAddress,
                    SetupInfoTipsAddress             = SetupInfo.TipsAddress,
                    CKEDITOR_BASEPATH      = WebPath.GetPath("/UserControls/Common/ckeditor/"),
                    MaxImageFCKWidth       = ConfigurationManagerExtension.AppSettings["MaxImageFCKWidth"] ?? "620",
                    UserPhotoHandlerUrl    = VirtualPathUtility.ToAbsolute("~/UserPhoto.ashx"),
                    UserDefaultBigPhotoURL = UserPhotoManager.GetDefaultBigPhotoURL(),
                    ImageWebPath           = WebImageSupplier.GetImageFolderAbsoluteWebPath(),
                    UrlShareTwitter        = SetupInfo.ShareTwitterUrl,
                    UrlShareFacebook       = SetupInfo.ShareFacebookUrl,
                    LogoDarkUrl            = CommonLinkUtility.GetFullAbsolutePath(TenantLogoManager.GetLogoDark(true)),
                    HelpLink = helpLink ?? "",
                    MailMaximumMessageBodySize = ConfigurationManagerExtension.AppSettings["mail.maximum-message-body-size"] ?? "524288",
                    PasswordHasher.PasswordHashSize,
                    PasswordHasher.PasswordHashIterations,
                    PasswordHasher.PasswordHashSalt,
                })
            };

            if (CoreContext.Configuration.Personal)
            {
                result.Add(RegisterObject(new { CoreContext.Configuration.Personal }));
            }

            if (CoreContext.Configuration.CustomMode)
            {
                result.Add(RegisterObject(new { CoreContext.Configuration.CustomMode }));
            }

            if (CoreContext.Configuration.Standalone)
            {
                result.Add(RegisterObject(new { CoreContext.Configuration.Standalone }));
            }

            if (!string.IsNullOrEmpty(helpLink))
            {
                result.Add(RegisterObject(new { FilterHelpCenterLink = helpLink.TrimEnd('/') + "/tipstricks/using-search.aspx" }));
            }

            return(result);
        }
コード例 #6
0
        protected override IEnumerable <KeyValuePair <string, object> > GetClientVariables(HttpContext context)
        {
            var currentProject = "0";

            if (context.Request.GetUrlRewriter() != null)
            {
                currentProject = HttpUtility.ParseQueryString(context.Request.GetUrlRewriter().Query)["prjID"];

                if (string.IsNullOrEmpty(currentProject) && context.Request.UrlReferrer != null)
                {
                    currentProject = HttpUtility.ParseQueryString(context.Request.UrlReferrer.Query)["prjID"];
                }
            }

            var filter = new TaskFilter
            {
                SortBy            = "deadline",
                SortOrder         = false,
                MilestoneStatuses = new List <MilestoneStatus> {
                    MilestoneStatus.Open
                },
                ProjectIds = new List <int> {
                    Convert.ToInt32(currentProject)
                }
            };

            var milestones = Global.EngineFactory.MilestoneEngine.GetByFilter(filter)
                             .Select(m => new
            {
                id           = m.ID,
                title        = m.Title,
                deadline     = ClientUserResources.SetDate(m.DeadLine, TimeZoneInfo.Local),
                projectOwner = new { id = m.Project.ID }
            });

            var team = Global.EngineFactory.ProjectEngine.GetTeam(Convert.ToInt32(currentProject))
                       .Select(r => new
            {
                id          = r.UserInfo.ID,
                displayName = DisplayUserSettings.GetFullUserName(r.UserInfo.ID),
                userName    = r.UserInfo.UserName,
                avatarSmall = UserPhotoManager.GetSmallPhotoURL(r.UserInfo.ID),
                status      = r.UserInfo.Status,
                groups      = CoreContext.UserManager.GetUserGroups(r.UserInfo.ID).Select(x => new
                {
                    id      = x.ID,
                    name    = x.Name,
                    manager = CoreContext.UserManager.GetUsers(CoreContext.UserManager.GetDepartmentManager(x.ID)).UserName
                }).ToList(),
                isVisitor         = r.UserInfo.IsVisitor(),
                isAdmin           = r.UserInfo.IsAdmin(),
                isOwner           = r.UserInfo.IsOwner(),
                isManager         = r.IsManager,
                canReadFiles      = r.CanReadFiles,
                canReadMilestones = r.CanReadMilestones,
                canReadMessages   = r.CanReadMessages,
                canReadTasks      = r.CanReadTasks,
                canReadContacts   = r.CanReadContacts,
                isAdministrator   = r.UserInfo.IsAdmin(),
                title             = r.UserInfo.Title,
                profileUrl        = r.UserInfo.GetUserProfilePageURL()
            }).OrderBy(r => r.displayName).ToList();

            return(new List <KeyValuePair <string, object> >(2)
            {
                RegisterObject("Milestones", new { response = milestones }),
                RegisterObject("Team", new { response = team })
            });
        }
コード例 #7
0
        protected void Page_Load(object sender, EventArgs e)
        {
            Page.RegisterBodyScripts("~/js/third-party/xregexp.js", "~/UserControls/Management/ConfirmInviteActivation/js/confirm_invite_activation.js")
            .RegisterStyle("~/UserControls/Management/ConfirmInviteActivation/css/confirm_invite_activation.less");

            var uid = Guid.Empty;

            try
            {
                uid = new Guid(Request["uid"]);
            }
            catch
            {
            }

            var email = GetEmailAddress();

            if (_type != ConfirmType.Activation && AccountLinkControl.IsNotEmpty && !CoreContext.Configuration.Personal)
            {
                var thrd = (AccountLinkControl)LoadControl(AccountLinkControl.Location);
                thrd.InviteView     = true;
                thrd.ClientCallback = "loginJoinCallback";
                thrdParty.Visible   = true;
                thrdParty.Controls.Add(thrd);
            }

            Page.Title = HeaderStringHelper.GetPageTitle(Resource.Authorization);

            UserInfo user;

            try
            {
                SecurityContext.AuthenticateMe(ASC.Core.Configuration.Constants.CoreSystem);

                user = CoreContext.UserManager.GetUserByEmail(email);
                var usr = CoreContext.UserManager.GetUsers(uid);
                if (usr.ID.Equals(Constants.LostUser.ID) || usr.ID.Equals(ASC.Core.Configuration.Constants.Guest.ID))
                {
                    usr = CoreContext.UserManager.GetUsers(CoreContext.TenantManager.GetCurrentTenant().OwnerId);
                }

                var photoData = UserPhotoManager.GetUserPhotoData(usr.ID, UserPhotoManager.MediumFotoSize);

                _userAvatar = photoData == null?usr.GetMediumPhotoURL() : "data:image/png;base64," + Convert.ToBase64String(photoData);

                _userName = usr.DisplayUserName(true);
                _userPost = (usr.Title ?? "").HtmlEncode();
            }
            finally
            {
                SecurityContext.Logout();
            }

            if (_type == ConfirmType.LinkInvite || _type == ConfirmType.EmpInvite)
            {
                if (TenantStatisticsProvider.GetUsersCount() >= TenantExtra.GetTenantQuota().ActiveUsers&& _employeeType == EmployeeType.User)
                {
                    ShowError(UserControlsCommonResource.TariffUserLimitReason);
                    return;
                }

                if (!user.ID.Equals(Constants.LostUser.ID))
                {
                    ShowError(CustomNamingPeople.Substitute <Resource>("ErrorEmailAlreadyExists"));
                    return;
                }
            }

            else if (_type == ConfirmType.Activation)
            {
                if (user.IsActive)
                {
                    Response.Redirect(CommonLinkUtility.GetDefault());
                    return;
                }

                if (user.ID.Equals(Constants.LostUser.ID) || user.Status == EmployeeStatus.Terminated)
                {
                    ShowError(string.Format(Resource.ErrorUserNotFoundByEmail, email));
                    return;
                }
            }

            var tenant = CoreContext.TenantManager.GetCurrentTenant();

            if (tenant != null)
            {
                var settings = IPRestrictionsSettings.Load();
                if (settings.Enable && !IPSecurity.IPSecurity.Verify(tenant))
                {
                    ShowError(Resource.ErrorAccessRestricted);
                    return;
                }
            }

            if (!IsPostBack)
            {
                return;
            }

            var firstName = GetFirstName();
            var lastName  = GetLastName();

            var          passwordHash       = (Request["passwordHash"] ?? "").Trim();
            var          analytics          = (Request["analytics"] ?? "").Trim() == "True";
            var          mustChangePassword = false;
            LoginProfile thirdPartyProfile;

            //thirdPartyLogin confirmInvite
            if (Request["__EVENTTARGET"] == "thirdPartyLogin")
            {
                var valueRequest = Request["__EVENTARGUMENT"];
                thirdPartyProfile = new LoginProfile(valueRequest);

                if (!string.IsNullOrEmpty(thirdPartyProfile.AuthorizationError))
                {
                    // ignore cancellation
                    if (thirdPartyProfile.AuthorizationError != "Canceled at provider")
                    {
                        ShowError(HttpUtility.HtmlEncode(thirdPartyProfile.AuthorizationError));
                    }
                    return;
                }

                if (string.IsNullOrEmpty(thirdPartyProfile.EMail))
                {
                    ShowError(HttpUtility.HtmlEncode(Resource.ErrorNotCorrectEmail));
                    return;
                }
            }

            if (Request["__EVENTTARGET"] == "confirmInvite")
            {
                if (String.IsNullOrEmpty(email))
                {
                    _errorMessage = Resource.ErrorEmptyUserEmail;
                    return;
                }

                if (!email.TestEmailRegex())
                {
                    _errorMessage = Resource.ErrorNotCorrectEmail;
                    return;
                }

                if (String.IsNullOrEmpty(firstName))
                {
                    _errorMessage = Resource.ErrorEmptyUserFirstName;
                    return;
                }

                if (String.IsNullOrEmpty(lastName))
                {
                    _errorMessage = Resource.ErrorEmptyUserLastName;
                    return;
                }

                if (String.IsNullOrEmpty(passwordHash))
                {
                    _errorMessage = Resource.ErrorPasswordEmpty;
                    return;
                }
            }
            var userID = Guid.Empty;

            try
            {
                SecurityContext.AuthenticateMe(ASC.Core.Configuration.Constants.CoreSystem);
                if (_type == ConfirmType.EmpInvite || _type == ConfirmType.LinkInvite)
                {
                    if (TenantStatisticsProvider.GetUsersCount() >= TenantExtra.GetTenantQuota().ActiveUsers&& _employeeType == EmployeeType.User)
                    {
                        ShowError(UserControlsCommonResource.TariffUserLimitReason);
                        return;
                    }

                    UserInfo newUser;
                    if (Request["__EVENTTARGET"] == "confirmInvite")
                    {
                        var fromInviteLink = _type == ConfirmType.LinkInvite;
                        newUser = CreateNewUser(firstName, lastName, email, passwordHash, _employeeType, fromInviteLink);

                        var messageAction = _employeeType == EmployeeType.User ? MessageAction.UserCreatedViaInvite : MessageAction.GuestCreatedViaInvite;
                        MessageService.Send(HttpContext.Current.Request, MessageInitiator.System, messageAction, MessageTarget.Create(newUser.ID), newUser.DisplayUserName(false));

                        userID = newUser.ID;

                        var settings = TenantAnalyticsSettings.LoadForCurrentUser();
                        settings.Analytics = analytics;

                        settings.SaveForCurrentUser();
                    }

                    if (Request["__EVENTTARGET"] == "thirdPartyLogin")
                    {
                        if (String.IsNullOrEmpty(passwordHash))
                        {
                            passwordHash       = UserManagerWrapper.GeneratePassword();
                            mustChangePassword = true;
                        }

                        var valueRequest = Request["__EVENTARGUMENT"];
                        thirdPartyProfile = new LoginProfile(valueRequest);
                        newUser           = CreateNewUser(GetFirstName(thirdPartyProfile), GetLastName(thirdPartyProfile), GetEmailAddress(thirdPartyProfile), passwordHash, _employeeType, false);

                        var messageAction = _employeeType == EmployeeType.User ? MessageAction.UserCreatedViaInvite : MessageAction.GuestCreatedViaInvite;
                        MessageService.Send(HttpContext.Current.Request, MessageInitiator.System, messageAction, MessageTarget.Create(newUser.ID), newUser.DisplayUserName(false));

                        userID = newUser.ID;
                        if (!String.IsNullOrEmpty(thirdPartyProfile.Avatar))
                        {
                            SaveContactImage(userID, thirdPartyProfile.Avatar);
                        }

                        var linker = new AccountLinker("webstudio");
                        linker.AddLink(userID.ToString(), thirdPartyProfile);
                    }
                }
                else if (_type == ConfirmType.Activation)
                {
                    if (!UserFormatter.IsValidUserName(firstName, lastName))
                    {
                        throw new Exception(Resource.ErrorIncorrectUserName);
                    }

                    SecurityContext.SetUserPasswordHash(user.ID, passwordHash);

                    user.ActivationStatus = EmployeeActivationStatus.Activated;
                    user.FirstName        = firstName;
                    user.LastName         = lastName;
                    CoreContext.UserManager.SaveUserInfo(user);

                    userID = user.ID;

                    //notify
                    if (user.IsVisitor())
                    {
                        StudioNotifyService.Instance.GuestInfoAddedAfterInvite(user);
                        MessageService.Send(HttpContext.Current.Request, MessageInitiator.System, MessageAction.GuestActivated, MessageTarget.Create(user.ID), user.DisplayUserName(false));
                    }
                    else
                    {
                        StudioNotifyService.Instance.UserInfoAddedAfterInvite(user);
                        MessageService.Send(HttpContext.Current.Request, MessageInitiator.System, MessageAction.UserActivated, MessageTarget.Create(user.ID), user.DisplayUserName(false));
                    }
                }
            }
            catch (SecurityContext.PasswordException)
            {
                _errorMessage = HttpUtility.HtmlEncode(Resource.ErrorPasswordRechange);
                return;
            }
            catch (Exception exception)
            {
                _errorMessage = HttpUtility.HtmlEncode(exception.Message);
                return;
            }
            finally
            {
                SecurityContext.Logout();
            }

            user = CoreContext.UserManager.GetUsers(userID);
            try
            {
                var cookiesKey = SecurityContext.AuthenticateMe(user.Email, passwordHash);
                CookiesManager.SetCookies(CookiesType.AuthKey, cookiesKey);
                MessageService.Send(HttpContext.Current.Request, MessageAction.LoginSuccess);
                StudioNotifyService.Instance.UserHasJoin();

                if (mustChangePassword)
                {
                    StudioNotifyService.Instance.UserPasswordChange(user);
                }
            }
            catch (Exception exception)
            {
                (Page as Confirm).ErrorMessage = HttpUtility.HtmlEncode(exception.Message);
                return;
            }

            UserHelpTourHelper.IsNewUser = true;
            if (CoreContext.Configuration.Personal)
            {
                PersonalSettings.IsNewUser = true;
            }
            Response.Redirect(CommonLinkUtility.GetDefault());
        }
コード例 #8
0
        public EmployeeWraperFull(UserInfo userInfo, ApiContext context)
            : base(userInfo, context)
        {
            UserName  = userInfo.UserName;
            IsVisitor = userInfo.IsVisitor();
            FirstName = userInfo.FirstName;
            LastName  = userInfo.LastName;
            Birthday  = (ApiDateTime)userInfo.BirthDate;

            if (userInfo.Sex.HasValue)
            {
                Sex = userInfo.Sex.Value ? "male" : "female";
            }

            Status           = userInfo.Status;
            ActivationStatus = userInfo.ActivationStatus & ~EmployeeActivationStatus.AutoGenerated;
            Terminated       = (ApiDateTime)userInfo.TerminatedDate;

            WorkFrom = (ApiDateTime)userInfo.WorkFromDate;
            Email    = userInfo.Email;

            if (!string.IsNullOrEmpty(userInfo.Location))
            {
                Location = userInfo.Location;
            }

            if (!string.IsNullOrEmpty(userInfo.Notes))
            {
                Notes = userInfo.Notes;
            }

            if (!string.IsNullOrEmpty(userInfo.MobilePhone))
            {
                MobilePhone = userInfo.MobilePhone;
            }

            MobilePhoneActivationStatus = userInfo.MobilePhoneActivationStatus;

            if (!string.IsNullOrEmpty(userInfo.CultureName))
            {
                CultureName = userInfo.CultureName;
            }

            FillConacts(userInfo);

            if (CheckContext(context, "groups") || CheckContext(context, "department"))
            {
                var groups = CoreContext.UserManager.GetUserGroups(userInfo.ID).Select(x => new GroupWrapperSummary(x)).ToList();

                if (groups.Any())
                {
                    Groups     = groups;
                    Department = string.Join(", ", Groups.Select(d => d.Name.HtmlEncode()));
                }
                else
                {
                    Department = "";
                }
            }

            if (CheckContext(context, "avatarMedium"))
            {
                AvatarMedium = UserPhotoManager.GetMediumPhotoURL(userInfo.ID) + "?_=" + userInfo.LastModified.GetHashCode();
            }

            if (CheckContext(context, "avatar"))
            {
                Avatar = UserPhotoManager.GetBigPhotoURL(userInfo.ID) + "?_=" + userInfo.LastModified.GetHashCode();
            }

            IsAdmin = userInfo.IsAdmin();

            if (CheckContext(context, "listAdminModules"))
            {
                var listAdminModules = userInfo.GetListAdminModules();

                if (listAdminModules.Any())
                {
                    ListAdminModules = listAdminModules;
                }
            }

            IsOwner = userInfo.IsOwner();

            IsLDAP = userInfo.IsLDAP();
            IsSSO  = userInfo.IsSSO();
        }
コード例 #9
0
 public string GetPhotoPath()
 {
     return(IsPageEditProfileFlag ? UserPhotoManager.GetPhotoAbsoluteWebPath(UserProfile.Id) : UserPhotoManager.GetDefaultPhotoAbsoluteWebPath());
 }
コード例 #10
0
 public static Size GetPhotoSize(this UserInfo userInfo, Guid moduleID)
 {
     return(UserPhotoManager.GetPhotoSize(moduleID, userInfo.ID));
 }
コード例 #11
0
 public static string GetPhotoURL(this UserInfo userInfo, Guid moduleID)
 {
     return(UserPhotoManager.GetPhotoAbsoluteWebPath(moduleID, userInfo.ID));
 }
コード例 #12
0
 public static string GetMediumPhotoURL(this UserInfo userInfo)
 {
     return UserPhotoManager.GetMediumPhotoURL(userInfo.ID);
 }
コード例 #13
0
        public AjaxResponse SaveUser(UserInfoEx userInfoEx, string photoPath)
        {
            var resp = new AjaxResponse();

            if (!SecurityContext.IsAuthenticated)
            {
                resp.rs1 = "0";
                return(resp);
            }

            var isNew = userInfoEx.Info.ID.Equals(Guid.Empty);


            userInfoEx.Info.Email = (userInfoEx.Info.Email ?? "").Trim();

            if (String.IsNullOrEmpty(userInfoEx.Info.FirstName.Trim()))
            {
                resp.rs1 = "0";
                resp.rs2 = "<div>" + Resources.Resource.ErrorEmptyUserFirstName + "</div>";
                return(resp);
            }
            else if (String.IsNullOrEmpty(userInfoEx.Info.LastName.Trim()))
            {
                resp.rs1 = "0";
                resp.rs2 = "<div>" + Resources.Resource.ErrorEmptyUserLastName + "</div>";
                return(resp);
            }
            else if (String.IsNullOrEmpty(userInfoEx.Info.Email.Trim()) || !userInfoEx.Info.Email.TestEmailRegex())
            {
                resp.rs1 = "0";
                resp.rs2 = "<div>" + Resources.Resource.ErrorNotCorrectEmail + "</div>";
                return(resp);
            }

            if (isNew)
            {
                userInfoEx.Pwd = UserManagerWrapper.GeneratePassword();
            }

            try
            {
                var self = SecurityContext.CurrentAccount.ID.Equals(userInfoEx.Info.ID);

                var newDepartment = CoreContext.GroupManager.GetGroupInfo(userInfoEx.DepartmentID);
                if (newDepartment != ASC.Core.Users.Constants.LostGroupInfo)
                {
                    userInfoEx.Info.Department = newDepartment.Name;
                }

                UserInfo newUserInfo = null;

                if (isNew && SecurityContext.IsAuthenticated &&
                    SecurityContext.CheckPermissions(ASC.Core.Users.Constants.Action_AddRemoveUser))
                {
                    var disableEditGroups = false;
                    if (!SecurityContext.CheckPermissions(ASC.Core.Users.Constants.Action_EditGroups))
                    {
                        userInfoEx.Info.Title = "";
                        disableEditGroups     = true;
                    }

                    newUserInfo = UserManagerWrapper.AddUser(userInfoEx.Info, userInfoEx.Pwd);

                    if (disableEditGroups == false && userInfoEx.DepartmentID != Guid.Empty)
                    {
                        CoreContext.UserManager.AddUserIntoGroup(newUserInfo.ID, userInfoEx.DepartmentID);
                    }

                    resp.rs3  = "add_user";
                    resp.rs10 = CustomNamingPeople.Substitute <Resources.Resource>("UserMakerAddUser").HtmlEncode();
                }
                else if (SecurityContext.CheckPermissions(ASC.Core.Users.Constants.Action_EditUser) ||
                         (self && SecurityContext.CheckPermissions(new UserSecurityProvider(SecurityContext.CurrentAccount.ID), ASC.Core.Users.Constants.Action_EditUser)))
                {
                    newUserInfo = (UserInfo)CoreContext.UserManager.GetUsers(userInfoEx.Info.ID).Clone();

                    newUserInfo.FirstName    = userInfoEx.Info.FirstName.Trim();
                    newUserInfo.LastName     = userInfoEx.Info.LastName.Trim();
                    newUserInfo.Sex          = userInfoEx.Info.Sex;
                    newUserInfo.Title        = userInfoEx.Info.Title.Trim();
                    newUserInfo.BirthDate    = userInfoEx.Info.BirthDate;
                    newUserInfo.WorkFromDate = userInfoEx.Info.WorkFromDate;

                    newUserInfo.Notes      = userInfoEx.Info.Notes.Trim();
                    newUserInfo.Department = userInfoEx.Info.Department;

                    newUserInfo.Location = userInfoEx.Info.Location.Trim();

                    newUserInfo.Contacts.Clear();
                    userInfoEx.Info.Contacts.ForEach(c => newUserInfo.Contacts.Add(c));

                    if (SecurityContext.CheckPermissions(ASC.Core.Users.Constants.Action_EditGroups))
                    {
                        var oldDep = GetDepartmentForUser(userInfoEx.Info.ID);

                        if (oldDep != null && !oldDep.ID.Equals(userInfoEx.DepartmentID))
                        {
                            CoreContext.UserManager.RemoveUserFromGroup(newUserInfo.ID, oldDep.ID);
                            newUserInfo.Department = "";
                        }

                        if (((oldDep != null && !oldDep.ID.Equals(userInfoEx.DepartmentID)) || oldDep == null) &&
                            userInfoEx.DepartmentID != Guid.Empty)
                        {
                            CoreContext.UserManager.AddUserIntoGroup(newUserInfo.ID, userInfoEx.DepartmentID);

                            var dep = CoreContext.GroupManager.GetGroupInfo(userInfoEx.DepartmentID);
                            newUserInfo.Department = dep.Name;
                        }
                    }

                    UserManagerWrapper.SaveUserInfo(newUserInfo);

                    resp.rs3  = "edit_user";
                    resp.rs10 = Resources.Resource.UserMakerEditUser;
                    resp.rs5  = SecurityContext.CurrentAccount.ID.Equals(newUserInfo.ID) ? "1" : "";

                    if (self && !CoreContext.UserManager.IsUserInGroup(SecurityContext.CurrentAccount.ID, ASC.Core.Users.Constants.GroupAdmin.ID))
                    {
                        StudioNotifyService.Instance.SendMsgToAdminAboutProfileUpdated();
                    }
                }
                else
                {
                    resp.rs1 = "0";
                    return(resp);
                }

                if (!String.IsNullOrEmpty(photoPath))
                {
                    var fileName = Path.GetFileName(photoPath);
                    var data     = UserPhotoManager.GetTempPhotoData(fileName);
                    UserPhotoManager.SaveOrUpdatePhoto(newUserInfo.ID, data);
                    try
                    {
                        UserPhotoManager.RemoveTempPhoto(fileName);
                    }
                    catch
                    {
                    }
                    ;
                }

                resp.rs1 = "1";
            }
            catch (Exception e)
            {
                resp.rs1 = "0";
                resp.rs2 = "<div>" + e.Message.HtmlEncode() + "</div>";
            }
            return(resp);
        }
コード例 #14
0
        private void SaveUsers(BaseCamp basecampManager)
        {
            var employees = basecampManager.People;
            var step      = 100.0 / employees.Count();

            foreach (var person in employees.Where(x => _withClosed ? true : !x.Deleted))
            {
                try
                {
                    Status.UserProgress += step;
                    Guid userID = FindUserByEmail(person.EmailAddress);

                    if (userID.Equals(Guid.Empty))
                    {
                        UserInfo userInfo = new UserInfo()
                        {
                            Email     = person.EmailAddress,
                            FirstName = person.FirstName,
                            LastName  = person.LastName,
                            Title     = person.Title,
                            Status    = person.Deleted ? EmployeeStatus.Terminated : EmployeeStatus.Active,
                        };

                        if (!string.IsNullOrEmpty(person.PhoneNumberMobile))
                        {
                            userInfo.AddSocialContact(SocialContactsManager.ContactType_mobphone, person.PhoneNumberMobile);
                        }
                        if (!string.IsNullOrEmpty(person.PhoneNumberHome))
                        {
                            userInfo.AddSocialContact(SocialContactsManager.ContactType_phone, person.PhoneNumberHome);
                        }
                        if (!string.IsNullOrEmpty(person.PhoneNumberOffice))
                        {
                            userInfo.AddSocialContact(SocialContactsManager.ContactType_phone, person.PhoneNumberOffice);
                        }
                        if (!string.IsNullOrEmpty(person.PhoneNumberFax))
                        {
                            userInfo.AddSocialContact(SocialContactsManager.ContactType_phone, person.PhoneNumberFax);
                        }
                        if (!string.IsNullOrEmpty(person.ImHandle))
                        {
                            switch (person.ImService)
                            {
                            case "MSN":
                                userInfo.AddSocialContact(SocialContactsManager.ContactType_msn, person.ImHandle);
                                break;

                            case "ICQ":
                                userInfo.AddSocialContact(SocialContactsManager.ContactType_icq, person.ImHandle);
                                break;

                            case "Yahoo":
                                userInfo.AddSocialContact(SocialContactsManager.ContactType_yahoo, person.ImHandle);
                                break;

                            case "Jabber":
                                userInfo.AddSocialContact(SocialContactsManager.ContactType_jabber, person.ImHandle);
                                break;

                            case "Skype":
                                userInfo.AddSocialContact(SocialContactsManager.ContactType_skype, person.ImHandle);
                                break;

                            case "Google":
                                userInfo.AddSocialContact(SocialContactsManager.ContactType_gmail, person.ImHandle);
                                break;
                            }
                        }

                        var newUserInfo = UserManagerWrapper.AddUser(userInfo, UserManagerWrapper.GeneratePassword(), false, !_disableNotifications);
                        if (person.Administrator)
                        {
                            CoreContext.UserManager.AddUserIntoGroup(newUserInfo.ID, ASC.Core.Users.Constants.GroupAdmin.ID);
                        }
                        NewUsersID.Add(new UserIDWrapper()
                        {
                            inBasecamp = person.ID, inProjects = newUserInfo.ID
                        });

                        //save user avatar
                        const string emptyAvatar = "http://asset1.37img.com/global/missing/avatar.png?r=3";//TODO:?!!! Wtf??!!
                        if (person.AvatarUrl != emptyAvatar)
                        {
                            UserPhotoManager.SaveOrUpdatePhoto(newUserInfo.ID, StreamFile(person.AvatarUrl));
                        }
                    }
                    else
                    {
                        NewUsersID.Add(new UserIDWrapper()
                        {
                            inBasecamp = person.ID, inProjects = userID
                        });
                    }
                }
                catch (Exception e)
                {
                    Status.LogError(string.Format(SettingsResource.FailedToSaveUser, person.EmailAddress), e);
                    LogError(string.Format("user '{0}' failed", person.EmailAddress), e);
                    NewUsersID.RemoveAll(x => x.inBasecamp == person.ID);
                }
            }
        }
コード例 #15
0
        public EmployeeWraperFull(UserInfo userInfo, ApiContext context)
            : base(userInfo)
        {
            UserName  = userInfo.UserName;
            IsVisitor = userInfo.IsVisitor();
            FirstName = userInfo.FirstName;
            LastName  = userInfo.LastName;
            Birthday  = (ApiDateTime)userInfo.BirthDate;

            if (userInfo.Sex.HasValue)
            {
                Sex = userInfo.Sex.Value ? "male" : "female";
            }

            Status           = userInfo.Status;
            ActivationStatus = userInfo.ActivationStatus;
            Terminated       = (ApiDateTime)userInfo.TerminatedDate;

            if (!string.IsNullOrEmpty(userInfo.Department))
            {
                Department = userInfo.Department;
            }

            WorkFrom = (ApiDateTime)userInfo.WorkFromDate;
            Email    = userInfo.Email;

            if (!string.IsNullOrEmpty(userInfo.Location))
            {
                Location = userInfo.Location;
            }

            if (!string.IsNullOrEmpty(userInfo.Notes))
            {
                Notes = userInfo.Notes;
            }

            if (!string.IsNullOrEmpty(userInfo.MobilePhone))
            {
                MobilePhone = userInfo.MobilePhone;
            }

            MobilePhoneActivationStatus = userInfo.MobilePhoneActivationStatus;

            if (!string.IsNullOrEmpty(userInfo.CultureName))
            {
                CultureName = userInfo.CultureName;
            }

            FillConacts(userInfo);

            var groups = Core.CoreContext.UserManager.GetUserGroups(userInfo.ID).Select(x => new GroupWrapperSummary(x)).ToList();

            if (groups.Any())
            {
                Groups = groups;
            }

            try
            {
                if (CheckContext(context, "avatarSmall"))
                {
                    AvatarSmall = UserPhotoManager.GetSmallPhotoURL(userInfo.ID);
                }

                if (CheckContext(context, "avatarMedium"))
                {
                    AvatarMedium = UserPhotoManager.GetMediumPhotoURL(userInfo.ID);
                }

                if (CheckContext(context, "avatar"))
                {
                    Avatar = UserPhotoManager.GetBigPhotoURL(userInfo.ID);
                }
            }
            catch (Exception)
            {
            }

            try
            {
                IsOnline = false;
                IsAdmin  = userInfo.IsAdmin();

                if (CheckContext(context, "listAdminModules"))
                {
                    var listAdminModules = userInfo.GetListAdminModules();

                    if (listAdminModules.Any())
                    {
                        ListAdminModules = listAdminModules;
                    }
                }

                IsOwner = userInfo.IsOwner();
            }
            catch (Exception)
            {
            }
        }
コード例 #16
0
 public static string GetSmallPhotoURL(this UserInfo userInfo, UserPhotoManager UserPhotoManager)
 {
     return(UserPhotoManager.GetSmallPhotoURL(userInfo.ID));
 }
コード例 #17
0
 public EmployeeWraperHelper(ApiContext httpContext, DisplayUserSettingsHelper displayUserSettingsHelper, UserPhotoManager userPhotoManager, CommonLinkUtility commonLinkUtility)
 {
     HttpContext = httpContext;
     DisplayUserSettingsHelper = displayUserSettingsHelper;
     UserPhotoManager          = userPhotoManager;
     CommonLinkUtility         = commonLinkUtility;
 }
コード例 #18
0
        public EmployeeWraperFull GetFull(UserInfo userInfo)
        {
            var result = new EmployeeWraperFull
            {
                UserName         = userInfo.UserName,
                FirstName        = userInfo.FirstName,
                LastName         = userInfo.LastName,
                Birthday         = ApiDateTime.FromDate(TenantManager, TimeZoneConverter, userInfo.BirthDate),
                Status           = userInfo.Status,
                ActivationStatus = userInfo.ActivationStatus & ~EmployeeActivationStatus.AutoGenerated,
                Terminated       = ApiDateTime.FromDate(TenantManager, TimeZoneConverter, userInfo.TerminatedDate),
                WorkFrom         = ApiDateTime.FromDate(TenantManager, TimeZoneConverter, userInfo.WorkFromDate),
                Email            = userInfo.Email,
                IsVisitor        = userInfo.IsVisitor(UserManager),
                IsAdmin          = userInfo.IsAdmin(UserManager),
                IsOwner          = userInfo.IsOwner(Context.Tenant),
                IsLDAP           = userInfo.IsLDAP(),
                IsSSO            = userInfo.IsSSO()
            };

            Init(result, userInfo);

            if (userInfo.Sex.HasValue)
            {
                result.Sex = userInfo.Sex.Value ? "male" : "female";
            }

            if (!string.IsNullOrEmpty(userInfo.Location))
            {
                result.Location = userInfo.Location;
            }

            if (!string.IsNullOrEmpty(userInfo.Notes))
            {
                result.Notes = userInfo.Notes;
            }

            if (!string.IsNullOrEmpty(userInfo.MobilePhone))
            {
                result.MobilePhone = userInfo.MobilePhone;
            }

            result.MobilePhoneActivationStatus = userInfo.MobilePhoneActivationStatus;

            if (!string.IsNullOrEmpty(userInfo.CultureName))
            {
                result.CultureName = userInfo.CultureName;
            }

            FillConacts(result, userInfo);

            if (Context.Check("groups") || Context.Check("department"))
            {
                var groups = UserManager.GetUserGroups(userInfo.ID)
                             .Select(x => new GroupWrapperSummary(x, UserManager))
                             .ToList();

                if (groups.Count > 0)
                {
                    result.Groups     = groups;
                    result.Department = string.Join(", ", result.Groups.Select(d => d.Name.HtmlEncode()));
                }
                else
                {
                    result.Department = "";
                }
            }

            var userInfoLM = userInfo.LastModified.GetHashCode();

            if (Context.Check("avatarMax"))
            {
                result.AvatarMax = UserPhotoManager.GetMaxPhotoURL(userInfo.ID, out var isdef) + (isdef ? "" : $"?_={userInfoLM}");
            }

            if (Context.Check("avatarMedium"))
            {
                result.AvatarMedium = UserPhotoManager.GetMediumPhotoURL(userInfo.ID, out var isdef) + (isdef ? "" : $"?_={userInfoLM}");
            }

            if (Context.Check("avatar"))
            {
                result.Avatar = UserPhotoManager.GetBigPhotoURL(userInfo.ID, out var isdef) + (isdef ? "" : $"?_={userInfoLM}");
            }

            if (Context.Check("listAdminModules"))
            {
                var listAdminModules = userInfo.GetListAdminModules(WebItemSecurity);

                if (listAdminModules.Any())
                {
                    result.ListAdminModules = listAdminModules;
                }
            }

            return(result);
        }
コード例 #19
0
        private void SaveUsers(IBaseCamp basecampManager)
        {
            var employees = basecampManager.People;
            var step      = 100.0 / employees.Count();

            foreach (var person in employees)
            {
                try
                {
                    if (TenantExtra.GetRemainingCountUsers() <= 0)
                    {
                        _importUsersOverLimitAsCollaborators = true;
                    }

                    StatusState.StatusUserProgress(step);
                    var userID = FindUserByEmail(person.EmailAddress);

                    if (userID.Equals(Guid.Empty))
                    {
                        var userName = Regex.Replace(person.UserName, @"[!|@|#|$|%|'|+]", "");
                        var name     = userName.Split(' ');
                        var userInfo = new UserInfo
                        {
                            Email     = person.EmailAddress,
                            FirstName = name.First(),
                            LastName  = name.Count() > 1 ? name.Last() : "",
                            UserName  = userName,
                            Status    = EmployeeStatus.Active,
                        };
                        var collaboratorFlag = _importUsersOverLimitAsCollaborators || _importUsersAsCollaborators;

                        if (!UserManagerWrapper.ValidateEmail(userInfo.Email))
                        {
                            throw new Exception("Invalid email");
                        }

                        var newUserInfo = UserManagerWrapper.AddUser(userInfo, UserManagerWrapper.GeneratePassword(), false, !_disableNotifications, collaboratorFlag);
                        _newUsersID.Add(new UserIDWrapper {
                            InBasecamp = person.ID, InProjects = newUserInfo.ID
                        });

                        //save user avatar
                        const string emptyAvatar = "http://asset0.37img.com/global/default_avatar_v1_4/avatar.gif?r=3";
                        if (person.AvatarUrl != emptyAvatar)
                        {
                            UserPhotoManager.SaveOrUpdatePhoto(newUserInfo.ID, StreamFile(person.AvatarUrl));
                        }
                    }
                    else
                    {
                        _newUsersID.Add(new UserIDWrapper {
                            InBasecamp = person.ID, InProjects = userID
                        });
                    }
                }
                catch (Exception e)
                {
                    StatusState.StatusLogError(string.Format(ImportResource.FailedToSaveUser, person.EmailAddress), e);
                    LogError(string.Format("user '{0}' failed", person.EmailAddress), e);
                    _newUsersID.RemoveAll(x => x.InBasecamp == person.ID);
                }
            }
        }
コード例 #20
0
 public static bool HasAvatar(this UserInfo userInfo, Tenant tenant)
 {
     return(UserPhotoManager.UserHasAvatar(tenant, userInfo.ID));
 }
コード例 #21
0
        public FileUploadResult ProcessUpload(HttpContext context)
        {
            var result = new FileUploadResult();

            try
            {
                if (context.Request.Files.Count != 0)
                {
                    Guid userId;
                    try
                    {
                        userId = new Guid(context.Request["userId"]);
                    }
                    catch
                    {
                        userId = SecurityContext.CurrentAccount.ID;
                    }
                    SecurityContext.DemandPermissions(new UserSecurityProvider(userId), Constants.Action_EditUser);

                    var userPhoto = context.Request.Files[0];

                    if (userPhoto.InputStream.Length > SetupInfo.MaxImageUploadSize)
                    {
                        result.Success = false;
                        result.Message = FileSizeComment.FileImageSizeExceptionString;
                        return(result);
                    }

                    var data = new byte[userPhoto.InputStream.Length];

                    var br = new BinaryReader(userPhoto.InputStream);
                    br.Read(data, 0, (int)userPhoto.InputStream.Length);
                    br.Close();

                    CheckImgFormat(data);

                    if (context.Request["autosave"] == "true")
                    {
                        if (data.Length > SetupInfo.MaxImageUploadSize)
                        {
                            throw new ImageSizeLimitException();
                        }

                        var mainPhoto = UserPhotoManager.SaveOrUpdatePhoto(userId, data);

                        result.Data =
                            new
                        {
                            main   = mainPhoto,
                            retina = UserPhotoManager.GetRetinaPhotoURL(userId),
                            max    = UserPhotoManager.GetMaxPhotoURL(userId),
                            big    = UserPhotoManager.GetBigPhotoURL(userId),
                            medium = UserPhotoManager.GetMediumPhotoURL(userId),
                            small  = UserPhotoManager.GetSmallPhotoURL(userId),
                        };
                    }
                    else
                    {
                        result.Data = UserPhotoManager.SaveTempPhoto(data, SetupInfo.MaxImageUploadSize, UserPhotoManager.OriginalFotoSize.Width, UserPhotoManager.OriginalFotoSize.Height);
                    }

                    result.Success = true;
                }
                else
                {
                    result.Success = false;
                    result.Message = PeopleResource.ErrorEmptyUploadFileSelected;
                }
            }
            catch (UnknownImageFormatException)
            {
                result.Success = false;
                result.Message = PeopleResource.ErrorUnknownFileImageType;
            }
            catch (ImageWeightLimitException)
            {
                result.Success = false;
                result.Message = PeopleResource.ErrorImageWeightLimit;
            }
            catch (ImageSizeLimitException)
            {
                result.Success = false;
                result.Message = PeopleResource.ErrorImageSizetLimit;
            }
            catch (Exception ex)
            {
                result.Success = false;
                result.Message = ex.Message.HtmlEncode();
            }

            return(result);
        }
コード例 #22
0
 public static Size GetPhotoSize(this UserInfo userInfo, Tenant tenant)
 {
     return(UserPhotoManager.GetPhotoSize(tenant, userInfo.ID));
 }
コード例 #23
0
        public EmployeeWraperFull UpdateMember(bool isVisitor, string userid, string email, string firstname, string lastname, string comment, Guid[] department, string title, string location, string sex, ApiDateTime birthday, ApiDateTime worksfrom, IEnumerable <Contact> contacts, string files, bool?disable)
        {
            SecurityContext.DemandPermissions(new UserSecurityProvider(new Guid(userid)), Core.Users.Constants.Action_EditUser);

            var user = GetUserInfo(userid);

            if (CoreContext.UserManager.IsSystemUser(user.ID))
            {
                throw new SecurityException();
            }

            var self      = SecurityContext.CurrentAccount.ID.Equals(user.ID);
            var resetDate = new DateTime(1900, 01, 01);

            //Update it

            //Validate email
            if (!string.IsNullOrEmpty(email))
            {
                var address = new MailAddress(email);
                user.Email = address.Address;
            }

            //Set common fields
            user.FirstName = firstname ?? user.FirstName;
            user.LastName  = lastname ?? user.LastName;
            user.Title     = title ?? user.Title;
            user.Location  = location ?? user.Location;
            user.Notes     = comment ?? user.Notes;
            user.Sex       = ("male".Equals(sex, StringComparison.OrdinalIgnoreCase)
                            ? true
                            : ("female".Equals(sex, StringComparison.OrdinalIgnoreCase) ? (bool?)false : null)) ?? user.Sex;

            user.BirthDate = birthday != null?TenantUtil.DateTimeFromUtc(Convert.ToDateTime(birthday)) : user.BirthDate;

            if (user.BirthDate == resetDate)
            {
                user.BirthDate = null;
            }

            user.WorkFromDate = worksfrom != null?TenantUtil.DateTimeFromUtc(Convert.ToDateTime(worksfrom)) : user.WorkFromDate;

            if (user.WorkFromDate == resetDate)
            {
                user.WorkFromDate = null;
            }

            //Update contacts
            UpdateContacts(contacts, user);
            UpdateDepartments(department, user);

            if (files != UserPhotoManager.GetPhotoAbsoluteWebPath(user.ID))
            {
                UpdatePhotoUrl(files, user);
            }
            if (disable.HasValue)
            {
                user.Status         = disable.Value ? EmployeeStatus.Terminated : EmployeeStatus.Active;
                user.TerminatedDate = disable.Value ? DateTime.UtcNow : (DateTime?)null;
            }

            if (self && !CoreContext.UserManager.IsUserInGroup(SecurityContext.CurrentAccount.ID, Core.Users.Constants.GroupAdmin.ID))
            {
                StudioNotifyService.Instance.SendMsgToAdminAboutProfileUpdated();
            }

            // change user type
            var canBeGuestFlag = !user.IsOwner() && !user.IsAdmin() && !user.GetListAdminModules().Any() && !user.IsMe();

            if (isVisitor && !user.IsVisitor() && canBeGuestFlag)
            {
                CoreContext.UserManager.AddUserIntoGroup(user.ID, Core.Users.Constants.GroupVisitor.ID);
                WebItemSecurity.ClearCache();
            }

            if (!self && !isVisitor && user.IsVisitor())
            {
                var usersQuota = TenantExtra.GetTenantQuota().ActiveUsers;
                if (TenantStatisticsProvider.GetUsersCount() < usersQuota)
                {
                    CoreContext.UserManager.RemoveUserFromGroup(user.ID, Core.Users.Constants.GroupVisitor.ID);
                    WebItemSecurity.ClearCache();
                }
                else
                {
                    throw new TenantQuotaException(string.Format("Exceeds the maximum active users ({0})", usersQuota));
                }
            }

            CoreContext.UserManager.SaveUserInfo(user, isVisitor);
            MessageService.Send(Request, MessageAction.UserUpdated, user.DisplayUserName(false));

            return(new EmployeeWraperFull(user));
        }
コード例 #24
0
 public static string GetSmallPhotoURL(this UserInfo userInfo, int tenantId)
 {
     return(UserPhotoManager.GetSmallPhotoURL(tenantId, userInfo.ID));
 }
コード例 #25
0
        public FileUploadResult ProcessUpload(HttpContext context)
        {
            var result = new FileUploadResult();

            try
            {
                SecurityContext.DemandPermissions(SecutiryConstants.EditPortalSettings);

                var width = Convert.ToInt32(context.Request["size"]);
                var size  = new Size(width, width);

                if (context.Request.Files.Count != 0)
                {
                    const string imgContentType = @"image";

                    var logo = context.Request.Files[0];
                    if (!logo.ContentType.StartsWith(imgContentType))
                    {
                        throw new Exception(WhiteLabelResource.ErrorFileNotImage);
                    }

                    var data = new byte[logo.InputStream.Length];

                    var reader = new BinaryReader(logo.InputStream);
                    reader.Read(data, 0, (int)logo.InputStream.Length);
                    reader.Close();

                    using (var stream = new MemoryStream(data))
                        using (var image = Image.FromStream(stream))
                        {
                            var actualSize = image.Size;
                            if (actualSize.Height != size.Height || actualSize.Width != size.Width)
                            {
                                throw new ImageSizeLimitException();
                            }
                        }

                    result.Success = true;
                    result.Message = UserPhotoManager.SaveTempPhoto(data, SetupInfo.MaxImageUploadSize, size.Width,
                                                                    size.Height);
                }
                else
                {
                    result.Success = false;
                    result.Message = Resource.ErrorEmptyUploadFileSelected;
                }
            }
            catch (ImageWeightLimitException)
            {
                result.Success = false;
                result.Message = Resource.ErrorImageWeightLimit;
            }
            catch (ImageSizeLimitException)
            {
                result.Success = false;
                result.Message = WhiteLabelResource.ErrorImageSize;
            }
            catch (Exception ex)
            {
                result.Success = false;
                result.Message = ex.Message.HtmlEncode();
            }

            return(result);
        }
コード例 #26
0
        private void SyncLdapAvatar()
        {
            SetProgress(90, Resource.LdapSettingsStatusUpdatingUserPhotos);

            if (!LDAPSettings.LdapMapping.ContainsKey(LdapSettings.MappingFields.AvatarAttribute))
            {
                var ph = LdapCurrentUserPhotos.Load();

                if (ph.CurrentPhotos == null || !ph.CurrentPhotos.Any())
                {
                    return;
                }

                foreach (var guid in ph.CurrentPhotos.Keys)
                {
                    Logger.InfoFormat("SyncLdapAvatar() Removing photo for '{0}'", guid);
                    UserPhotoManager.RemovePhoto(guid);
                    UserPhotoManager.ResetThumbnailSettings(guid);
                }

                ph.CurrentPhotos = null;
                ph.Save();
                return;
            }

            var photoSettings = LdapCurrentUserPhotos.Load();

            if (photoSettings.CurrentPhotos == null)
            {
                photoSettings.CurrentPhotos = new Dictionary <Guid, string>();
            }

            var ldapUsers      = Importer.AllDomainUsers.Where(x => !x.IsDisabled);
            var step           = 5.0 / ldapUsers.Count();
            var currentPercent = 90.0;

            foreach (var ldapUser in ldapUsers)
            {
                var image = ldapUser.GetValue(LDAPSettings.LdapMapping[LdapSettings.MappingFields.AvatarAttribute], true);

                if (image == null || image.GetType() != typeof(byte[]))
                {
                    continue;
                }

                string hash;
                using (MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider())
                {
                    hash = Convert.ToBase64String(md5.ComputeHash((byte[])image));
                }

                var user = CoreContext.UserManager.GetUserBySid(ldapUser.Sid);

                Logger.DebugFormat("SyncLdapAvatar() Found photo for '{0}'", ldapUser.Sid);

                if (photoSettings.CurrentPhotos.ContainsKey(user.ID) && photoSettings.CurrentPhotos[user.ID] == hash)
                {
                    Logger.Debug("SyncLdapAvatar() Same hash, skipping.");
                    continue;
                }

                try
                {
                    SetProgress((int)(currentPercent += step),
                                string.Format("{0}: {1}", Resource.LdapSettingsStatusSavingUserPhoto, UserFormatter.GetUserName(user, DisplayUserNameFormat.Default)));
                    UserPhotoManager.ResetThumbnailSettings(user.ID);
                    UserPhotoManager.SaveOrUpdatePhoto(user.ID, (byte[])image);

                    if (photoSettings.CurrentPhotos.ContainsKey(user.ID))
                    {
                        photoSettings.CurrentPhotos[user.ID] = hash;
                    }
                    else
                    {
                        photoSettings.CurrentPhotos.Add(user.ID, hash);
                    }
                }
                catch
                {
                    Logger.DebugFormat("SyncLdapAvatar() Couldn't save photo for '{0}'", user.ID);
                    if (photoSettings.CurrentPhotos.ContainsKey(user.ID))
                    {
                        photoSettings.CurrentPhotos.Remove(user.ID);
                    }
                }
            }

            photoSettings.Save();
        }
コード例 #27
0
 public static Size GetPhotoSize(this UserInfo userInfo)
 {
     return(UserPhotoManager.GetPhotoSize(userInfo.ID));
 }
コード例 #28
0
        public override void HandleMessage(XmppStream stream, Message message, XmppHandlerContext context)
        {
            if (!message.HasTo || message.To.IsServer)
            {
                context.Sender.SendTo(stream, XmppStanzaError.ToServiceUnavailable(message));
                return;
            }

            var sessions = context.SessionManager.GetBareJidSessions(message.To);

            if (0 < sessions.Count)
            {
                foreach (var s in sessions)
                {
                    try
                    {
                        context.Sender.SendTo(s, message);
                    }
                    catch
                    {
                        context.Sender.SendToAndClose(s.Stream, message);
                    }
                }
            }
            else
            {
                pushStore = new DbPushStore();
                var properties = new Dictionary <string, string>(1);
                properties.Add("connectionStringName", "default");
                pushStore.Configure(properties);

                if (message.HasTag("active"))
                {
                    var fromFullName = message.HasAttribute("username") ?
                                       message.GetAttribute("username") : message.From.ToString();


                    var messageToDomain = message.To.ToString().Split(new char[] { '@' })[1];
                    var tenant          = CoreContext.TenantManager.GetTenant(messageToDomain);
                    var tenantId        = tenant != null ? tenant.TenantId : -1;

                    var userPushList = new List <UserPushInfo>();
                    userPushList = pushStore.GetUserEndpoint(message.To.ToString().Split(new char[] { '@' })[0]);

                    var firebaseAuthorization = "";
                    try
                    {
                        CallContext.SetData(TenantManager.CURRENT_TENANT, new Tenant(tenantId, ""));
                        firebaseAuthorization = FireBase.Instance.Authorization;
                    }
                    catch (Exception exp)
                    {
                        log.DebugFormat("firebaseAuthorizationERROR: {0}", exp);
                    }
                    foreach (var user in userPushList)
                    {
                        try
                        {
                            var           from = message.From.ToString().Split(new char[] { '@' })[0];
                            List <string> userId;
                            string        photoPath = "";
                            using (var db = new DbManager("core"))
                                using (var command = db.Connection.CreateCommand())
                                {
                                    var q = new SqlQuery("core_user").Select("id").Where(Exp.Like("username", from)).Where("tenant", tenantId);

                                    userId = command.ExecuteList(q, DbRegistry.GetSqlDialect(db.DatabaseId))
                                             .ConvertAll(r => Convert.ToString(r[0]))
                                             .ToList();
                                }
                            if (userId.Count != 0)
                            {
                                var guid = new Guid(userId[0]);
                                photoPath = UserPhotoManager.GetBigPhotoURL(guid);
                            }

                            var tRequest = WebRequest.Create("https://fcm.googleapis.com/fcm/send");
                            tRequest.Method      = "post";
                            tRequest.ContentType = "application/json";
                            var data = new
                            {
                                to   = user.endpoint,
                                data = new
                                {
                                    msg          = message.Body,
                                    fromFullName = fromFullName,
                                    photoPath    = photoPath
                                }
                            };
                            var serializer = new JavaScriptSerializer();
                            var json       = serializer.Serialize(data);
                            var byteArray  = Encoding.UTF8.GetBytes(json);
                            tRequest.Headers.Add(string.Format("Authorization: key={0}", firebaseAuthorization));
                            tRequest.ContentLength = byteArray.Length;
                            using (var dataStream = tRequest.GetRequestStream())
                            {
                                dataStream.Write(byteArray, 0, byteArray.Length);
                                using (var tResponse = tRequest.GetResponse())
                                {
                                    using (var dataStreamResponse = tResponse.GetResponseStream())
                                    {
                                        using (var tReader = new StreamReader(dataStreamResponse))
                                        {
                                            var sResponseFromServer = tReader.ReadToEnd();
                                            var str = sResponseFromServer;
                                        }
                                    }
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            var str = ex.Message;
                            log.DebugFormat("PushRequestERROR: {0}", str);
                        }
                    }
                }
                StoreOffline(message, context.StorageManager.OfflineStorage);
            }
        }
コード例 #29
0
 public static string GetBigPhotoURL(this UserInfo userInfo)
 {
     return(UserPhotoManager.GetBigPhotoURL(userInfo.ID));
 }
コード例 #30
0
        public FileUploadResult ProcessUpload(HttpContext context)
        {
            var result = new FileUploadResult();

            try
            {
                var type           = Convert.ToInt32(context.Request["logotype"]);
                var coBrandingType = (CoBrandingLogoTypeEnum)type;

                if (context.Request.Files.Count != 0)
                {
                    var logo = context.Request.Files[0];
                    var data = new byte[logo.InputStream.Length];

                    var br = new BinaryReader(logo.InputStream);
                    br.Read(data, 0, (int)logo.InputStream.Length);
                    br.Close();


                    var size = TenantCoBrandingSettings.GetSize(coBrandingType, false);

                    //get size
                    using (var memory = new MemoryStream(data))
                        using (var image = Image.FromStream(memory))
                        {
                            var actualSize = image.Size;
                            if (actualSize.Height != size.Height || actualSize.Width != size.Width)
                            {
                                throw new ImageSizeLimitException();
                            }
                        }

                    var ap = UserPhotoManager.SaveTempPhoto(data, SetupInfo.MaxImageUploadSize, size.Width, size.Height);

                    result.Success = true;
                    result.Message = ap;
                }
                else
                {
                    result.Success = false;
                    result.Message = Resource.ErrorEmptyUploadFileSelected;
                }
            }
            catch (ImageWeightLimitException)
            {
                result.Success = false;
                result.Message = Resource.ErrorImageWeightLimit;
            }
            catch (ImageSizeLimitException)
            {
                result.Success = false;
                result.Message = CoBrandingResource.ErrorImageSize;
            }
            catch (Exception ex)
            {
                result.Success = false;
                result.Message = ex.Message.HtmlEncode();
            }

            return(result);
        }