private void UpdatePhotoUrl(string files, UserInfo user)
        {
            if (string.IsNullOrEmpty(files))
            {
                return;
            }

            SecurityContext.DemandPermissions(new UserSecurityProvider(user.ID), Core.Users.Constants.Action_EditUser);

            if (!files.StartsWith("http://") && !files.StartsWith("https://"))
            {
                files = _context.RequestContext.HttpContext.Request.Url.GetLeftPart(UriPartial.Scheme | UriPartial.Authority) + "/" + files.TrimStart('/');
            }
            var request = HttpWebRequest.Create(files);

            using (var response = (HttpWebResponse)request.GetResponse())
            {
                using (var inputStream = response.GetResponseStream())
                    using (var br = new BinaryReader(inputStream))
                    {
                        var imageByteArray = br.ReadBytes((int)response.ContentLength);
                        UserPhotoManager.SaveOrUpdatePhoto(user.ID, imageByteArray);
                    }
            }
        }
Beispiel #2
0
 private static void UpdatePhotoUrl(string files, UserInfo user)
 {
     if (!String.IsNullOrEmpty(files))
     {
         var fileName    = Path.GetFileName(files);
         var photoUpload = UserPhotoManager.GetTempPhotoData(fileName);
         UserPhotoManager.SaveOrUpdatePhoto(user.ID, photoUpload);
     }
 }
Beispiel #3
0
        private static void UpdatePhotoUrl(string files, UserInfo user)
        {
            SecurityContext.DemandPermissions(new UserSecurityProvider(user.ID), Core.Users.Constants.Action_EditUser);
            if (String.IsNullOrEmpty(files))
            {
                return;
            }

            var fileName    = Path.GetFileName(files);
            var photoUpload = UserPhotoManager.GetTempPhotoData(fileName);

            UserPhotoManager.SaveOrUpdatePhoto(user.ID, photoUpload);
        }
Beispiel #4
0
 private static void UpdatePhoto(IEnumerable <HttpPostedFileBase> files, UserInfo user)
 {
     if (files != null)
     {
         var file = files.FirstOrDefault(x => x.ContentType.StartsWith("image/") && x.ContentLength > 0);
         if (file != null)
         {
             if (file.InputStream.CanRead)
             {
                 //Read a stream
                 var buffer = new byte[file.ContentLength];
                 file.InputStream.Read(buffer, 0, buffer.Length);
                 UserPhotoManager.SaveOrUpdatePhoto(user.ID, buffer);
             }
         }
     }
 }
Beispiel #5
0
        private static void SaveContactImage(Guid userID, string url)
        {
            using (var memstream = new MemoryStream())
            {
                var req      = WebRequest.Create(url);
                var response = req.GetResponse();
                var stream   = response.GetResponseStream();

                var buffer = new byte[512];
                int bytesRead;
                while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) > 0)
                {
                    memstream.Write(buffer, 0, bytesRead);
                }
                var bytes = memstream.ToArray();

                UserPhotoManager.SaveOrUpdatePhoto(userID, bytes);
            }
        }
Beispiel #6
0
 public void SaveOrUpdatePhoto(string photoUrl, Guid userId)
 {
     if (photoUrl != null)
     {
         if (CheckUri(photoUrl))
         {
             log.DebugFormat("Loading image: {0}", photoUrl);
             var data = GetUserPhoto(photoUrl);
             if (data != null)
             {
                 UserPhotoManager.SaveOrUpdatePhoto(userId, data);
             }
             else
             {
                 log.DebugFormat("Can't load image: {0}. Image size is more than 1Mb", photoUrl);
             }
         }
         else
         {
             log.ErrorFormat("Wrong photo url: {0}", photoUrl);
         }
     }
 }
        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);
        }
Beispiel #8
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);
                }
            }
        }
Beispiel #9
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();
        }
Beispiel #10
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);
        }
        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);
                }
            }
        }