Beispiel #1
0
        protected void PageLoad()
        {
            var file = new File();

            try
            {
                ShareLink = Request[UrlConstant.DocUrlKey] ?? "";
                WithLink  = !string.IsNullOrEmpty(ShareLink);

                var fileId = WithLink ? (object)-1 : Request[UrlConstant.FileId];
                FileNew = !string.IsNullOrEmpty(Request[UrlConstant.New]) && Request[UrlConstant.New] == "true";

                file = DocumentUtils.EditIframeSrc(fileId, FileNew, ShareLink, out SrcIframe);

                if (SecurityContext.IsAuthenticated)
                {
                    var parent = Global.DaoFactory.GetFolderDao().GetFolder(file.FolderID);
                    if (file.RootFolderType == FolderType.USER &&
                        file.RootFolderCreator != SecurityContext.CurrentAccount.ID &&
                        !Global.GetFilesSecurity().CanRead(parent))
                    {
                        FolderUrl = PathProvider.GetFolderUrl(Global.FolderShare, false, null);
                    }
                    else
                    {
                        FolderUrl = PathProvider.GetFolderUrl(parent);

                        if (string.IsNullOrEmpty(FolderUrl))
                        {
                            FolderUrl = Request.UrlReferrer == null
                                            ? VirtualPathUtility.ToAbsolute(PathProvider.StartURL)
                                            : Request.UrlReferrer.ToString();
                        }

                        if (Global.EnableShare)
                        {
                            CommonContainerHolder.Controls.Add(LoadControl(AccessRights.Location));
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Response.Redirect(PathProvider.BaseVirtualPath + "docviewer.aspx" + "?" + Request.QueryString + "#" + UrlConstant.Error + "/" + HttpUtility.UrlEncode(ex.Message));
            }

            Title       = file.Title;
            FileId      = file.ID;
            FileTitle   = file.Title;
            FileVersion = file.Version;

            DocKeyForTrack = DocumentUtils.GetDocKey(file.ID, -1, DateTime.MinValue);

            using (var tagDao = Global.DaoFactory.GetTagDao())
            {
                tagDao.RemoveTags(Tag.New(SecurityContext.CurrentAccount.ID, file));
            }

            FileLocker.Add(file.ID);
        }
Beispiel #2
0
        public static List <DocServiceParams.RecentDocument> GetRecentEditedDocument(bool forEdit, int count, string crumbsSeporator, IFileDao fileDao)
        {
            var recent = new List <DocServiceParams.RecentDocument>();

            var activity = UserActivityManager.GetUserActivities(TenantProvider.CurrentTenantID, SecurityContext.CurrentAccount.ID,
                                                                 ProductEntryPoint.ID, null, UserActivityConstants.AllActionType,
                                                                 new[] { "OpenEditorFile" }, 0, 100);

            foreach (var entryId in activity.Select(userActivity => userActivity.ContentID.Substring("file_".Length)))
            {
                if (recent.Exists(r => r.ID.Equals(entryId)))
                {
                    continue;
                }

                var fileAct = fileDao.GetFile(entryId);

                if (fileAct.RootFolderType == FolderType.TRASH)
                {
                    continue;
                }

                if (!FileUtility.UsingHtml5(fileAct.Title))
                {
                    continue;
                }

                if (!Global.GetFilesSecurity().CanRead(fileAct))
                {
                    continue;
                }

                string uri;
                if (forEdit && Global.GetFilesSecurity().CanEdit(fileAct))
                {
                    uri = CommonLinkUtility.GetFileWebEditorUrl(fileAct.ID);
                }
                else
                {
                    uri = CommonLinkUtility.GetFileWebViewerUrl(fileAct.ID);
                }

                var fileBreadCrumbs = Global.GetBreadCrumbs(fileAct.FolderID);
                recent.Add(new DocServiceParams.RecentDocument
                {
                    ID         = entryId,
                    Title      = fileAct.Title,
                    Uri        = CommonLinkUtility.GetFullAbsolutePath(uri),
                    FolderPath = string.Join(crumbsSeporator, fileBreadCrumbs.Select(folder => folder.Title).ToArray())
                });

                if (recent.Count == count)
                {
                    break;
                }
            }
            return(recent);
        }
Beispiel #3
0
        private void InitScript()
        {
            var  fileId = Request[FilesLinkUtility.FileId];
            File file;

            try
            {
                using (var fileDao = Global.DaoFactory.GetFileDao())
                {
                    file = fileDao.GetFile(fileId);
                }
            }
            catch (Exception ex)
            {
                Global.Logger.Error("ShareLink", ex);

                Response.StatusCode = (int)HttpStatusCode.BadRequest;
                return;
            }

            if (file == null)
            {
                Response.StatusCode = (int)HttpStatusCode.NotFound;
                return;
            }
            if (!Global.GetFilesSecurity().CanRead(file))
            {
                Response.StatusCode = (int)HttpStatusCode.Forbidden;
                return;
            }

            var originForPost = "*";

            if (!FilesLinkUtility.DocServiceApiUrl.StartsWith("/"))
            {
                var origin = new Uri(FilesLinkUtility.DocServiceApiUrl ?? "");
                originForPost = origin.Scheme + "://" + origin.Host + ":" + origin.Port;
            }

            var script = new StringBuilder();

            script.AppendFormat("ASC.Files.Share.getSharedInfo(\"file_{0}\", \"{1}\", true, {2}, \"{3}\", {4}, {5}, {6}, {7});",
                                file.ID,
                                file.Title,
                                (file.RootFolderType == FolderType.COMMON).ToString().ToLower(),
                                originForPost,
                                file.DenyDownload.ToString().ToLower(),
                                file.DenySharing.ToString().ToLower(),
                                file.ProviderEntry.ToString().ToLower(),
                                JsonConvert.SerializeObject(FilesSettings.DefaultSharingAccessRights));

            //todo: change hardcode url
            script.AppendFormat("\r\nASC.Controls.JabberClient.pathWebTalk = \"{0}\";",
                                VirtualPathUtility.ToAbsolute("~/addons/talk/JabberClient.aspx"));
            Page.RegisterInlineScript(script.ToString());
        }
Beispiel #4
0
        private void InitScript()
        {
            var  fileId = Request[FilesLinkUtility.FileId];
            File file;

            try
            {
                using (var fileDao = Global.DaoFactory.GetFileDao())
                {
                    file = fileDao.GetFile(fileId);
                }
            }
            catch (Exception ex)
            {
                Global.Logger.Error("ShareLink", ex);

                Response.StatusCode = (int)HttpStatusCode.BadRequest;
                return;
            }

            if (file == null)
            {
                Response.StatusCode = (int)HttpStatusCode.NotFound;
                return;
            }
            if (!FileSharing.CanSetAccess(file))
            {
                Response.StatusCode = (int)HttpStatusCode.Forbidden;
                return;
            }

            var shareRecord = Global.GetFilesSecurity().GetShares(file).FirstOrDefault(r => r.Subject == FileConstant.ShareLinkId);

            if (shareRecord == null)
            {
                Response.StatusCode = (int)HttpStatusCode.Forbidden;
                return;
            }

            Link = FileShareLink.GetLink(file);

            if (BitlyLoginProvider.Enabled)
            {
                try
                {
                    Link = BitlyLoginProvider.GetShortenLink(Link);
                }
                catch (Exception ex)
                {
                    Global.Logger.Error("Get shorten link", ex);
                }
            }
        }
Beispiel #5
0
        private List <SubscriptionObject> GetFilesShare(Guid productID, Guid moduleID, Guid typeID)
        {
            if (!productID.Equals(Configuration.ProductEntryPoint.ID) || !moduleID.Equals(subscrGroupsUpdateDoc) || !typeID.Equals(subscrTypeUpdateDoc))
            {
                return(null);
            }

            var groupFollow         = GetSubscriptionGroups().Find(r => r.ID.Equals(moduleID));
            var typeFollow          = GetSubscriptionTypes().Find(r => r.ID.Equals(typeID));
            var subscriptionObjects = new List <SubscriptionObject>();

            using (var fileDao = Global.DaoFactory.GetFileDao())
            {
                var filesId = new List <object>();

                NotifySource.Instance.GetSubscriptionProvider()
                .GetSubscriptions(NotifyConstants.Event_UpdateDocument, NotifySource.Instance.GetRecipientsProvider().GetRecipient(SecurityContext.CurrentAccount.ID.ToString()))
                .ToList().ForEach(
                    id =>
                {
                    if (id.StartsWith("file_"))
                    {
                        filesId.Add(id.Substring("file_".Length));
                    }
                }
                    );

                Global.GetFilesSecurity().FilterRead(fileDao.GetFiles(filesId.ToArray()))
                .ToList()
                .ForEach(file => subscriptionObjects.Add(new SubscriptionObject
                {
                    ID   = file.UniqID,
                    Name = HttpUtility.HtmlDecode(file.Title),
                    URL  = file.ViewUrl,
                    SubscriptionGroup = groupFollow,
                    SubscriptionType  = typeFollow
                })
                         );
            }

            return(subscriptionObjects);
        }
Beispiel #6
0
        private void InitScript()
        {
            var  fileId = Request[FilesLinkUtility.FileId];
            File file;

            try
            {
                using (var fileDao = Global.DaoFactory.GetFileDao())
                {
                    file = fileDao.GetFile(fileId);
                }
            }
            catch (Exception ex)
            {
                Global.Logger.Error("ShareLink", ex);

                Response.StatusCode = (int)HttpStatusCode.BadRequest;
                return;
            }

            if (file == null)
            {
                Response.StatusCode = (int)HttpStatusCode.NotFound;
                return;
            }
            if (!Global.GetFilesSecurity().CanRead(file))
            {
                Response.StatusCode = (int)HttpStatusCode.Forbidden;
                return;
            }

            var script = new StringBuilder();

            script.AppendFormat("ASC.Files.Share.getSharedInfo(\"file_{0}\", \"{1}\", true, {2} === true);",
                                file.ID,
                                file.Title,
                                (file.RootFolderType == FolderType.COMMON).ToString().ToLower());
            Page.RegisterInlineScript(script.ToString());
        }
Beispiel #7
0
        private static FileShare CheckShareLink(string key, IFileDao fileDao, out File file)
        {
            file = null;

            var fileId = ParseShareLink(key);

            file = fileDao.GetFile(fileId);
            if (file == null)
            {
                return(FileShare.Restrict);
            }

            var filesSecurity = Global.GetFilesSecurity();

            if (filesSecurity.CanEdit(file, FileConstant.ShareLinkId))
            {
                return(FileShare.ReadWrite);
            }
            if (filesSecurity.CanRead(file, FileConstant.ShareLinkId))
            {
                return(FileShare.Read);
            }
            return(FileShare.Restrict);
        }
Beispiel #8
0
        public bool FilterActivity(UserActivity activity)
        {
            if (activity == null)
            {
                return(true);
            }

            if (string.IsNullOrEmpty(activity.SecurityId))
            {
                return(true);
            }

            try
            {
                string entryId;
                if (activity.ContentID.StartsWith("file_"))
                {
                    entryId = activity.ContentID.Substring("file_".Length);
                    var file = Global.DaoFactory.GetFileDao().GetFile(entryId);
                    return(Global.GetFilesSecurity().CanRead(file));
                }

                if (activity.ContentID.StartsWith("folder_"))
                {
                    entryId = activity.ContentID.Substring("folder_".Length);
                    var folder = Global.DaoFactory.GetFolderDao().GetFolder(entryId);
                    return(Global.GetFilesSecurity().CanRead(folder));
                }
            }
            catch (Exception)
            {
                return(false);
            }

            return(true);
        }
        private void PageLoad()
        {
            var editPossible = !RequestEmbedded;
            var isExtenral   = false;

            File file;
            var  fileUri = string.Empty;

            try
            {
                if (string.IsNullOrEmpty(RequestFileUrl))
                {
                    var app = ThirdPartySelector.GetAppByFileId(RequestFileId);
                    if (app == null)
                    {
                        file = DocumentServiceHelper.GetParams(RequestFileId, RequestVersion, RequestShareLinkKey, editPossible, !RequestView, true, out _configuration);
                        if (_valideShareLink)
                        {
                            _configuration.Document.SharedLinkKey += RequestShareLinkKey;
                            _configuration.Document.Info.Favorite  = null;

                            if (CoreContext.Configuration.Personal && !SecurityContext.IsAuthenticated)
                            {
                                var user    = CoreContext.UserManager.GetUsers(file.CreateBy);
                                var culture = CultureInfo.GetCultureInfo(user.CultureName);
                                Thread.CurrentThread.CurrentCulture   = culture;
                                Thread.CurrentThread.CurrentUICulture = culture;
                            }
                        }
                    }
                    else
                    {
                        isExtenral = true;

                        bool editable;
                        _thirdPartyApp = true;
                        file           = app.GetFile(RequestFileId, out editable);
                        file           = DocumentServiceHelper.GetParams(file, true, editPossible ? FileShare.ReadWrite : FileShare.Read, false, editable, editable, editable, true, out _configuration);

                        _configuration.Document.Url = app.GetFileStreamUrl(file);
                        _configuration.EditorConfig.Customization.GobackUrl = string.Empty;
                        _configuration.Document.Info.Favorite = null;
                    }
                }
                else
                {
                    isExtenral = true;

                    fileUri = RequestFileUrl;
                    var fileTitle = Request[FilesLinkUtility.FileTitle];
                    if (string.IsNullOrEmpty(fileTitle))
                    {
                        fileTitle = Path.GetFileName(HttpUtility.UrlDecode(fileUri)) ?? "";
                    }

                    file = new File
                    {
                        ID    = RequestFileUrl,
                        Title = Global.ReplaceInvalidCharsAndTruncate(fileTitle)
                    };

                    file = DocumentServiceHelper.GetParams(file, true, FileShare.Read, false, false, false, false, false, out _configuration);
                    _configuration.Document.Permissions.Edit          = editPossible && !CoreContext.Configuration.Standalone;
                    _configuration.Document.Permissions.Rename        = false;
                    _configuration.Document.Permissions.Review        = false;
                    _configuration.Document.Permissions.FillForms     = false;
                    _configuration.Document.Permissions.ChangeHistory = false;
                    _configuration.Document.Permissions.ModifyFilter  = false;
                    _editByUrl = true;

                    _configuration.Document.Url           = fileUri;
                    _configuration.Document.Info.Favorite = null;
                }
                ErrorMessage = _configuration.ErrorMessage;
            }
            catch (Exception ex)
            {
                Global.Logger.Warn("DocEditor", ex);
                ErrorMessage = ex.Message;
                return;
            }

            var        userAgent      = Request.UserAgent.ToString().ToLower();
            HttpCookie deeplinkCookie = Request.Cookies.Get("deeplink");
            var        deepLink       = ConfigurationManagerExtension.AppSettings["deeplink.documents.url"];

            if (!_valideShareLink &&
                deepLink != null && MobileDetector.IsMobile &&
                ((!userAgent.Contains("version/") && userAgent.Contains("android")) || !userAgent.Contains("android")) &&       //check webkit
                ((Request[DeepLinking.WithoutDeeplinkRedirect] == null && deeplinkCookie == null) ||
                 Request[DeepLinking.WithoutDeeplinkRedirect] == null && deeplinkCookie != null && deeplinkCookie.Value == "app"))
            {
                var          currentUser  = CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID);
                DeepLinkData deepLinkData = new DeepLinkData
                {
                    Email  = currentUser.Email,
                    Portal = CoreContext.TenantManager.GetCurrentTenant().TenantDomain,
                    File   = new DeepLinkDataFile
                    {
                        Id        = file.ID.ToString(),
                        Title     = file.Title,
                        Extension = file.ConvertedExtension
                    },
                    Folder = new DeepLinkDataFolder
                    {
                        Id             = file.FolderID.ToString(),
                        ParentId       = file.RootFolderId.ToString(),
                        RootFolderType = (int)file.RootFolderType
                    },
                    OriginalUrl = Request.GetUrlRewriter().ToString()
                };

                var    jsonDeeplinkData   = JsonConvert.SerializeObject(deepLinkData);
                string base64DeeplinkData = Convert.ToBase64String(Encoding.UTF8.GetBytes(jsonDeeplinkData));

                Response.Redirect("~/DeepLink.aspx?data=" + HttpUtility.UrlEncode(base64DeeplinkData));
            }


            if (_configuration.EditorConfig.ModeWrite && FileConverter.MustConvert(file))
            {
                try
                {
                    file = FileConverter.ExecSync(file, RequestShareLinkKey);
                }
                catch (Exception ex)
                {
                    _configuration = null;
                    Global.Logger.Error("DocEditor", ex);
                    ErrorMessage = ex.Message;
                    return;
                }

                var comment = "#message/" + HttpUtility.UrlEncode(string.Format(FilesCommonResource.ConvertForEdit, file.Title));

                Response.Redirect(FilesLinkUtility.GetFileWebEditorUrl(file.ID) + comment);
                return;
            }

            var fileSecurity = Global.GetFilesSecurity();

            if (_configuration.EditorConfig.ModeWrite &&
                FileUtility.CanWebRestrictedEditing(file.Title) &&
                fileSecurity.CanFillForms(file) &&
                !fileSecurity.CanEdit(file))
            {
                if (!file.IsFillFormDraft)
                {
                    FileMarker.RemoveMarkAsNew(file);

                    Folder folderIfNew;
                    try
                    {
                        file = EntryManager.GetFillFormDraft(file, out folderIfNew);
                    }
                    catch (Exception ex)
                    {
                        _configuration = null;
                        Global.Logger.Error("DocEditor", ex);
                        ErrorMessage = ex.Message;
                        return;
                    }

                    var comment = folderIfNew == null
                        ? string.Empty
                        : "#message/" + HttpUtility.UrlEncode(string.Format(FilesCommonResource.MessageFillFormDraftCreated, folderIfNew.Title));

                    Response.Redirect(FilesLinkUtility.GetFileWebEditorUrl(file.ID) + comment);
                    return;
                }
                else if (!EntryManager.CheckFillFormDraft(file))
                {
                    var comment = "#message/" + HttpUtility.UrlEncode(FilesCommonResource.MessageFillFormDraftDiscard);

                    Response.Redirect(FilesLinkUtility.GetFileWebEditorUrl(file.ID) + comment);
                    return;
                }
            }

            Title = file.Title + GetPageTitlePostfix();

            if (_configuration.EditorConfig.Customization.Goback == null || string.IsNullOrEmpty(_configuration.EditorConfig.Customization.Goback.Url))
            {
                _configuration.EditorConfig.Customization.GobackUrl = Request[FilesLinkUtility.FolderUrl] ?? "";
            }

            _configuration.EditorConfig.Customization.IsRetina = TenantLogoManager.IsRetina(Request);

            if (RequestEmbedded)
            {
                _configuration.Type = Services.DocumentService.Configuration.EditorType.Embedded;

                _configuration.EditorConfig.Embedded.ShareLinkParam = string.IsNullOrEmpty(RequestShareLinkKey) ? string.Empty : "&" + FilesLinkUtility.DocShareKey + "=" + RequestShareLinkKey;
            }
            else
            {
                _configuration.Type = IsMobile ? Services.DocumentService.Configuration.EditorType.Mobile : Services.DocumentService.Configuration.EditorType.Desktop;

                if (FileSharing.CanSetAccess(file) &&
                    !(file.Encrypted &&
                      (!Request.DesktopApp() ||
                       CoreContext.Configuration.Personal)))
                {
                    _configuration.EditorConfig.SharingSettingsUrl = CommonLinkUtility.GetFullAbsolutePath(
                        Share.Location
                        + "?" + FilesLinkUtility.FileId + "=" + HttpUtility.UrlEncode(file.ID.ToString())
                        + (Request.DesktopApp() ? "&desktop=true" : string.Empty));
                }

                if (file.RootFolderType == FolderType.Privacy)
                {
                    if (!PrivacyRoomSettings.Enabled)
                    {
                        _configuration = null;
                        ErrorMessage   = FilesCommonResource.ErrorMassage_FileNotFound;
                        return;
                    }
                    else
                    {
                        if (Request.DesktopApp())
                        {
                            var keyPair = EncryptionKeyPair.GetKeyPair();
                            if (keyPair != null)
                            {
                                _configuration.EditorConfig.EncryptionKeys = new Services.DocumentService.Configuration.EditorConfiguration.EncryptionKeysConfig
                                {
                                    PrivateKeyEnc = keyPair.PrivateKeyEnc,
                                    PublicKey     = keyPair.PublicKey,
                                };
                            }
                        }
                    }
                }
            }

            if (!isExtenral)
            {
                _docKeyForTrack = DocumentServiceHelper.GetDocKey(file.ID, -1, DateTime.MinValue);

                FileMarker.RemoveMarkAsNew(file);
                if (!file.Encrypted && !file.ProviderEntry)
                {
                    EntryManager.MarkAsRecent(file);
                }

                if (RequestView)
                {
                    FilesMessageService.Send(file, MessageInitiator.DocsService, MessageAction.FileReaded, file.Title);
                }
                else
                {
                    FilesMessageService.Send(file, MessageInitiator.DocsService, MessageAction.FileOpenedForChange, file.Title);
                }
            }

            if (SecurityContext.IsAuthenticated)
            {
                var saveAsUrl = SaveAs.GetUrl;
                using (var folderDao = Global.DaoFactory.GetFolderDao())
                {
                    var folder = folderDao.GetFolder(file.FolderID);
                    if (folder != null && Global.GetFilesSecurity().CanCreate(folder))
                    {
                        saveAsUrl = SaveAs.GetUrlToFolder(file.FolderID);
                    }
                }

                _configuration.EditorConfig.SaveAsUrl = CommonLinkUtility.GetFullAbsolutePath(saveAsUrl);
            }

            if (_configuration.EditorConfig.ModeWrite)
            {
                _tabId = FileTracker.Add(file.ID);

                Global.SocketManager.FilesChangeEditors(file.ID);

                if (SecurityContext.IsAuthenticated)
                {
                    _configuration.EditorConfig.FileChoiceUrl = CommonLinkUtility.GetFullAbsolutePath(FileChoice.GetUrlForEditor);
                }
            }
            else
            {
                _linkToEdit = _editByUrl
                                  ? CommonLinkUtility.GetFullAbsolutePath(FilesLinkUtility.GetFileWebEditorExternalUrl(fileUri, file.Title))
                                  : CommonLinkUtility.GetFullAbsolutePath(FilesLinkUtility.GetFileWebEditorUrl(file.ID));
                if (Request.DesktopApp())
                {
                    _linkToEdit += "&desktop=true";
                }

                if (FileConverter.MustConvert(_configuration.Document.Info.File))
                {
                    _editByUrl = true;
                }
            }

            var actionAnchor = Request[FilesLinkUtility.Anchor];

            if (!string.IsNullOrEmpty(actionAnchor))
            {
                _configuration.EditorConfig.ActionLinkString = actionAnchor;
            }
        }
Beispiel #10
0
        public static File UploadFile(string folderId, string title, long contentLength, string contentType, Stream data, bool createNewIfExist)
        {
            if (contentLength > SetupInfo.MaxUploadSize)
            {
                throw FileSizeComment.FileSizeException;
            }
            if (contentLength <= 0)
            {
                throw new InvalidOperationException(FilesCommonResource.ErrorMassage_EmptyFile);
            }

            title = Global.ReplaceInvalidCharsAndTruncate(Path.GetFileName(title));

            using (var dao = Global.DaoFactory.GetFileDao())
            {
                var file = dao.GetFile(folderId, title);

                if (file == null || createNewIfExist)
                {
                    using (var folderDao = Global.DaoFactory.GetFolderDao())
                    {
                        var folder = folderDao.GetFolder(folderId);
                        if (folder == null)
                        {
                            throw new Exception(FilesCommonResource.ErrorMassage_FolderNotFound);
                        }
                        if (!Global.GetFilesSecurity().CanCreate(folder))
                        {
                            throw new SecurityException(FilesCommonResource.ErrorMassage_SecurityException_Create);
                        }
                        file = new File
                        {
                            FolderID      = folder.ID,
                            Title         = title,
                            ContentLength = contentLength,
                            ContentType   = contentType
                        };
                    }

                    try
                    {
                        file = dao.SaveFile(file, data);
                    }
                    catch
                    {
                        dao.DeleteFile(file.ID);
                        throw;
                    }
                    FilesActivityPublisher.UploadFile(dao.GetFile(file.ID));
                }
                else
                {
                    if (!Global.GetFilesSecurity().CanEdit(file))
                    {
                        throw new SecurityException(FilesCommonResource.ErrorMassage_SecurityException);
                    }
                    if ((file.FileStatus & FileStatus.IsEditing) == FileStatus.IsEditing)
                    {
                        throw new Exception(FilesCommonResource.ErrorMassage_SecurityException_DeleteEditingFile);
                    }

                    file.Title         = title;
                    file.ContentLength = contentLength;
                    file.ContentType   = contentType;
                    file.ConvertedType = null;
                    file.Version++;

                    file = dao.SaveFile(file, data);

                    Global.PublishUpdateDocument(file.ID);
                }
                return(file);
            }
        }
Beispiel #11
0
        public static File GetServiceParams(bool forEdit, object fileId, int version, bool itsNew, string shareLink, out DocServiceParams docServiceParams, bool forHtml5)
        {
            File         file;
            const string crumbsSeporator = " > ";
            var          breadCrumbs     = new List <Folder>();
            var          recent          = new ItemList <DocServiceParams.RecentDocument>();
            var          acesParams      = new ItemList <DocServiceParams.Aces>();
            var          folderUrl       = "";

            var    lastVersion = true;
            var    checkLink   = false;
            var    canEdit     = true;
            string fileExt;

            var documentType = string.Empty;

            using (var fileDao = Global.DaoFactory.GetFileDao())
            {
                if (forEdit)
                {
                    checkLink = CheckShareLink(shareLink, false, fileDao, out file);
                    if (!checkLink && file == null)
                    {
                        file = fileDao.GetFile(fileId);
                    }
                }
                else
                {
                    if (version < 1)
                    {
                        var editLink = CheckShareLink(shareLink, fileDao, out file);
                        checkLink = editLink <= FileShare.Read;
                        if (checkLink)
                        {
                            canEdit = canEdit && editLink <= FileShare.ReadWrite;
                        }
                        else if (file == null)
                        {
                            file = fileDao.GetFile(fileId);
                        }
                    }
                    else
                    {
                        file = fileDao.GetFile(fileId, version);
                        if (file != null)
                        {
                            lastVersion = file.Version == fileDao.GetFile(fileId).Version;
                        }
                    }
                }

                if (file == null)
                {
                    throw new Exception(FilesCommonResource.ErrorMassage_FileNotFound);
                }

                if (forHtml5 && !FileUtility.UsingHtml5(file.Title, forEdit))
                {
                    docServiceParams = new DocServiceParams();
                    return(file);
                }

                if (file.RootFolderType == FolderType.TRASH)
                {
                    throw new Exception(FilesCommonResource.ErrorMassage_ViewTrashItem);
                }
                if (!checkLink)
                {
                    canEdit &= Global.GetFilesSecurity().CanEdit(file);
                    if (forEdit && !canEdit)
                    {
                        throw new SecurityException(FilesCommonResource.ErrorMassage_SecurityException_EditFile);
                    }
                    if (!forEdit && !Global.GetFilesSecurity().CanRead(file))
                    {
                        throw new SecurityException(FilesCommonResource.ErrorMassage_SecurityException_ReadFile);
                    }
                }

                fileExt = FileUtility.GetFileExtension(file.Title);

                canEdit = canEdit && (file.FileStatus & FileStatus.IsEditing) != FileStatus.IsEditing;
                if (forEdit && !canEdit)
                {
                    throw new Exception(FilesCommonResource.ErrorMassage_UpdateEditingFile);
                }

                canEdit = canEdit && FileUtility.ExtsWebEdited.Contains(fileExt, Comparer);
                if (forEdit && !canEdit)
                {
                    throw new Exception(FilesCommonResource.ErrorMassage_NotSupportedFormat);
                }


                if (!forEdit && !FileUtility.ExtsWebPreviewed.Contains(fileExt, Comparer))
                {
                    throw new Exception(FilesCommonResource.ErrorMassage_NotSupportedFormat);
                }

                if (forHtml5)
                {
                    breadCrumbs = Global.GetBreadCrumbs(file.FolderID);

                    recent = new ItemList <DocServiceParams.RecentDocument>(GetRecentEditedDocument(forEdit, 10, crumbsSeporator, fileDao));

                    if (FileUtility.DocumentExts.Contains(fileExt, Comparer))
                    {
                        documentType = "text";
                    }
                    else if (FileUtility.SpreadsheetExts.Contains(fileExt, Comparer))
                    {
                        documentType = "spreadsheet";
                    }
                    else if (FileUtility.PresentationExts.Contains(fileExt, Comparer))
                    {
                        documentType = "presentation";
                    }
                }
            }

            var buttons = string.Empty;

            if (fileExt != ".pdf" && !FileUtility.PresentationExts.Contains(fileExt, Comparer))
            {
                buttons += "download;";
            }

            if (lastVersion && canEdit)
            {
                buttons += "save;edit;";
            }

            if (SecurityContext.IsAuthenticated)
            {
                if (!checkLink && Global.EnableShare)
                {
                    if (file.RootFolderType == FolderType.COMMON && Global.IsAdministrator)
                    {
                        buttons += "share;";
                    }
                    else
                    {
                        if (file.RootFolderType == FolderType.USER && Equals(file.RootFolderId, Global.FolderMy))
                        {
                            buttons += "share;";
                        }
                    }
                }

                if (forHtml5)
                {
                    buttons += "create;";

                    using (var folderDao = Global.DaoFactory.GetFolderDao())
                    {
                        var parent = folderDao.GetFolder(file.FolderID);
                        if (file.RootFolderType == FolderType.USER &&
                            file.RootFolderCreator != SecurityContext.CurrentAccount.ID &&
                            !Global.GetFilesSecurity().CanRead(parent))
                        {
                            folderUrl = PathProvider.GetFolderUrl(Global.FolderShare, false, null);
                        }
                        else
                        {
                            folderUrl = PathProvider.GetFolderUrl(parent);
                        }
                    }

                    try
                    {
                        var docService = ServiceLocator.Current.GetInstance <IFileStorageService>();
                        var aces       = docService.GetSharedInfo(file.UniqID);
                        foreach (var aceWrapper in aces)
                        {
                            string permission;

                            switch (aceWrapper.Share)
                            {
                            case FileShare.Read:
                                permission = FilesCommonResource.AceStatusEnum_Read;
                                break;

                            case FileShare.ReadWrite:
                                permission = FilesCommonResource.AceStatusEnum_ReadWrite;
                                break;

                            default:
                                continue;
                            }

                            var user = aceWrapper.SubjectName;
                            if (aceWrapper.SubjectId.Equals(FileConstant.ShareLinkId))
                            {
                                continue;
                                //var domain = "?";
                                //switch (aceWrapper.Share)
                                //{
                                //    case FileShare.Read:
                                //        user = domain + CommonLinkUtility.GetFileWebViewerUrl(file.ID) + user;
                                //        break;
                                //    case FileShare.ReadWrite:
                                //        user = domain + CommonLinkUtility.GetFileWebEditorUrl(file.ID) + user;
                                //        break;
                                //    default:
                                //        continue;
                                //}
                            }

                            acesParams.Add(new DocServiceParams.Aces
                            {
                                User        = user,
                                Permissions = permission
                            });
                        }
                    }
                    catch (Exception)
                    {
                    }
                }
            }

            var versionForKey = file.Version;

            //CreateNewDoc
            if (forEdit)
            {
                versionForKey++;
                if (file.Version == 1 && file.ConvertedType != null && itsNew)
                {
                    versionForKey = 1;
                }
            }

            var docKey  = GetDocKey(file.ID, versionForKey, file.ModifiedOn);
            var docVKey = GetValidateKey(docKey, true);

            docServiceParams = new DocServiceParams
            {
                File = file,

                FileUri         = GetFileUri(file),
                OutputType      = string.IsNullOrEmpty(file.ProviderName) ? string.Empty : FileUtility.GetFileExtension(file.Title).Trim('.'),
                FileType        = (file.ConvertedType ?? FileUtility.GetFileExtension(file.Title)).Trim('.'),
                FilePath        = string.Join(crumbsSeporator, breadCrumbs.Select(folder => folder.Title).ToArray()),
                FolderUrl       = folderUrl,
                Recent          = recent,
                SharingSettings = acesParams,
                Buttons         = buttons,
                DocumentType    = documentType,

                Mode = forEdit ? "edit" : "view",

                Key  = docKey,
                Vkey = docVKey,
                Lang = CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID).GetCulture().Name
            };
            return(file);
        }
Beispiel #12
0
        protected void PageLoad()
        {
            File file;

            try
            {
                ShareLink = Request[UrlConstant.DocUrlKey] ?? "";
                WithLink  = !string.IsNullOrEmpty(ShareLink);

                var fileId  = WithLink ? (object)-1 : Request[UrlConstant.FileId];
                var ver     = string.IsNullOrEmpty(Request[UrlConstant.Version]) ? -1 : Convert.ToInt32(Request[UrlConstant.Version]);
                var fileNew = !string.IsNullOrEmpty(Request[UrlConstant.New]) && Request[UrlConstant.New] == "true";

                file = DocumentUtils.ViewIframeSrc(fileId, fileNew, ver, ShareLink, out SrcIframe);

                if (!MobileDetector.IsRequestMatchesMobile(Context))
                {
                    if (SecurityContext.IsAuthenticated)
                    {
                        var parent = Global.DaoFactory.GetFolderDao().GetFolder(file.FolderID);
                        if (file.RootFolderType == FolderType.USER &&
                            file.RootFolderCreator != SecurityContext.CurrentAccount.ID &&
                            !Global.GetFilesSecurity().CanRead(parent))
                        {
                            FolderUrl = PathProvider.GetFolderUrl(Global.FolderShare, false, null);
                        }
                        else
                        {
                            FolderUrl = PathProvider.GetFolderUrl(parent);

                            if (string.IsNullOrEmpty(FolderUrl))
                            {
                                FolderUrl = Request.UrlReferrer == null
                                                ? VirtualPathUtility.ToAbsolute(PathProvider.StartURL)
                                                : Request.UrlReferrer.ToString();
                            }

                            if (Global.EnableShare)
                            {
                                CommonContainerHolder.Controls.Add(LoadControl(AccessRights.Location));
                            }
                        }
                    }
                }
                else
                {
                    file = null;
                }
            }
            catch (Exception ex)
            {
                ErrorMessage = ex.Message;
                return;
                //var urlRedirect = Request.UrlReferrer == null
                //                      ? PathProvider.StartURL
                //                      : Request.UrlReferrer.ToString();

                //Response.Redirect(urlRedirect + "#" + UrlConstant.Error + "/" + HttpUtility.UrlEncode(ex.Message));
            }

            if (file == null)
            {
                Response.Redirect(SrcIframe);
            }

            Title       = file.Title;
            FileId      = file.ID;
            FileTitle   = file.Title;
            FileVersion = file.Version;

            using (var tagDao = Global.DaoFactory.GetTagDao())
            {
                tagDao.RemoveTags(Tag.New(SecurityContext.CurrentAccount.ID, file));
            }
        }