示例#1
0
        private IEnumerable <Guid> WhoCan <T>(FileEntry <T> entry, FilesSecurityActions action)
        {
            var shares = GetShares(entry);

            FileShareRecord defaultShareRecord;

            switch (entry.RootFolderType)
            {
            case FolderType.COMMON:
                defaultShareRecord = new FileShareRecord
                {
                    Level     = int.MaxValue,
                    EntryId   = entry.ID,
                    EntryType = entry.FileEntryType,
                    Share     = DefaultCommonShare,
                    Subject   = Constants.GroupEveryone.ID,
                    Tenant    = TenantManager.GetCurrentTenant().TenantId,
                    Owner     = AuthContext.CurrentAccount.ID
                };

                if (!shares.Any())
                {
                    if ((defaultShareRecord.Share == FileShare.Read && action == FilesSecurityActions.Read) ||
                        (defaultShareRecord.Share == FileShare.ReadWrite))
                    {
                        return(UserManager.GetUsersByGroup(defaultShareRecord.Subject)
                               .Where(x => x.Status == EmployeeStatus.Active).Select(y => y.ID).Distinct());
                    }

                    return(Enumerable.Empty <Guid>());
                }

                break;

            case FolderType.USER:
                defaultShareRecord = new FileShareRecord
                {
                    Level     = int.MaxValue,
                    EntryId   = entry.ID,
                    EntryType = entry.FileEntryType,
                    Share     = DefaultMyShare,
                    Subject   = entry.RootFolderCreator,
                    Tenant    = TenantManager.GetCurrentTenant().TenantId,
                    Owner     = entry.RootFolderCreator
                };

                if (!shares.Any())
                {
                    return new List <Guid>
                           {
                               entry.RootFolderCreator
                           }
                }
                ;

                break;

            case FolderType.Privacy:
                defaultShareRecord = new FileShareRecord
                {
                    Level     = int.MaxValue,
                    EntryId   = entry.ID,
                    EntryType = entry.FileEntryType,
                    Share     = DefaultPrivacyShare,
                    Subject   = entry.RootFolderCreator,
                    Tenant    = TenantManager.GetCurrentTenant().TenantId,
                    Owner     = entry.RootFolderCreator
                };

                if (!shares.Any())
                {
                    return new List <Guid>
                           {
                               entry.RootFolderCreator
                           }
                }
                ;

                break;

            case FolderType.BUNCH:
                if (action == FilesSecurityActions.Read)
                {
                    var folderDao = daoFactory.GetFolderDao <T>();

                    var root = folderDao.GetFolder(entry.RootFolderId);
                    if (root != null)
                    {
                        var path = folderDao.GetBunchObjectID(root.ID);

                        var adapter = FilesIntegration.GetFileSecurity(path);

                        if (adapter != null)
                        {
                            return(adapter.WhoCanRead(entry));
                        }
                    }
                }

                // TODO: For Projects and other
                defaultShareRecord = null;
                break;

            default:
                defaultShareRecord = null;
                break;
            }

            if (defaultShareRecord != null)
            {
                shares = shares.Concat(new[] { defaultShareRecord });
            }

            return(shares.SelectMany(x =>
            {
                var groupInfo = UserManager.GetGroupInfo(x.Subject);

                if (groupInfo.ID != Constants.LostGroupInfo.ID)
                {
                    return
                    UserManager.GetUsersByGroup(groupInfo.ID)
                    .Where(p => p.Status == EmployeeStatus.Active)
                    .Select(y => y.ID);
                }

                return new[] { x.Subject };
            })
                   .Distinct()
                   .Where(x => Can(entry, x, action))
                   .ToList());
        }
示例#2
0
        private IEnumerable <FileEntry <T> > Filter <T>(IEnumerable <FileEntry <T> > entries, FilesSecurityActions action, Guid userId)
        {
            if (entries == null || !entries.Any())
            {
                return(Enumerable.Empty <FileEntry <T> >());
            }

            var user       = UserManager.GetUsers(userId);
            var isOutsider = user.IsOutsider(UserManager);

            if (isOutsider && action != FilesSecurityActions.Read)
            {
                return(Enumerable.Empty <FileEntry <T> >());
            }

            entries = entries.Where(f => f != null).ToList();
            var result = new List <FileEntry <T> >(entries.Count());

            // save entries order
            var order = entries.Select((f, i) => new { Id = f.UniqID, Pos = i }).ToDictionary(e => e.Id, e => e.Pos);

            // common or my files
            Func <FileEntry <T>, bool> filter =
                f => f.RootFolderType == FolderType.COMMON ||
                f.RootFolderType == FolderType.USER ||
                f.RootFolderType == FolderType.SHARE ||
                f.RootFolderType == FolderType.Recent ||
                f.RootFolderType == FolderType.Favorites ||
                f.RootFolderType == FolderType.Templates ||
                f.RootFolderType == FolderType.Privacy ||
                f.RootFolderType == FolderType.Projects;

            var isVisitor = user.IsVisitor(UserManager);

            if (entries.Any(filter))
            {
                var subjects = GetUserSubjects(userId);
                List <FileShareRecord> shares = null;
                foreach (var e in entries.Where(filter))
                {
                    if (!AuthManager.GetAccountByID(TenantManager.GetCurrentTenant().TenantId, userId).IsAuthenticated&& userId != FileConstant.ShareLinkId)
                    {
                        continue;
                    }

                    if (isOutsider && (e.RootFolderType == FolderType.USER ||
                                       e.RootFolderType == FolderType.SHARE ||
                                       e.RootFolderType == FolderType.Privacy))
                    {
                        continue;
                    }

                    if (isVisitor && e.RootFolderType == FolderType.Recent)
                    {
                        continue;
                    }

                    if (isVisitor && e.RootFolderType == FolderType.Favorites)
                    {
                        continue;
                    }

                    if (isVisitor && e.RootFolderType == FolderType.Templates)
                    {
                        continue;
                    }

                    if (isVisitor && e.RootFolderType == FolderType.Privacy)
                    {
                        continue;
                    }

                    if (action != FilesSecurityActions.Read && e.FileEntryType == FileEntryType.Folder && ((Folder <T>)e).FolderType == FolderType.Projects)
                    {
                        // Root Projects folder read-only
                        continue;
                    }

                    if (action != FilesSecurityActions.Read && e.FileEntryType == FileEntryType.Folder && ((Folder <T>)e).FolderType == FolderType.SHARE)
                    {
                        // Root Share folder read-only
                        continue;
                    }

                    if (action != FilesSecurityActions.Read && e.FileEntryType == FileEntryType.Folder && ((Folder <T>)e).FolderType == FolderType.Recent)
                    {
                        // Recent folder read-only
                        continue;
                    }

                    if (action != FilesSecurityActions.Read && e.FileEntryType == FileEntryType.Folder && ((Folder <T>)e).FolderType == FolderType.Favorites)
                    {
                        // Favorites folder read-only
                        continue;
                    }

                    if (action != FilesSecurityActions.Read && e.FileEntryType == FileEntryType.Folder && ((Folder <T>)e).FolderType == FolderType.Templates)
                    {
                        // Templates folder read-only
                        continue;
                    }

                    if (isVisitor && e.ProviderEntry)
                    {
                        continue;
                    }

                    if (e.RootFolderType == FolderType.USER && e.RootFolderCreator == userId && !isVisitor)
                    {
                        // user has all right in his folder
                        result.Add(e);
                        continue;
                    }

                    if (e.RootFolderType == FolderType.Privacy && e.RootFolderCreator == userId && !isVisitor)
                    {
                        // user has all right in his privacy folder
                        result.Add(e);
                        continue;
                    }

                    if (DefaultCommonShare == FileShare.Read && action == FilesSecurityActions.Read && e.FileEntryType == FileEntryType.Folder &&
                        ((Folder <T>)e).FolderType == FolderType.COMMON)
                    {
                        // all can read Common folder
                        result.Add(e);
                        continue;
                    }

                    if (action == FilesSecurityActions.Read && e.FileEntryType == FileEntryType.Folder &&
                        ((Folder <T>)e).FolderType == FolderType.SHARE)
                    {
                        // all can read Share folder
                        result.Add(e);
                        continue;
                    }

                    if (action == FilesSecurityActions.Read && e.FileEntryType == FileEntryType.Folder &&
                        ((Folder <T>)e).FolderType == FolderType.Recent)
                    {
                        // all can read recent folder
                        result.Add(e);
                        continue;
                    }

                    if (action == FilesSecurityActions.Read && e.FileEntryType == FileEntryType.Folder &&
                        ((Folder <T>)e).FolderType == FolderType.Favorites)
                    {
                        // all can read favorites folder
                        result.Add(e);
                        continue;
                    }

                    if (action == FilesSecurityActions.Read && e.FileEntryType == FileEntryType.Folder &&
                        ((Folder <T>)e).FolderType == FolderType.Templates)
                    {
                        // all can read templates folder
                        result.Add(e);
                        continue;
                    }


                    if (e.RootFolderType == FolderType.COMMON && FileSecurityCommon.IsAdministrator(userId))
                    {
                        // administrator in Common has all right
                        result.Add(e);
                        continue;
                    }

                    if (shares == null)
                    {
                        shares = GetShares(entries).Join(subjects, r => r.Subject, s => s, (r, s) => r).ToList();
                        // shares ordered by level
                    }

                    FileShareRecord ace;
                    if (e.FileEntryType == FileEntryType.File)
                    {
                        ace = shares
                              .OrderBy(r => r, new SubjectComparer(subjects))
                              .ThenByDescending(r => r.Share, new FileShareRecord.ShareComparer())
                              .FirstOrDefault(r => Equals(r.EntryId, e.ID) && r.EntryType == FileEntryType.File);
                        if (ace == null)
                        {
                            // share on parent folders
                            ace = shares.Where(r => Equals(r.EntryId, ((File <T>)e).FolderID) && r.EntryType == FileEntryType.Folder)
                                  .OrderBy(r => r, new SubjectComparer(subjects))
                                  .ThenBy(r => r.Level)
                                  .ThenByDescending(r => r.Share, new FileShareRecord.ShareComparer())
                                  .FirstOrDefault();
                        }
                    }
                    else
                    {
                        ace = shares.Where(r => Equals(r.EntryId, e.ID) && r.EntryType == FileEntryType.Folder)
                              .OrderBy(r => r, new SubjectComparer(subjects))
                              .ThenBy(r => r.Level)
                              .ThenByDescending(r => r.Share, new FileShareRecord.ShareComparer())
                              .FirstOrDefault();
                    }

                    var defaultShare = e.RootFolderType == FolderType.USER
                        ? DefaultMyShare
                        : e.RootFolderType == FolderType.Privacy
                            ? DefaultPrivacyShare
                            : DefaultCommonShare;
                    e.Access = ace != null
                        ? ace.Share
                        : userId == FileConstant.ShareLinkId
                            ? FileShare.Restrict
                            : defaultShare;

                    if (action == FilesSecurityActions.Read && e.Access != FileShare.Restrict)
                    {
                        result.Add(e);
                    }
                    else if (action == FilesSecurityActions.Comment && (e.Access == FileShare.Comment || e.Access == FileShare.Review || e.Access == FileShare.CustomFilter || e.Access == FileShare.ReadWrite))
                    {
                        result.Add(e);
                    }
                    else if (action == FilesSecurityActions.FillForms && (e.Access == FileShare.FillForms || e.Access == FileShare.Review || e.Access == FileShare.ReadWrite))
                    {
                        result.Add(e);
                    }
                    else if (action == FilesSecurityActions.Review && (e.Access == FileShare.Review || e.Access == FileShare.ReadWrite))
                    {
                        result.Add(e);
                    }
                    else if (action == FilesSecurityActions.CustomFilter && (e.Access == FileShare.CustomFilter || e.Access == FileShare.ReadWrite))
                    {
                        result.Add(e);
                    }
                    else if (action == FilesSecurityActions.Edit && e.Access == FileShare.ReadWrite)
                    {
                        result.Add(e);
                    }
                    else if (action == FilesSecurityActions.Create && e.Access == FileShare.ReadWrite)
                    {
                        result.Add(e);
                    }
                    else if (e.Access != FileShare.Restrict && e.CreateBy == userId && (e.FileEntryType == FileEntryType.File || ((Folder <T>)e).FolderType != FolderType.COMMON))
                    {
                        result.Add(e);
                    }

                    if (e.CreateBy == userId)
                    {
                        e.Access = FileShare.None;                       //HACK: for client
                    }
                }
            }

            // files in bunch
            filter = f => f.RootFolderType == FolderType.BUNCH;
            if (entries.Any(filter))
            {
                var folderDao       = daoFactory.GetFolderDao <T>();
                var filteredEntries = entries.Where(filter).ToList();
                var roots           = filteredEntries
                                      .Select(r => r.RootFolderId)
                                      .ToArray();

                var rootsFolders   = folderDao.GetFolders(roots);
                var bunches        = folderDao.GetBunchObjectIDs(rootsFolders.Select(r => r.ID).ToList());
                var findedAdapters = FilesIntegration.GetFileSecurity(bunches);

                foreach (var e in filteredEntries)
                {
                    var adapter = findedAdapters[e.RootFolderId.ToString()];

                    if (adapter == null)
                    {
                        continue;
                    }

                    if (adapter.CanRead(e, userId) &&
                        adapter.CanCreate(e, userId) &&
                        adapter.CanEdit(e, userId) &&
                        adapter.CanDelete(e, userId))
                    {
                        e.Access = FileShare.None;
                        result.Add(e);
                    }
                    else if (action == FilesSecurityActions.Comment && adapter.CanComment(e, userId))
                    {
                        e.Access = FileShare.Comment;
                        result.Add(e);
                    }
                    else if (action == FilesSecurityActions.FillForms && adapter.CanFillForms(e, userId))
                    {
                        e.Access = FileShare.FillForms;
                        result.Add(e);
                    }
                    else if (action == FilesSecurityActions.Review && adapter.CanReview(e, userId))
                    {
                        e.Access = FileShare.Review;
                        result.Add(e);
                    }
                    else if (action == FilesSecurityActions.CustomFilter && adapter.CanCustomFilterEdit(e, userId))
                    {
                        e.Access = FileShare.CustomFilter;
                        result.Add(e);
                    }
                    else if (action == FilesSecurityActions.Create && adapter.CanCreate(e, userId))
                    {
                        e.Access = FileShare.ReadWrite;
                        result.Add(e);
                    }
                    else if (action == FilesSecurityActions.Delete && adapter.CanDelete(e, userId))
                    {
                        e.Access = FileShare.ReadWrite;
                        result.Add(e);
                    }
                    else if (action == FilesSecurityActions.Read && adapter.CanRead(e, userId))
                    {
                        if (adapter.CanCreate(e, userId) ||
                            adapter.CanDelete(e, userId) ||
                            adapter.CanEdit(e, userId))
                        {
                            e.Access = FileShare.ReadWrite;
                        }
                        else
                        {
                            e.Access = FileShare.Read;
                        }

                        result.Add(e);
                    }
                    else if (action == FilesSecurityActions.Edit && adapter.CanEdit(e, userId))
                    {
                        e.Access = FileShare.ReadWrite;

                        result.Add(e);
                    }
                }
            }

            // files in trash
            filter = f => f.RootFolderType == FolderType.TRASH;
            if ((action == FilesSecurityActions.Read || action == FilesSecurityActions.Delete) && entries.Any(filter))
            {
                var folderDao = daoFactory.GetFolderDao <T>();
                var mytrashId = folderDao.GetFolderIDTrash(false, userId);
                if (!Equals(mytrashId, 0))
                {
                    result.AddRange(entries.Where(filter).Where(e => Equals(e.RootFolderId, mytrashId)));
                }
            }

            if (FileSecurityCommon.IsAdministrator(userId))
            {
                // administrator can work with crashed entries (crash in files_folder_tree)
                filter = f => f.RootFolderType == FolderType.DEFAULT;
                result.AddRange(entries.Where(filter));
            }

            // restore entries order
            result.Sort((x, y) => order[x.UniqID].CompareTo(order[y.UniqID]));
            return(result);
        }
示例#3
0
        private IEnumerable <FileEntry> Filter(IEnumerable <FileEntry> entries, FilesSecurityActions action, Guid userId)
        {
            if (entries == null || !entries.Any())
            {
                return(Enumerable.Empty <FileEntry>());
            }

            var user       = CoreContext.UserManager.GetUsers(userId);
            var isOutsider = user.IsOutsider();

            if (isOutsider && action != FilesSecurityActions.Read)
            {
                return(Enumerable.Empty <FileEntry>());
            }

            entries = entries.Where(f => f != null);
            var result = new List <FileEntry>(entries.Count());

            // save entries order
            var order = entries.Select((f, i) => new { Id = f.UniqID, Pos = i }).ToDictionary(e => e.Id, e => e.Pos);

            // common or my files
            Func <FileEntry, bool> filter =
                f => f.RootFolderType == FolderType.COMMON ||
                f.RootFolderType == FolderType.USER ||
                f.RootFolderType == FolderType.SHARE ||
                f.RootFolderType == FolderType.Projects;

            var isVisitor = user.IsVisitor();

            if (entries.Any(filter))
            {
                var subjects = GetUserSubjects(userId);
                List <FileShareRecord> shares = null;
                foreach (var e in entries.Where(filter))
                {
                    if (!CoreContext.Authentication.GetAccountByID(userId).IsAuthenticated&& userId != FileConstant.ShareLinkId)
                    {
                        continue;
                    }

                    if (isOutsider && (e.RootFolderType == FolderType.USER ||
                                       e.RootFolderType == FolderType.SHARE ||
                                       e.RootFolderType == FolderType.TRASH))
                    {
                        continue;
                    }

                    if (action != FilesSecurityActions.Read && e is Folder && ((Folder)e).FolderType == FolderType.Projects)
                    {
                        // Root Projects folder read-only
                        continue;
                    }

                    if (action != FilesSecurityActions.Read && e is Folder && ((Folder)e).FolderType == FolderType.SHARE)
                    {
                        // Root Share folder read-only
                        continue;
                    }

                    if (isVisitor && e.ProviderEntry)
                    {
                        continue;
                    }

                    if (e.RootFolderType == FolderType.USER && e.RootFolderCreator == userId && !isVisitor)
                    {
                        // user has all right in his folder
                        result.Add(e);
                        continue;
                    }

                    if (DefaultCommonShare == FileShare.Read && action == FilesSecurityActions.Read && e is Folder &&
                        ((Folder)e).FolderType == FolderType.COMMON)
                    {
                        // all can read Common folder
                        result.Add(e);
                        continue;
                    }

                    if (action == FilesSecurityActions.Read && e is Folder &&
                        ((Folder)e).FolderType == FolderType.SHARE)
                    {
                        // all can read Share folder
                        result.Add(e);
                        continue;
                    }

                    if (e.RootFolderType == FolderType.COMMON && IsAdministrator(userId))
                    {
                        // administrator in Common has all right
                        result.Add(e);
                        continue;
                    }

                    if (shares == null)
                    {
                        shares = GetShares(entries.ToArray()).Join(subjects, r => r.Subject, s => s, (r, s) => r).ToList();
                        // shares ordered by level
                    }

                    FileShareRecord ace;

                    if (e is File)
                    {
                        ace = shares
                              .OrderBy(r => r, new SubjectComparer(subjects))
                              .ThenByDescending(r => r.Share)
                              .FirstOrDefault(r => Equals(r.EntryId, e.ID) && r.EntryType == FileEntryType.File);
                        if (ace == null)
                        {
                            // share on parent folders
                            ace = shares.Where(r => Equals(r.EntryId, ((File)e).FolderID) && r.EntryType == FileEntryType.Folder)
                                  .OrderBy(r => r, new SubjectComparer(subjects))
                                  .ThenBy(r => r.Level)
                                  .ThenByDescending(r => r.Share)
                                  .FirstOrDefault();
                        }
                    }
                    else
                    {
                        ace = shares.Where(r => Equals(r.EntryId, e.ID) && r.EntryType == FileEntryType.Folder)
                              .OrderBy(r => r, new SubjectComparer(subjects))
                              .ThenBy(r => r.Level)
                              .ThenByDescending(r => r.Share)
                              .FirstOrDefault();
                    }
                    var defaultShare = e.RootFolderType == FolderType.USER ? DefaultMyShare : DefaultCommonShare;
                    e.Access = ace != null ? ace.Share : defaultShare;

                    if (action == FilesSecurityActions.Read && e.Access != FileShare.Restrict)
                    {
                        result.Add(e);
                    }
                    else if (action == FilesSecurityActions.Review && (e.Access == FileShare.Review || e.Access == FileShare.ReadWrite))
                    {
                        result.Add(e);
                    }
                    else if (action == FilesSecurityActions.Edit && e.Access == FileShare.ReadWrite)
                    {
                        result.Add(e);
                    }
                    else if (action == FilesSecurityActions.Create && e.Access == FileShare.ReadWrite)
                    {
                        result.Add(e);
                    }
                    else if (e.Access != FileShare.Restrict && e.CreateBy == userId && (e is File || ((Folder)e).FolderType != FolderType.COMMON))
                    {
                        result.Add(e);
                    }

                    if (e.CreateBy == userId)
                    {
                        e.Access = FileShare.None;                       //HACK: for client
                    }
                }
            }

            // files in bunch
            filter = f => f.RootFolderType == FolderType.BUNCH;
            if (entries.Any(filter))
            {
                using (var folderDao = daoFactory.GetFolderDao())
                {
                    var findedAdapters = new Dictionary <object, IFileSecurity>();
                    foreach (var e in entries.Where(filter))
                    {
                        IFileSecurity adapter = null;

                        if (!findedAdapters.ContainsKey(e.RootFolderId))
                        {
                            var root = folderDao.GetFolder(e.RootFolderId);
                            if (root != null)
                            {
                                var path = folderDao.GetBunchObjectID(root.ID);

                                adapter = FilesIntegration.GetFileSecurity(path);
                            }
                            findedAdapters[e.RootFolderId] = adapter;
                        }

                        adapter = findedAdapters[e.RootFolderId];

                        if (adapter == null)
                        {
                            continue;
                        }

                        if (adapter.CanRead(e, userId) &&
                            adapter.CanCreate(e, userId) &&
                            adapter.CanEdit(e, userId) &&
                            adapter.CanDelete(e, userId))
                        {
                            e.Access = FileShare.None;
                            result.Add(e);
                        }
                        else if (action == FilesSecurityActions.Create && adapter.CanCreate(e, userId))
                        {
                            e.Access = FileShare.ReadWrite;
                            result.Add(e);
                        }
                        else if (action == FilesSecurityActions.Delete && adapter.CanDelete(e, userId))
                        {
                            e.Access = FileShare.ReadWrite;
                            result.Add(e);
                        }
                        else if (action == FilesSecurityActions.Read && adapter.CanRead(e, userId))
                        {
                            if (adapter.CanCreate(e, userId) ||
                                adapter.CanDelete(e, userId) ||
                                adapter.CanEdit(e, userId))
                            {
                                e.Access = FileShare.ReadWrite;
                            }
                            else
                            {
                                e.Access = FileShare.Read;
                            }

                            result.Add(e);
                        }
                        else if (action == FilesSecurityActions.Edit && adapter.CanEdit(e, userId))
                        {
                            e.Access = FileShare.ReadWrite;

                            result.Add(e);
                        }
                    }
                }
            }

            // files in trash
            filter = f => f.RootFolderType == FolderType.TRASH;
            if (entries.Any(filter))
            {
                using (var folderDao = daoFactory.GetFolderDao())
                {
                    var mytrashId = folderDao.GetFolderID(FileConstant.ModuleId, "trash", userId.ToString(), false);
                    foreach (var e in entries.Where(filter))
                    {
                        // only in my trash
                        if (Equals(e.RootFolderId, mytrashId))
                        {
                            result.Add(e);
                        }
                    }
                }
            }

            if (IsAdministrator(userId))
            {
                // administrator can work with crashed entries (crash in files_folder_tree)
                filter = f => f.RootFolderType == FolderType.DEFAULT;
                result.AddRange(entries.Where(filter));
            }

            // restore entries order
            result.Sort((x, y) => order[x.UniqID].CompareTo(order[y.UniqID]));
            return(result);
        }
示例#4
0
        public MailAttachmentData AttachFileFromDocuments(int tenant, string user, int messageId, string fileId, string version, bool needSaveToTemp = false)
        {
            MailAttachmentData result;

            using (var fileDao = FilesIntegration.GetFileDao())
            {
                var file = string.IsNullOrEmpty(version)
                               ? fileDao.GetFile(fileId)
                               : fileDao.GetFile(fileId, Convert.ToInt32(version));

                if (file == null)
                {
                    throw new AttachmentsException(AttachmentsException.Types.DocumentNotFound, "File not found.");
                }

                if (!FilesIntegration.GetFileSecurity().CanRead(file))
                {
                    throw new AttachmentsException(AttachmentsException.Types.DocumentAccessDenied,
                                                   "Access denied.");
                }

                if (!fileDao.IsExistOnStorage(file))
                {
                    throw new AttachmentsException(AttachmentsException.Types.DocumentNotFound,
                                                   "File not exists on storage.");
                }

                Log.InfoFormat("Original file id: {0}", file.ID);
                Log.InfoFormat("Original file name: {0}", file.Title);
                var fileExt     = FileUtility.GetFileExtension(file.Title);
                var curFileType = FileUtility.GetFileTypeByFileName(file.Title);
                Log.InfoFormat("File converted type: {0}", file.ConvertedType);

                if (file.ConvertedType != null)
                {
                    switch (curFileType)
                    {
                    case FileType.Image:
                        fileExt = file.ConvertedType == ".zip" ? ".pptt" : file.ConvertedType;
                        break;

                    case FileType.Spreadsheet:
                        fileExt = file.ConvertedType != ".xlsx" ? ".xlst" : file.ConvertedType;
                        break;

                    default:
                        if (file.ConvertedType == ".doct" || file.ConvertedType == ".xlst" || file.ConvertedType == ".pptt")
                        {
                            fileExt = file.ConvertedType;
                        }
                        break;
                    }
                }

                var convertToExt = string.Empty;
                switch (curFileType)
                {
                case FileType.Document:
                    if (fileExt == ".doct")
                    {
                        convertToExt = ".docx";
                    }
                    break;

                case FileType.Spreadsheet:
                    if (fileExt == ".xlst")
                    {
                        convertToExt = ".xlsx";
                    }
                    break;

                case FileType.Presentation:
                    if (fileExt == ".pptt")
                    {
                        convertToExt = ".pptx";
                    }
                    break;
                }

                if (!string.IsNullOrEmpty(convertToExt) && fileExt != convertToExt)
                {
                    var fileName = Path.ChangeExtension(file.Title, convertToExt);
                    Log.InfoFormat("Changed file name - {0} for file {1}:", fileName, file.ID);

                    using (var readStream = FileConverter.Exec(file, convertToExt))
                    {
                        if (readStream == null)
                        {
                            throw new AttachmentsException(AttachmentsException.Types.DocumentAccessDenied, "Access denied.");
                        }

                        using (var memStream = new MemoryStream())
                        {
                            readStream.StreamCopyTo(memStream);
                            result = AttachFileToDraft(tenant, user, messageId, fileName, memStream, memStream.Length, null, needSaveToTemp);
                            Log.InfoFormat("Attached attachment: ID - {0}, Name - {1}, StoredUrl - {2}", result.fileName, result.fileName, result.storedFileUrl);
                        }
                    }
                }
                else
                {
                    using (var readStream = fileDao.GetFileStream(file))
                    {
                        if (readStream == null)
                        {
                            throw new AttachmentsException(AttachmentsException.Types.DocumentAccessDenied, "Access denied.");
                        }

                        result = AttachFileToDraft(tenant, user, messageId, file.Title, readStream, readStream.CanSeek ? readStream.Length : file.ContentLength, null, needSaveToTemp);
                        Log.InfoFormat("Attached attachment: ID - {0}, Name - {1}, StoredUrl - {2}", result.fileName, result.fileName, result.storedFileUrl);
                    }
                }
            }

            return(result);
        }
示例#5
0
        public MailAttachment AttachFileFromDocuments(int id_tenant, string id_user, int id_message, string id_file,
                                                      string version, string share_link, string id_stream)
        {
            MailAttachment result;

            using (var file_dao = FilesIntegration.GetFileDao())
            {
                Files.Core.File file;
                var             check_link = FileShareLink.Check(share_link, true, file_dao, out file);
                if (!check_link && file == null)
                {
                    file = String.IsNullOrEmpty(version)
                               ? file_dao.GetFile(id_file)
                               : file_dao.GetFile(id_file, Convert.ToInt32(version));
                }

                if (file == null)
                {
                    throw new AttachmentsException(AttachmentsException.Types.DOCUMENT_NOT_FOUND, "File not found.");
                }

                if (!check_link && !FilesIntegration.GetFileSecurity().CanRead(file))
                {
                    throw new AttachmentsException(AttachmentsException.Types.DOCUMENT_ACCESS_DENIED,
                                                   "Access denied.");
                }

                if (!file_dao.IsExistOnStorage(file))
                {
                    throw new AttachmentsException(AttachmentsException.Types.DOCUMENT_NOT_FOUND,
                                                   "File not exists on storage.");
                }

                var file_ext      = FileUtility.GetFileExtension(file.Title);
                var cur_file_type = FileUtility.GetFileTypeByFileName(file.Title);

                if (file.ConvertedType != null)
                {
                    if (cur_file_type == FileType.Image)
                    {
                        file_ext = file.ConvertedType == ".zip" ? ".pptt" : file.ConvertedType;
                    }
                    else if (cur_file_type == FileType.Spreadsheet)
                    {
                        file_ext = file.ConvertedType != ".xlsx" ? ".xlst" : file.ConvertedType;
                    }
                    else if (file.ConvertedType == ".doct" || file.ConvertedType == ".xlst" || file.ConvertedType == ".pptt")
                    {
                        file_ext = file.ConvertedType;
                    }
                }

                var convert_to_ext = string.Empty;
                switch (cur_file_type)
                {
                case FileType.Document:
                    if (file_ext == ".doct")
                    {
                        convert_to_ext = ".docx";
                    }
                    break;

                case FileType.Spreadsheet:
                    if (file_ext == ".xlst")
                    {
                        convert_to_ext = ".xlsx";
                    }
                    break;

                case FileType.Presentation:
                    if (file_ext == ".pptt")
                    {
                        convert_to_ext = ".pptx";
                    }
                    break;
                }

                if (!string.IsNullOrEmpty(convert_to_ext) && file_ext != convert_to_ext)
                {
                    var file_name = Path.ChangeExtension(file.Title, convert_to_ext);

                    using (var read_stream = FileConverter.Exec(file, convert_to_ext))
                    {
                        if (read_stream != null)
                        {
                            using (var mem_stream = new MemoryStream())
                            {
                                read_stream.StreamCopyTo(mem_stream);
                                result = AttachFile(id_tenant, id_user, id_message, file_name, mem_stream,
                                                    id_stream);
                            }
                        }
                        else
                        {
                            throw new AttachmentsException(AttachmentsException.Types.DOCUMENT_ACCESS_DENIED,
                                                           "Access denied.");
                        }
                    }
                }
                else
                {
                    using (var read_stream = file_dao.GetFileStream(file))
                    {
                        if (read_stream != null)
                        {
                            result = AttachFile(id_tenant, id_user, id_message, file.Title, read_stream, id_stream);
                        }
                        else
                        {
                            throw new AttachmentsException(AttachmentsException.Types.DOCUMENT_ACCESS_DENIED,
                                                           "Access denied.");
                        }
                    }
                }
            }

            return(result);
        }
        public List <SearchGroup> Search(String searchText, int projectId)
        {
            var queryResult = _searchDao.Search(searchText, projectId);

            var groups = new Dictionary <int, SearchGroup>();

            foreach (var r in queryResult)
            {
                var        projId = 0;
                SearchItem item   = null;

                if (r is Project)
                {
                    var p = (Project)r;
                    if (ProjectSecurity.CanRead(p))
                    {
                        projId = p.ID;
                        if (!groups.ContainsKey(projId))
                        {
                            groups[projId] = new SearchGroup(projId, p.Title);
                        }
                        item = new SearchItem(EntityType.Project, p.ID, p.Title, p.Description, p.CreateOn);
                    }
                }
                else
                {
                    if (r is Milestone)
                    {
                        var m = (Milestone)r;
                        if (ProjectSecurity.CanRead(m))
                        {
                            projId = m.Project.ID;
                            if (!groups.ContainsKey(projId))
                            {
                                groups[projId] = new SearchGroup(projId, m.Project.Title);
                            }
                            item = new SearchItem(EntityType.Milestone, m.ID, m.Title, null, m.CreateOn);
                        }
                    }
                    else if (r is Message)
                    {
                        var m = (Message)r;
                        if (ProjectSecurity.CanReadMessages(m.Project))
                        {
                            projId = m.Project.ID;
                            if (!groups.ContainsKey(projId))
                            {
                                groups[projId] = new SearchGroup(projId, m.Project.Title);
                            }
                            item = new SearchItem(EntityType.Message, m.ID, m.Title, m.Content, m.CreateOn);
                        }
                    }
                    else if (r is Task)
                    {
                        var t = (Task)r;
                        if (ProjectSecurity.CanRead(t))
                        {
                            projId = t.Project.ID;
                            if (!groups.ContainsKey(projId))
                            {
                                groups[projId] = new SearchGroup(projId, t.Project.Title);
                            }
                            item = new SearchItem(EntityType.Task, t.ID, t.Title, t.Description, t.CreateOn);
                        }
                    }
                }
                if (0 < projId && item != null)
                {
                    groups[projId].Items.Add(item);
                }
            }

            try
            {
                // search in files
                var fileEntries = new List <Files.Core.FileEntry>();
                using (var folderDao = FilesIntegration.GetFolderDao())
                    using (var fileDao = FilesIntegration.GetFileDao())
                    {
                        fileEntries.AddRange(folderDao.Search(searchText, Files.Core.FolderType.BUNCH).Cast <Files.Core.FileEntry>());
                        fileEntries.AddRange(fileDao.Search(searchText, Files.Core.FolderType.BUNCH).Cast <Files.Core.FileEntry>());

                        var projectIds = projectId != 0
                                         ? new List <int> {
                            projectId
                        }
                                         : fileEntries.GroupBy(f => f.RootFolderId)
                        .Select(g => folderDao.GetFolder(g.Key))
                        .Select(f => f != null ? folderDao.GetBunchObjectID(f.RootFolderId).Split('/').Last() : null)
                        .Where(s => !string.IsNullOrEmpty(s))
                        .Select(s => int.Parse(s));

                        var rootProject = projectIds.ToDictionary(id => FilesIntegration.RegisterBunch("projects", "project", id.ToString()));
                        fileEntries.RemoveAll(f => !rootProject.ContainsKey(f.RootFolderId));

                        var security = FilesIntegration.GetFileSecurity();
                        fileEntries.RemoveAll(f => !security.CanRead(f));

                        foreach (var f in fileEntries)
                        {
                            var id = rootProject[f.RootFolderId];
                            if (!groups.ContainsKey(id))
                            {
                                var project = _projDao.GetById(id);
                                if (project != null && ProjectSecurity.CanRead(project) && ProjectSecurity.CanReadFiles(project))
                                {
                                    groups[id] = new SearchGroup(id, project.Title);
                                }
                                else
                                {
                                    continue;
                                }
                            }
                            var item = new SearchItem
                            {
                                EntityType = EntityType.File,
                                ID         = f is Files.Core.File ? ((Files.Core.File)f).ViewUrl : string.Format("{0}tmdocs.aspx?prjID={1}#{2}", VirtualPathUtility.ToAbsolute("~/products/projects/"), id, f.ID),
                                Title      = f.Title,
                                CreateOn   = f.CreateOn,
                            };
                            groups[id].Items.Add(item);
                        }
                    }
            }
            catch (Exception err)
            {
                LogManager.GetLogger("ASC.Web").Error(err);
            }
            return(new List <SearchGroup>(groups.Values));
        }
示例#7
0
        public IEnumerable <SearchItem> Search(string searchText, int projectId = 0)
        {
            var queryResult = DaoFactory.SearchDao.Search(searchText, projectId);

            using (var scope = DIHelper.Resolve())
            {
                var projectSecurity = scope.Resolve <ProjectSecurity>();

                foreach (var r in queryResult)
                {
                    switch (r.EntityType)
                    {
                    case EntityType.Project:
                        var project = (Project)r;
                        if (projectSecurity.CanRead(project))
                        {
                            searchItems.Add(new SearchItem(project));
                        }
                        continue;

                    case EntityType.Milestone:
                        var milestone = (Milestone)r;
                        if (projectSecurity.CanRead(milestone))
                        {
                            searchItems.Add(new SearchItem(milestone));
                        }
                        continue;

                    case EntityType.Message:
                        var message = (Message)r;
                        if (projectSecurity.CanRead(message))
                        {
                            searchItems.Add(new SearchItem(message));
                        }
                        continue;

                    case EntityType.Task:
                        var task = (Task)r;
                        if (projectSecurity.CanRead(task))
                        {
                            searchItems.Add(new SearchItem(task));
                        }
                        continue;

                    case EntityType.Comment:
                        var comment = (Comment)r;
                        var entity  = CommentEngine.GetEntityByTargetUniqId(comment);
                        if (entity == null)
                        {
                            continue;
                        }

                        searchItems.Add(new SearchItem(comment.EntityType,
                                                       comment.ID.ToString(CultureInfo.InvariantCulture), HtmlUtil.GetText(comment.Content),
                                                       comment.CreateOn, new SearchItem(entity)));
                        continue;

                    case EntityType.SubTask:
                        var subtask    = (Subtask)r;
                        var parentTask = TaskEngine.GetByID(subtask.Task);
                        if (parentTask == null)
                        {
                            continue;
                        }

                        searchItems.Add(new SearchItem(subtask.EntityType,
                                                       subtask.ID.ToString(CultureInfo.InvariantCulture), subtask.Title, subtask.CreateOn,
                                                       new SearchItem(parentTask)));
                        continue;
                    }
                }
            }

            try
            {
                // search in files
                var fileEntries = new List <FileEntry>();
                using (var folderDao = FilesIntegration.GetFolderDao())
                    using (var fileDao = FilesIntegration.GetFileDao())
                    {
                        fileEntries.AddRange(folderDao.Search(searchText, true));
                        fileEntries.AddRange(fileDao.Search(searchText, true));

                        var projectIds = projectId != 0
                                         ? new List <int> {
                            projectId
                        }
                                         : fileEntries.GroupBy(f => f.RootFolderId)
                        .Select(g => folderDao.GetFolder(g.Key))
                        .Select(f => f != null ? folderDao.GetBunchObjectID(f.RootFolderId).Split('/').Last() : null)
                        .Where(s => !string.IsNullOrEmpty(s))
                        .Select(int.Parse);

                        var rootProject = projectIds.ToDictionary(id => FilesIntegration.RegisterBunch("projects", "project", id.ToString(CultureInfo.InvariantCulture)));
                        fileEntries.RemoveAll(f => !rootProject.ContainsKey(f.RootFolderId));

                        var security = FilesIntegration.GetFileSecurity();
                        fileEntries.RemoveAll(f => !security.CanRead(f));

                        foreach (var f in fileEntries)
                        {
                            var id      = rootProject[f.RootFolderId];
                            var project = DaoFactory.ProjectDao.GetById(id);

                            if (ProjectSecurity.CanReadFiles(project))
                            {
                                var itemId = f.FileEntryType == FileEntryType.File
                                             ? FilesLinkUtility.GetFileWebPreviewUrl(f.Title, f.ID)
                                             : Web.Files.Classes.PathProvider.GetFolderUrl((Folder)f, project.ID);
                                searchItems.Add(new SearchItem(EntityType.File, itemId, f.Title, f.CreateOn, new SearchItem(project), itemPath: "{2}"));
                            }
                        }
                    }
            }
            catch (Exception err)
            {
                LogManager.GetLogger("ASC").Error(err);
            }
            return(searchItems);
        }