Esempio n. 1
0
        public File ExecSync(File file, string doc)
        {
            var fileDao      = DaoFactory.FileDao;
            var fileSecurity = FileSecurity;

            if (!fileSecurity.CanRead(file))
            {
                var readLink = FileShareLink.Check(doc, true, fileDao, out file);
                if (file == null)
                {
                    throw new ArgumentNullException("file", FilesCommonResource.ErrorMassage_FileNotFound);
                }
                if (!readLink)
                {
                    throw new SecurityException(FilesCommonResource.ErrorMassage_SecurityException_ReadFile);
                }
            }

            var fileUri       = PathProvider.GetFileStreamUrl(file);
            var fileExtension = file.ConvertedExtension;
            var toExtension   = FileUtility.GetInternalExtension(file.Title);
            var docKey        = DocumentServiceHelper.GetDocKey(file);

            fileUri = DocumentServiceConnector.ReplaceCommunityAdress(fileUri);
            DocumentServiceConnector.GetConvertedUri(fileUri, fileExtension, toExtension, docKey, null, false, out var convertUri);

            return(SaveConvertedFile(file, convertUri));
        }
Esempio n. 2
0
 public FileConverter(
     FileUtility fileUtility,
     FilesLinkUtility filesLinkUtility,
     IDaoFactory daoFactory,
     SetupInfo setupInfo,
     PathProvider pathProvider,
     FileSecurity fileSecurity,
     FileMarker fileMarker,
     TenantManager tenantManager,
     AuthContext authContext,
     EntryManager entryManager,
     IOptionsMonitor <ILog> options,
     FilesSettingsHelper filesSettingsHelper,
     GlobalFolderHelper globalFolderHelper,
     FilesMessageService filesMessageService,
     FileShareLink fileShareLink,
     DocumentServiceHelper documentServiceHelper,
     DocumentServiceConnector documentServiceConnector,
     IServiceProvider serviceProvider,
     IHttpContextAccessor httpContextAccesor)
     : this(fileUtility, filesLinkUtility, daoFactory, setupInfo, pathProvider, fileSecurity,
            fileMarker, tenantManager, authContext, entryManager, options, filesSettingsHelper,
            globalFolderHelper, filesMessageService, fileShareLink, documentServiceHelper, documentServiceConnector,
            serviceProvider)
 {
     HttpContextAccesor = httpContextAccesor;
 }
        public static void TrackEditing(string fileId, Guid tabId, Guid userId, string doc, bool editingAlone = false)
        {
            bool checkRight;

            if (FileTracker.GetEditingBy(fileId).Contains(userId))
            {
                checkRight = FileTracker.ProlongEditing(fileId, tabId, userId, editingAlone);
                if (!checkRight)
                {
                    return;
                }
            }

            File file;
            bool editLink;

            using (var fileDao = Global.DaoFactory.GetFileDao())
            {
                editLink = FileShareLink.Check(doc, false, fileDao, out file);
                if (file == null)
                {
                    file = fileDao.GetFile(fileId);
                }
            }

            if (file == null)
            {
                throw new FileNotFoundException(FilesCommonResource.ErrorMassage_FileNotFound);
            }
            var fileSecurity = Global.GetFilesSecurity();

            if (!editLink && (!fileSecurity.CanEdit(file, userId) && !fileSecurity.CanReview(file, userId) && !fileSecurity.CanFillForms(file, userId) && !fileSecurity.CanComment(file, userId) || CoreContext.UserManager.GetUsers(userId).IsVisitor()))
            {
                throw new SecurityException(FilesCommonResource.ErrorMassage_SecurityException_EditFile);
            }
            if (FileLockedForMe(file.ID, userId))
            {
                throw new Exception(FilesCommonResource.ErrorMassage_LockedFile);
            }
            if (file.RootFolderType == FolderType.TRASH)
            {
                throw new Exception(FilesCommonResource.ErrorMassage_ViewTrashItem);
            }

            checkRight = FileTracker.ProlongEditing(fileId, tabId, userId, editingAlone);
            if (checkRight)
            {
                FileTracker.ChangeRight(fileId, userId, false);
            }
        }
Esempio n. 4
0
 public FileConverter(
     FileUtility fileUtility,
     FilesLinkUtility filesLinkUtility,
     IDaoFactory daoFactory,
     SetupInfo setupInfo,
     PathProvider pathProvider,
     FileSecurity fileSecurity,
     FileMarker fileMarker,
     TenantManager tenantManager,
     AuthContext authContext,
     EntryManager entryManager,
     FilesSettingsHelper filesSettingsHelper,
     GlobalFolderHelper globalFolderHelper,
     FilesMessageService filesMessageService,
     FileShareLink fileShareLink,
     DocumentServiceHelper documentServiceHelper,
     DocumentServiceConnector documentServiceConnector,
     FileTrackerHelper fileTracker,
     BaseCommonLinkUtility baseCommonLinkUtility,
     EntryStatusManager entryStatusManager,
     IServiceProvider serviceProvider)
 {
     FileUtility              = fileUtility;
     FilesLinkUtility         = filesLinkUtility;
     DaoFactory               = daoFactory;
     SetupInfo                = setupInfo;
     PathProvider             = pathProvider;
     FileSecurity             = fileSecurity;
     FileMarker               = fileMarker;
     TenantManager            = tenantManager;
     AuthContext              = authContext;
     EntryManager             = entryManager;
     FilesSettingsHelper      = filesSettingsHelper;
     GlobalFolderHelper       = globalFolderHelper;
     FilesMessageService      = filesMessageService;
     FileShareLink            = fileShareLink;
     DocumentServiceHelper    = documentServiceHelper;
     DocumentServiceConnector = documentServiceConnector;
     FileTracker              = fileTracker;
     BaseCommonLinkUtility    = baseCommonLinkUtility;
     EntryStatusManager       = entryStatusManager;
     ServiceProvider          = serviceProvider;
 }
Esempio n. 5
0
 public FileSharing(
     Global global,
     FileSecurity fileSecurity,
     AuthContext authContext,
     UserManager userManager,
     IOptionsMonitor <ILog> optionsMonitor,
     DisplayUserSettingsHelper displayUserSettingsHelper,
     FileShareLink fileShareLink,
     IDaoFactory daoFactory,
     FileSharingHelper fileSharingHelper)
 {
     Global       = global;
     FileSecurity = fileSecurity;
     AuthContext  = authContext;
     UserManager  = userManager;
     DisplayUserSettingsHelper = displayUserSettingsHelper;
     FileShareLink             = fileShareLink;
     DaoFactory        = daoFactory;
     FileSharingHelper = fileSharingHelper;
     Logger            = optionsMonitor.CurrentValue;
 }
Esempio n. 6
0
 public FileConverter(
     FileUtility fileUtility,
     FilesLinkUtility filesLinkUtility,
     IDaoFactory daoFactory,
     SetupInfo setupInfo,
     PathProvider pathProvider,
     FileSecurity fileSecurity,
     FileMarker fileMarker,
     TenantManager tenantManager,
     AuthContext authContext,
     EntryManager entryManager,
     IOptionsMonitor <ILog> options,
     FilesSettingsHelper filesSettingsHelper,
     GlobalFolderHelper globalFolderHelper,
     FilesMessageService filesMessageService,
     FileShareLink fileShareLink,
     DocumentServiceHelper documentServiceHelper,
     DocumentServiceConnector documentServiceConnector,
     IServiceProvider serviceProvider)
 {
     FileUtility              = fileUtility;
     FilesLinkUtility         = filesLinkUtility;
     DaoFactory               = daoFactory;
     SetupInfo                = setupInfo;
     PathProvider             = pathProvider;
     FileSecurity             = fileSecurity;
     FileMarker               = fileMarker;
     TenantManager            = tenantManager;
     AuthContext              = authContext;
     EntryManager             = entryManager;
     FilesSettingsHelper      = filesSettingsHelper;
     GlobalFolderHelper       = globalFolderHelper;
     FilesMessageService      = filesMessageService;
     FileShareLink            = fileShareLink;
     DocumentServiceHelper    = documentServiceHelper;
     DocumentServiceConnector = documentServiceConnector;
     ServiceProvider          = serviceProvider;
     Logger = options.CurrentValue;
     cache  = AscCache.Memory;
 }
        public static List <AceWrapper> GetSharedInfo(FileEntry entry)
        {
            if (entry == null)
            {
                throw new ArgumentNullException(FilesCommonResource.ErrorMassage_BadRequest);
            }
            if (!CanSetAccess(entry))
            {
                LogManager.GetLogger("ASC.Web.Files").ErrorFormat("User {0} can't get shared info for {1} {2}", SecurityContext.CurrentAccount.ID, (entry is File ? "file" : "folder"), entry.ID);
                throw new SecurityException(FilesCommonResource.ErrorMassage_SecurityException);
            }

            var linkAccess = FileShare.Restrict;
            var result     = new List <AceWrapper>();

            var fileSecurity = Global.GetFilesSecurity();

            var records = fileSecurity
                          .GetShares(entry)
                          .GroupBy(r => r.Subject)
                          .Select(g => g.OrderBy(r => r.Level)
                                  .ThenBy(r => r.Level)
                                  .ThenByDescending(r => r.Share).FirstOrDefault());

            foreach (var r in records)
            {
                if (r.Subject == FileConstant.ShareLinkId)
                {
                    linkAccess = r.Share;
                    continue;
                }

                var u       = CoreContext.UserManager.GetUsers(r.Subject);
                var isgroup = false;
                var title   = u.DisplayUserName(false);

                if (u.ID == Constants.LostUser.ID)
                {
                    var g = CoreContext.GroupManager.GetGroupInfo(r.Subject);
                    isgroup = true;
                    title   = g.Name;

                    if (g.ID == Constants.GroupAdmin.ID)
                    {
                        title = FilesCommonResource.Admin;
                    }
                    if (g.ID == Constants.GroupEveryone.ID)
                    {
                        title = FilesCommonResource.Everyone;
                    }

                    if (g.ID == Constants.LostGroupInfo.ID)
                    {
                        fileSecurity.RemoveSubject(r.Subject);
                        continue;
                    }
                }

                var w = new AceWrapper
                {
                    SubjectId    = r.Subject,
                    SubjectName  = title,
                    SubjectGroup = isgroup,
                    Share        = r.Share,
                    Owner        =
                        entry.RootFolderType == FolderType.USER
                                ? entry.RootFolderCreator == r.Subject
                                : entry.CreateBy == r.Subject,
                    LockedRights = r.Subject == SecurityContext.CurrentAccount.ID
                };
                result.Add(w);
            }

            if (entry is File && result.All(w => w.SubjectId != FileConstant.ShareLinkId))
            {
                var w = new AceWrapper
                {
                    SubjectId    = FileConstant.ShareLinkId,
                    SubjectName  = FileShareLink.GetLink((File)entry),
                    SubjectGroup = true,
                    Share        = linkAccess,
                    Owner        = false
                };
                result.Add(w);
            }

            if (!result.Any(w => w.Owner))
            {
                var ownerId = entry.RootFolderType == FolderType.USER ? entry.RootFolderCreator : entry.CreateBy;
                var w       = new AceWrapper
                {
                    SubjectId    = ownerId,
                    SubjectName  = Global.GetUserName(ownerId),
                    SubjectGroup = false,
                    Share        = FileShare.ReadWrite,
                    Owner        = true
                };
                result.Add(w);
            }

            if (result.Any(w => w.SubjectId == SecurityContext.CurrentAccount.ID))
            {
                result.Single(w => w.SubjectId == SecurityContext.CurrentAccount.ID).LockedRights =
                    true;
            }

            if (entry.RootFolderType == FolderType.COMMON)
            {
                if (result.All(w => w.SubjectId != Constants.GroupAdmin.ID))
                {
                    var w = new AceWrapper
                    {
                        SubjectId    = Constants.GroupAdmin.ID,
                        SubjectName  = FilesCommonResource.Admin,
                        SubjectGroup = true,
                        Share        = FileShare.ReadWrite,
                        Owner        = false,
                        LockedRights = true,
                    };
                    result.Add(w);
                }
                if (result.All(w => w.SubjectId != Constants.GroupEveryone.ID))
                {
                    var w = new AceWrapper
                    {
                        SubjectId     = Constants.GroupEveryone.ID,
                        SubjectName   = FilesCommonResource.Everyone,
                        SubjectGroup  = true,
                        Share         = fileSecurity.DefaultCommonShare,
                        Owner         = false,
                        DisableRemove = true
                    };
                    result.Add(w);
                }
            }

            return(result);
        }
Esempio n. 8
0
        public static List <AceWrapper> GetSharedInfo(FileEntry entry)
        {
            if (entry == null)
            {
                throw new ArgumentNullException(FilesCommonResource.ErrorMassage_BadRequest);
            }
            if (!CanSetAccess(entry))
            {
                Global.Logger.ErrorFormat("User {0} can't get shared info for {1} {2}", SecurityContext.CurrentAccount.ID, (entry.FileEntryType == FileEntryType.File ? "file" : "folder"), entry.ID);
                throw new SecurityException(FilesCommonResource.ErrorMassage_SecurityException);
            }

            var linkAccess = FileShare.Restrict;
            var result     = new List <AceWrapper>();

            var fileSecurity = Global.GetFilesSecurity();

            var records = fileSecurity
                          .GetShares(entry)
                          .GroupBy(r => r.Subject)
                          .Select(g => g.OrderBy(r => r.Level)
                                  .ThenBy(r => r.Level)
                                  .ThenByDescending(r => r.Share, new FileShareRecord.ShareComparer()).FirstOrDefault());

            foreach (var r in records)
            {
                if (r.Subject == FileConstant.ShareLinkId)
                {
                    linkAccess = r.Share;
                    continue;
                }

                if (r.Subject == FileConstant.DenyDownloadId || r.Subject == FileConstant.DenySharingId)
                {
                    continue;
                }

                var u       = CoreContext.UserManager.GetUsers(r.Subject);
                var isgroup = false;
                var title   = u.DisplayUserName(false);
                var share   = r.Share;

                if (u.ID == Constants.LostUser.ID)
                {
                    var g = CoreContext.UserManager.GetGroupInfo(r.Subject);
                    isgroup = true;
                    title   = g.Name;

                    if (g.ID == Constants.GroupAdmin.ID)
                    {
                        title = FilesCommonResource.Admin;
                    }
                    if (g.ID == Constants.GroupEveryone.ID)
                    {
                        title = FilesCommonResource.Everyone;
                    }

                    if (g.ID == Constants.LostGroupInfo.ID)
                    {
                        fileSecurity.RemoveSubject(r.Subject);
                        continue;
                    }
                }
                else if (u.IsVisitor() &&
                         new FileShareRecord.ShareComparer().Compare(FileShare.Read, share) > 0)
                {
                    share = FileShare.Read;
                }

                var w = new AceWrapper
                {
                    SubjectId    = r.Subject,
                    SubjectName  = title,
                    SubjectGroup = isgroup,
                    Share        = share,
                    Owner        =
                        entry.RootFolderType == FolderType.USER
                                ? entry.RootFolderCreator == r.Subject
                                : entry.CreateBy == r.Subject,
                    LockedRights = r.Subject == SecurityContext.CurrentAccount.ID
                };
                result.Add(w);
            }

            if (entry.FileEntryType == FileEntryType.File &&
                !((File)entry).Encrypted &&
                result.All(w => w.SubjectId != FileConstant.ShareLinkId) &&
                (linkAccess != FileShare.Restrict || CoreContext.Configuration.Standalone || !TenantExtra.GetTenantQuota().Trial || FileUtility.CanWebView(entry.Title)))
            {
                var w = new AceWrapper
                {
                    SubjectId    = FileConstant.ShareLinkId,
                    Link         = FilesSettings.ExternalShare ? FileShareLink.GetLink((File)entry) : string.Empty,
                    SubjectGroup = true,
                    Share        = linkAccess,
                    Owner        = false
                };
                result.Add(w);
            }

            if (!result.Any(w => w.Owner))
            {
                var ownerId = entry.RootFolderType == FolderType.USER ? entry.RootFolderCreator : entry.CreateBy;
                var w       = new AceWrapper
                {
                    SubjectId    = ownerId,
                    SubjectName  = Global.GetUserName(ownerId),
                    SubjectGroup = false,
                    Share        = FileShare.ReadWrite,
                    Owner        = true
                };
                result.Add(w);
            }

            if (result.Any(w => w.SubjectId == SecurityContext.CurrentAccount.ID))
            {
                result.Single(w => w.SubjectId == SecurityContext.CurrentAccount.ID).LockedRights = true;
            }

            if (entry.RootFolderType == FolderType.COMMON)
            {
                if (result.All(w => w.SubjectId != Constants.GroupAdmin.ID))
                {
                    var w = new AceWrapper
                    {
                        SubjectId    = Constants.GroupAdmin.ID,
                        SubjectName  = FilesCommonResource.Admin,
                        SubjectGroup = true,
                        Share        = FileShare.ReadWrite,
                        Owner        = false,
                        LockedRights = true,
                    };
                    result.Add(w);
                }
                var index = result.FindIndex(w => w.SubjectId == Constants.GroupEveryone.ID);
                if (index == -1)
                {
                    var w = new AceWrapper
                    {
                        SubjectId     = Constants.GroupEveryone.ID,
                        SubjectName   = FilesCommonResource.Everyone,
                        SubjectGroup  = true,
                        Share         = fileSecurity.DefaultCommonShare,
                        Owner         = false,
                        DisableRemove = true
                    };
                    result.Add(w);
                }
                else
                {
                    result[index].DisableRemove = true;
                }
            }

            return(result);
        }
        public static File ExecDuplicate(File file, string shareLinkKey)
        {
            var toFolderId = file.FolderID;

            using (var fileDao = Global.DaoFactory.GetFileDao())
                using (var folderDao = Global.DaoFactory.GetFolderDao())
                {
                    if (!Global.GetFilesSecurity().CanRead(file))
                    {
                        var readLink = FileShareLink.Check(shareLinkKey, true, fileDao, out file);

                        if (file == null)
                        {
                            throw new ArgumentNullException("file", FilesCommonResource.ErrorMassage_FileNotFound);
                        }
                        if (!readLink)
                        {
                            throw new SecurityException(FilesCommonResource.ErrorMassage_SecurityException_ReadFile);
                        }
                        toFolderId = Global.FolderMy;
                    }

                    if (Global.EnableUploadFilter && !FileUtility.ExtsUploadable.Contains(FileUtility.GetFileExtension(file.Title)))
                    {
                        throw new Exception(FilesCommonResource.ErrorMassage_NotSupportedFormat);
                    }

                    var toFolder = folderDao.GetFolder(toFolderId);
                    if (toFolder == null)
                    {
                        throw new DirectoryNotFoundException(FilesCommonResource.ErrorMassage_FolderNotFound);
                    }
                    if (!Global.GetFilesSecurity().CanCreate(toFolder))
                    {
                        throw new SecurityException(FilesCommonResource.ErrorMassage_SecurityException_Create);
                    }

                    var    fileUri       = PathProvider.GetFileStreamUrl(file);
                    var    fileExtension = file.ConvertedExtension;
                    var    toExtension   = FileUtility.GetInternalExtension(file.Title);
                    var    docKey        = DocumentServiceHelper.GetDocKey(file.ID, file.Version, file.ModifiedOn);
                    string convertUri;
                    DocumentServiceConnector.GetConvertedUri(fileUri, fileExtension, toExtension, docKey, false, out convertUri);

                    var newFile = new File
                    {
                        FolderID = toFolder.ID,
                        Title    = FileUtility.ReplaceFileExtension(file.Title, toExtension)
                    };

                    var req = (HttpWebRequest)WebRequest.Create(convertUri);
                    using (var editedFileStream = new ResponseStream(req.GetResponse()))
                    {
                        newFile.ContentLength = editedFileStream.Length;

                        newFile = fileDao.SaveFile(newFile, editedFileStream);
                    }

                    FileMarker.MarkAsNew(newFile);
                    return(newFile);
                }
        }
        public static File UpdateToVersionFile(object fileId, int version, String doc = null, bool checkRight = true)
        {
            using (var fileDao = Global.DaoFactory.GetFileDao())
            {
                if (version < 1)
                {
                    throw new ArgumentNullException("version");
                }

                File fromFile;
                var  editLink = FileShareLink.Check(doc, false, fileDao, out fromFile);

                if (fromFile == null)
                {
                    fromFile = fileDao.GetFile(fileId);
                }

                if (fromFile == null)
                {
                    throw new FileNotFoundException(FilesCommonResource.ErrorMassage_FileNotFound);
                }

                if (fromFile.Version != version)
                {
                    fromFile = fileDao.GetFile(fromFile.ID, Math.Min(fromFile.Version, version));
                }

                if (fromFile == null)
                {
                    throw new FileNotFoundException(FilesCommonResource.ErrorMassage_FileNotFound);
                }
                if (checkRight && !editLink && (!Global.GetFilesSecurity().CanEdit(fromFile) || CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID).IsVisitor()))
                {
                    throw new SecurityException(FilesCommonResource.ErrorMassage_SecurityException_EditFile);
                }
                if (FileLockedForMe(fromFile.ID))
                {
                    throw new Exception(FilesCommonResource.ErrorMassage_LockedFile);
                }
                if (checkRight && FileTracker.IsEditing(fromFile.ID))
                {
                    throw new Exception(FilesCommonResource.ErrorMassage_SecurityException_UpdateEditingFile);
                }
                if (fromFile.RootFolderType == FolderType.TRASH)
                {
                    throw new Exception(FilesCommonResource.ErrorMassage_ViewTrashItem);
                }
                if (fromFile.ProviderEntry)
                {
                    throw new Exception(FilesCommonResource.ErrorMassage_BadRequest);
                }

                var exists = cache.Get <string>(UPDATE_LIST + fileId.ToString()) != null;
                if (exists)
                {
                    throw new Exception(FilesCommonResource.ErrorMassage_UpdateEditingFile);
                }
                else
                {
                    cache.Insert(UPDATE_LIST + fileId.ToString(), fileId.ToString(), TimeSpan.FromMinutes(2));
                }

                try
                {
                    var currFile = fileDao.GetFile(fileId);
                    var newFile  = new File
                    {
                        ID            = fromFile.ID,
                        Version       = currFile.Version + 1,
                        VersionGroup  = currFile.VersionGroup,
                        Title         = FileUtility.ReplaceFileExtension(currFile.Title, FileUtility.GetFileExtension(fromFile.Title)),
                        FileStatus    = currFile.FileStatus,
                        FolderID      = currFile.FolderID,
                        CreateBy      = currFile.CreateBy,
                        CreateOn      = currFile.CreateOn,
                        ModifiedBy    = fromFile.ModifiedBy,
                        ModifiedOn    = fromFile.ModifiedOn,
                        ConvertedType = fromFile.ConvertedType,
                        Comment       = string.Format(FilesCommonResource.CommentRevert, fromFile.ModifiedOnString),
                        Encrypted     = fromFile.Encrypted,
                    };

                    using (var stream = fileDao.GetFileStream(fromFile))
                    {
                        newFile.ContentLength = stream.CanSeek ? stream.Length : fromFile.ContentLength;
                        newFile = fileDao.SaveFile(newFile, stream);
                    }

                    FileMarker.MarkAsNew(newFile);

                    SetFileStatus(newFile);

                    return(newFile);
                }
                catch (Exception e)
                {
                    Global.Logger.Error(string.Format("Error on update {0} to version {1}", fileId, version), e);
                    throw new Exception(e.Message, e);
                }
                finally
                {
                    cache.Remove(UPDATE_LIST + fromFile.ID);
                }
            }
        }
        public static File SaveEditing(String fileId, string fileExtension, string downloadUri, Stream stream, String doc, string comment = null, bool checkRight = true, bool encrypted = false, ForcesaveType?forcesave = null)
        {
            var newExtension = string.IsNullOrEmpty(fileExtension)
                              ? FileUtility.GetFileExtension(downloadUri)
                              : fileExtension;

            var app = ThirdPartySelector.GetAppByFileId(fileId);

            if (app != null)
            {
                app.SaveFile(fileId, newExtension, downloadUri, stream);
                return(null);
            }

            File file;

            using (var fileDao = Global.DaoFactory.GetFileDao())
            {
                var editLink = FileShareLink.Check(doc, false, fileDao, out file);
                if (file == null)
                {
                    file = fileDao.GetFile(fileId);
                }

                if (file == null)
                {
                    throw new FileNotFoundException(FilesCommonResource.ErrorMassage_FileNotFound);
                }
                var fileSecurity = Global.GetFilesSecurity();
                if (checkRight && !editLink && (!(fileSecurity.CanEdit(file) || fileSecurity.CanReview(file)) || CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID).IsVisitor()))
                {
                    throw new SecurityException(FilesCommonResource.ErrorMassage_SecurityException_EditFile);
                }
                if (checkRight && FileLockedForMe(file.ID))
                {
                    throw new Exception(FilesCommonResource.ErrorMassage_LockedFile);
                }
                if (checkRight && FileTracker.IsEditing(file.ID))
                {
                    throw new Exception(FilesCommonResource.ErrorMassage_SecurityException_UpdateEditingFile);
                }
                if (file.RootFolderType == FolderType.TRASH)
                {
                    throw new Exception(FilesCommonResource.ErrorMassage_ViewTrashItem);
                }

                var currentExt = file.ConvertedExtension;
                if (string.IsNullOrEmpty(newExtension))
                {
                    newExtension = FileUtility.GetInternalExtension(file.Title);
                }

                var replaceVersion = false;
                if (file.Forcesave != ForcesaveType.None)
                {
                    if (file.Forcesave == ForcesaveType.User && FilesSettings.StoreForcesave)
                    {
                        file.Version++;
                    }
                    else
                    {
                        replaceVersion = true;
                    }
                }
                else
                {
                    if (file.Version != 1)
                    {
                        file.VersionGroup++;
                    }
                    else
                    {
                        var storeTemplate = Global.GetStoreTemplate();

                        var path = FileConstant.NewDocPath + Thread.CurrentThread.CurrentCulture + "/";
                        if (!storeTemplate.IsDirectory(path))
                        {
                            path = FileConstant.NewDocPath + "default/";
                        }
                        path += "new" + FileUtility.GetInternalExtension(file.Title);

                        //todo: think about the criteria for saving after creation
                        if (file.ContentLength != storeTemplate.GetFileSize("", path))
                        {
                            file.VersionGroup++;
                        }
                    }
                    file.Version++;
                }
                file.Forcesave = forcesave.HasValue ? forcesave.Value : ForcesaveType.None;

                if (string.IsNullOrEmpty(comment))
                {
                    comment = FilesCommonResource.CommentEdit;
                }

                file.Encrypted = encrypted;

                file.ConvertedType = FileUtility.GetFileExtension(file.Title) != newExtension ? newExtension : null;

                if (file.ProviderEntry && !newExtension.Equals(currentExt))
                {
                    if (FileUtility.ExtsConvertible.Keys.Contains(newExtension) &&
                        FileUtility.ExtsConvertible[newExtension].Contains(currentExt))
                    {
                        if (stream != null)
                        {
                            downloadUri = PathProvider.GetTempUrl(stream, newExtension);
                            downloadUri = DocumentServiceConnector.ReplaceCommunityAdress(downloadUri);
                        }

                        var key = DocumentServiceConnector.GenerateRevisionId(downloadUri);
                        DocumentServiceConnector.GetConvertedUri(downloadUri, newExtension, currentExt, key, null, false, out downloadUri);

                        stream = null;
                    }
                    else
                    {
                        file.ID    = null;
                        file.Title = FileUtility.ReplaceFileExtension(file.Title, newExtension);
                    }

                    file.ConvertedType = null;
                }

                using (var tmpStream = new MemoryStream())
                {
                    if (stream != null)
                    {
                        stream.CopyTo(tmpStream);
                    }
                    else
                    {
                        // hack. http://ubuntuforums.org/showthread.php?t=1841740
                        if (WorkContext.IsMono)
                        {
                            ServicePointManager.ServerCertificateValidationCallback += (s, ce, ca, p) => true;
                        }

                        var req = (HttpWebRequest)WebRequest.Create(downloadUri);
                        using (var editedFileStream = new ResponseStream(req.GetResponse()))
                        {
                            editedFileStream.CopyTo(tmpStream);
                        }
                    }
                    tmpStream.Position = 0;

                    file.ContentLength = tmpStream.Length;
                    file.Comment       = string.IsNullOrEmpty(comment) ? null : comment;
                    if (replaceVersion)
                    {
                        file = fileDao.ReplaceFileVersion(file, tmpStream);
                    }
                    else
                    {
                        file = fileDao.SaveFile(file, tmpStream);
                    }
                }
            }

            FileMarker.MarkAsNew(file);
            FileMarker.RemoveMarkAsNew(file);
            return(file);
        }
Esempio n. 12
0
        public static File ExecDuplicate(File file, string doc)
        {
            var toFolderId = file.FolderID;

            using (var fileDao = Global.DaoFactory.GetFileDao())
                using (var folderDao = Global.DaoFactory.GetFolderDao())
                {
                    var fileSecurity = Global.GetFilesSecurity();
                    if (!fileSecurity.CanRead(file))
                    {
                        var readLink = FileShareLink.Check(doc, true, fileDao, out file);
                        if (file == null)
                        {
                            throw new ArgumentNullException("file", FilesCommonResource.ErrorMassage_FileNotFound);
                        }
                        if (!readLink)
                        {
                            throw new SecurityException(FilesCommonResource.ErrorMassage_SecurityException_ReadFile);
                        }
                        toFolderId = Global.FolderMy;
                    }
                    if (Global.EnableUploadFilter && !FileUtility.ExtsUploadable.Contains(FileUtility.GetFileExtension(file.Title)))
                    {
                        throw new Exception(FilesCommonResource.ErrorMassage_NotSupportedFormat);
                    }
                    var toFolder = folderDao.GetFolder(toFolderId);
                    if (toFolder == null)
                    {
                        throw new DirectoryNotFoundException(FilesCommonResource.ErrorMassage_FolderNotFound);
                    }
                    if (!fileSecurity.CanCreate(toFolder))
                    {
                        throw new SecurityException(FilesCommonResource.ErrorMassage_SecurityException_Create);
                    }

                    var fileUri       = PathProvider.GetFileStreamUrl(file);
                    var fileExtension = file.ConvertedExtension;
                    var toExtension   = FileUtility.GetInternalExtension(file.Title);
                    var docKey        = DocumentServiceHelper.GetDocKey(file);

                    string convertUri;
                    fileUri = DocumentServiceConnector.ReplaceCommunityAdress(fileUri);
                    DocumentServiceConnector.GetConvertedUri(fileUri, fileExtension, toExtension, docKey, false, out convertUri);

                    var newFile = new File
                    {
                        FolderID = toFolder.ID,
                        Title    = FileUtility.ReplaceFileExtension(file.Title, toExtension),
                        Comment  = string.Format(FilesCommonResource.CommentConvert, file.Title),
                    };

                    var req = (HttpWebRequest)WebRequest.Create(convertUri);

                    // hack. http://ubuntuforums.org/showthread.php?t=1841740
                    if (WorkContext.IsMono)
                    {
                        ServicePointManager.ServerCertificateValidationCallback += (s, ce, ca, p) => true;
                    }

                    using (var editedFileStream = new ResponseStream(req.GetResponse()))
                    {
                        newFile.ContentLength = editedFileStream.Length;
                        newFile = fileDao.SaveFile(newFile, editedFileStream);
                    }

                    FileMarker.MarkAsNew(newFile);
                    return(newFile);
                }
        }
Esempio n. 13
0
        public static File SaveEditing(String fileId, int version, Guid tabId, string fileExtension, string downloadUri, Stream stream, bool asNew, String shareLinkKey, string comment = null, bool checkRight = true)
        {
            var newExtension = string.IsNullOrEmpty(fileExtension)
                              ? FileUtility.GetFileExtension(downloadUri)
                              : fileExtension;

            var app = ThirdPartySelector.GetAppByFileId(fileId);

            if (app != null)
            {
                app.SaveFile(fileId, newExtension, downloadUri, stream);
                return(null);
            }

            File file;

            using (var fileDao = Global.DaoFactory.GetFileDao())
            {
                var editLink = FileShareLink.Check(shareLinkKey, false, fileDao, out file);
                if (file == null)
                {
                    file = fileDao.GetFile(fileId);
                }

                if (file == null)
                {
                    throw new FileNotFoundException(FilesCommonResource.ErrorMassage_FileNotFound);
                }
                var fileSecurity = Global.GetFilesSecurity();
                if (checkRight && !editLink && (!(fileSecurity.CanEdit(file) || fileSecurity.CanReview(file)) || CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID).IsVisitor()))
                {
                    throw new SecurityException(FilesCommonResource.ErrorMassage_SecurityException_EditFile);
                }
                if (checkRight && FileLockedForMe(file.ID))
                {
                    throw new Exception(FilesCommonResource.ErrorMassage_LockedFile);
                }
                if (file.RootFolderType == FolderType.TRASH)
                {
                    throw new Exception(FilesCommonResource.ErrorMassage_ViewTrashItem);
                }

                var currentExt = file.ConvertedExtension;
                if (string.IsNullOrEmpty(newExtension))
                {
                    newExtension = FileUtility.GetInternalExtension(file.Title);
                }

                if ((file.Version <= version || !newExtension.Equals(currentExt) || version < 1) &&
                    (file.Version > 1 || !asNew) &&
                    !FileTracker.FixedVersion(file.ID))
                {
                    file.Version++;
                    if (string.IsNullOrEmpty(comment))
                    {
                        comment = FilesCommonResource.CommentEdit;
                    }
                }
                else
                {
                    if (string.IsNullOrEmpty(comment))
                    {
                        comment = FilesCommonResource.CommentCreate;
                    }
                }

                file.ConvertedType = FileUtility.GetFileExtension(file.Title) != newExtension ? newExtension : null;

                if (file.ProviderEntry && !newExtension.Equals(currentExt))
                {
                    if (FileUtility.ExtsConvertible.Keys.Contains(newExtension) &&
                        FileUtility.ExtsConvertible[newExtension].Contains(currentExt))
                    {
                        var key = DocumentServiceConnector.GenerateRevisionId(downloadUri ?? Guid.NewGuid().ToString());
                        if (stream != null)
                        {
                            using (var tmpStream = new MemoryStream())
                            {
                                stream.CopyTo(tmpStream);
                                downloadUri = DocumentServiceConnector.GetExternalUri(tmpStream, newExtension, key);
                            }
                        }

                        DocumentServiceConnector.GetConvertedUri(downloadUri, newExtension, currentExt, key, false, out downloadUri);

                        stream = null;
                    }
                    else
                    {
                        file.ID    = null;
                        file.Title = FileUtility.ReplaceFileExtension(file.Title, newExtension);
                    }

                    file.ConvertedType = null;
                }

                using (var tmpStream = new MemoryStream())
                {
                    if (stream != null)
                    {
                        stream.CopyTo(tmpStream);
                    }
                    else
                    {
                        // hack. http://ubuntuforums.org/showthread.php?t=1841740
                        if (WorkContext.IsMono)
                        {
                            ServicePointManager.ServerCertificateValidationCallback += (s, ce, ca, p) => true;
                        }

                        var req = (HttpWebRequest)WebRequest.Create(downloadUri);
                        using (var editedFileStream = new ResponseStream(req.GetResponse()))
                        {
                            editedFileStream.CopyTo(tmpStream);
                        }
                    }
                    tmpStream.Position = 0;

                    file.ContentLength = tmpStream.Length;
                    file.Comment       = string.IsNullOrEmpty(comment) ? null : comment;
                    file = fileDao.SaveFile(file, tmpStream);
                }
            }

            checkRight = FileTracker.ProlongEditing(file.ID, tabId, true, SecurityContext.CurrentAccount.ID);
            if (checkRight)
            {
                FileTracker.ChangeRight(file.ID, SecurityContext.CurrentAccount.ID, false);
            }

            FileMarker.MarkAsNew(file);
            FileMarker.RemoveMarkAsNew(file);
            return(file);
        }
Esempio n. 14
0
        public FileOperationResult ExecSync <T>(File <T> file, string doc)
        {
            var fileDao      = DaoFactory.GetFileDao <T>();
            var fileSecurity = FileSecurity;

            if (!fileSecurity.CanRead(file))
            {
                var readLink = FileShareLink.Check(doc, true, fileDao, out file);
                if (file == null)
                {
                    throw new ArgumentNullException("file", FilesCommonResource.ErrorMassage_FileNotFound);
                }
                if (!readLink)
                {
                    throw new SecurityException(FilesCommonResource.ErrorMassage_SecurityException_ReadFile);
                }
            }

            var fileUri       = PathProvider.GetFileStreamUrl(file);
            var fileExtension = file.ConvertedExtension;
            var toExtension   = FileUtility.GetInternalExtension(file.Title);
            var docKey        = DocumentServiceHelper.GetDocKey(file);

            fileUri = DocumentServiceConnector.ReplaceCommunityAdress(fileUri);
            DocumentServiceConnector.GetConvertedUri(fileUri, fileExtension, toExtension, docKey, null, null, null, false, out var convertUri);

            var operationResult = new ConvertFileOperationResult
            {
                Source                                        = string.Format("{{\"id\":\"{0}\", \"version\":\"{1}\"}}", file.ID, file.Version),
                OperationType                                 = FileOperationType.Convert,
                Error                                         = string.Empty,
                Progress                                      = 0,
                Result                                        = string.Empty,
                Processed                                     = "",
                Id                                            = string.Empty,
                TenantId                                      = TenantManager.GetCurrentTenant().TenantId,
                Account                                       = AuthContext.CurrentAccount,
                Delete                                        = false,
                StartDateTime                                 = DateTime.Now,
                Url                                           = HttpContextAccesor?.HttpContext != null?HttpContextAccesor.HttpContext.Request.GetUrlRewriter().ToString() : null,
                                               Password       = null,
                                               ServerRootPath = BaseCommonLinkUtility.ServerRootPath
            };

            var operationResultError = string.Empty;

            var newFile = SaveConvertedFile(file, convertUri);

            if (newFile != null)
            {
                var folderDao   = DaoFactory.GetFolderDao <T>();
                var folder      = folderDao.GetFolder(newFile.FolderID);
                var folderTitle = fileSecurity.CanRead(folder) ? folder.Title : null;
                operationResult.Result = GetFileConverter <T>().FileJsonSerializer(EntryStatusManager, newFile, folderTitle);
            }

            operationResult.Progress     = 100;
            operationResult.StopDateTime = DateTime.UtcNow;
            operationResult.Processed    = "1";

            if (!string.IsNullOrEmpty(operationResultError))
            {
                operationResult.Error = operationResultError;
            }

            return(operationResult);
        }
Esempio n. 15
0
        public static File SaveEditing(String fileId, int version, Guid tabId, string downloadUri, bool asNew, String shareLinkKey, string comment = null, bool checkRight = true)
        {
            var app = ThirdPartySelector.GetAppByFileId(fileId);

            if (app != null)
            {
                app.SaveFile(fileId, downloadUri);
                return(null);
            }

            File file;

            using (var fileDao = Global.DaoFactory.GetFileDao())
            {
                var editLink = FileShareLink.Check(shareLinkKey, false, fileDao, out file);
                if (file == null)
                {
                    file = fileDao.GetFile(fileId);
                }

                if (file == null)
                {
                    throw new FileNotFoundException(FilesCommonResource.ErrorMassage_FileNotFound);
                }
                if (checkRight && !editLink && (!Global.GetFilesSecurity().CanEdit(file) || CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID).IsVisitor()))
                {
                    throw new SecurityException(FilesCommonResource.ErrorMassage_SecurityException_EditFile);
                }
                if (checkRight && FileLockedForMe(file.ID))
                {
                    throw new Exception(FilesCommonResource.ErrorMassage_LockedFile);
                }
                if (file.RootFolderType == FolderType.TRASH)
                {
                    throw new Exception(FilesCommonResource.ErrorMassage_ViewTrashItem);
                }

                var currentType   = file.ConvertedType ?? FileUtility.GetFileExtension(file.Title);
                var newType       = FileUtility.GetFileExtension(downloadUri);
                var updateVersion = file.Version > 1 || file.ConvertedType == null || !asNew;

                if ((file.Version <= version || currentType != newType || version == -1) &&
                    updateVersion &&
                    !FileTracker.FixedVersion(file.ID))
                {
                    file.Version++;
                }

                file.ConvertedType = newType;

                if (file.ProviderEntry && !newType.Equals(currentType))
                {
                    var key = DocumentServiceConnector.GenerateRevisionId(downloadUri);
                    DocumentServiceConnector.GetConvertedUri(downloadUri, newType, currentType, key, false, out downloadUri);

                    file.ConvertedType = currentType;
                }

                var req = (HttpWebRequest)WebRequest.Create(downloadUri);
                using (var editedFileStream = new ResponseStream(req.GetResponse()))
                {
                    file.ContentLength = editedFileStream.Length;
                    file.Comment       = string.IsNullOrEmpty(comment) ? string.Empty : comment;
                    file = fileDao.SaveFile(file, editedFileStream);
                }
            }

            checkRight = FileTracker.ProlongEditing(file.ID, tabId, true, SecurityContext.CurrentAccount.ID);
            if (checkRight)
            {
                FileTracker.ChangeRight(file.ID, SecurityContext.CurrentAccount.ID, false);
            }

            FileMarker.MarkAsNew(file);
            FileMarker.RemoveMarkAsNew(file);
            return(file);
        }