private void AddAccessRules(PageProperties newPage, IEnumerable <IAccessRule> userAccess)
        {
            if (cmsConfiguration.Security.AccessControlEnabled)
            {
                accessControlService.UpdateAccessControl(newPage, userAccess != null ? userAccess.ToList() : new List <IAccessRule>());
            }
            else
            {
                if (userAccess == null)
                {
                    return;
                }

                newPage.AccessRules = new List <AccessRule>();
                foreach (var rule in userAccess)
                {
                    newPage.AccessRules.Add(new AccessRule
                    {
                        Identity    = rule.Identity,
                        AccessLevel = rule.AccessLevel,
                        IsForRole   = rule.IsForRole
                    });
                }
            }
        }
Example #2
0
        /// <summary>
        /// Executes this command.
        /// </summary>
        /// <param name="request">The request.</param>
        public void Execute(FileViewModel request)
        {
            var mediaFile = Repository.First <MediaFile>(request.Id.ToGuidOrDefault());

            UnitOfWork.BeginTransaction();

            Repository.Save(mediaFile.CreateHistoryItem());

            mediaFile.PublishedOn = DateTime.Now;
            mediaFile.Title       = request.Title;
            mediaFile.Description = request.Description;
            mediaFile.Version     = request.Version.ToIntOrDefault();
            mediaFile.Image       = request.Image != null && request.Image.ImageId.HasValue ? Repository.AsProxy <MediaImage>(request.Image.ImageId.Value) : null;
            Repository.Save(mediaFile);

            // Save tags
            IList <Root.Models.Tag> newTags;

            tagService.SaveMediaTags(mediaFile, request.Tags, out newTags);

            // Save user access if enabled:
            if (cmsConfiguration.AccessControlEnabled)
            {
                accessControlService.UpdateAccessControl(request.UserAccessList, mediaFile.Id);
            }

            UnitOfWork.Commit();

            // Notify.
            Events.MediaManagerEvents.Instance.OnMediaFileUpdated(mediaFile);
        }
Example #3
0
        /// <summary>
        /// Upload file from the stream.
        /// </summary>
        /// <param name="request">The upload file request.</param>
        /// <returns>The upload file response.</returns>
        public UploadFileResponse Post(UploadFileRequest request)
        {
            MediaFolder parentFolder = null;

            if (request.Data.FolderId.HasValue)
            {
                parentFolder = repository.AsQueryable <MediaFolder>()
                               .Where(c => c.Id == request.Data.FolderId.Value && !c.IsDeleted)
                               .FirstOne();

                if (parentFolder.Type != Module.MediaManager.Models.MediaType.File)
                {
                    throw new CmsApiValidationException("Folder must be type of an file.");
                }
            }

            var savedFile = mediaFileService.UploadFileWithStream(
                Module.MediaManager.Models.MediaType.File,
                parentFolder != null ? parentFolder.Id : Guid.Empty,
                request.Data.FileName,
                request.Data.FileStream.Length,
                request.Data.FileStream,
                request.Data.WaitForUploadResult,
                request.Data.Title,
                request.Data.Description);

            if (savedFile != null)
            {
                if (request.Data.AccessRules != null)
                {
                    if (savedFile.AccessRules != null)
                    {
                        savedFile.AccessRules.RemoveDuplicateEntities();
                    }
                    var accessRules =
                        request.Data.AccessRules.Select(
                            r => (IAccessRule) new AccessRule {
                        AccessLevel = (AccessLevel)(int)r.AccessLevel, Identity = r.Identity, IsForRole = r.IsForRole
                    })
                        .ToList();
                    accessControlService.UpdateAccessControl(savedFile, accessRules);
                    mediaFileService.SaveMediaFile(savedFile);
                }

                Events.MediaManagerEvents.Instance.OnMediaFileUploaded(savedFile);
            }

            return(new UploadFileResponse
            {
                Data = savedFile.Id
            });
        }
Example #4
0
        /// <summary>
        /// Executes the specified request.
        /// </summary>
        /// <param name="request">The page view model.</param>
        /// <returns>Created page</returns>
        public virtual SavePageResponse Execute(AddNewPageViewModel request)
        {
            // Create / fix page url
            var pageUrl       = request.PageUrl;
            var createPageUrl = (pageUrl == null);

            if (createPageUrl && !string.IsNullOrWhiteSpace(request.PageTitle))
            {
                pageUrl = pageService.CreatePagePermalink(request.PageTitle, request.ParentPageUrl);
            }
            else
            {
                pageUrl = urlService.FixUrl(pageUrl);

                // Validate Url
                pageService.ValidatePageUrl(pageUrl);
            }

            var page = new PageProperties
            {
                PageUrl             = pageUrl,
                PageUrlLowerTrimmed = pageUrl.LowerTrimmedUrl(),
                Title     = request.PageTitle,
                MetaTitle = request.PageTitle,
                Layout    = Repository.First <Root.Models.Layout>(request.TemplateId),
                Status    = PageStatus.Unpublished
            };

            var parentOptions = Repository
                                .AsQueryable <LayoutOption>(o => o.Layout.Id == request.TemplateId)
                                .ToList();

            optionService.SaveOptionValues(request.OptionValues, null, parentOptions, () => new PageOption {
                Page = page
            });

            Repository.Save(page);

            // Update access control if enabled:
            if (cmsConfiguration.AccessControlEnabled)
            {
                accessControlService.UpdateAccessControl(request.UserAccessList, page.Id);
            }

            UnitOfWork.Commit();

            // Notifying, that page is created
            Events.PageEvents.Instance.OnPageCreated(page);

            return(new SavePageResponse(page));
        }
        /// <summary>
        /// Adds the default access rules to blog post entity.
        /// </summary>
        /// <param name="blogPost">The blog post.</param>
        /// <param name="principal">The principal.</param>
        /// <param name="masterPage">The master page.</param>
        protected void AddDefaultAccessRules(BlogPost blogPost, IPrincipal principal, Page masterPage)
        {
            IEnumerable <IAccessRule> accessRules;

            if (masterPage != null)
            {
                accessRules = masterPage.AccessRules;
            }
            else
            {
                accessRules = accessControlService.GetDefaultAccessList(principal);
            }

            accessControlService.UpdateAccessControl(blogPost, accessRules.ToList());
        }
Example #6
0
        /// <summary>
        /// Executes this command.
        /// </summary>
        /// <param name="request">The request.</param>
        public void Execute(FileViewModel request)
        {
//            var mediaFile = Repository.First<MediaFile>(request.Id.ToGuidOrDefault());

            var mediaFile = Repository.AsQueryable <MediaFile>().Where(mf => mf.Id == request.Id.ToGuidOrDefault()).ToList().First();

            UnitOfWork.BeginTransaction();

            var histItem = (MediaFile)mediaFile.CreateHistoryItem();

            histItem.SaveUnsecured = true;
            Repository.Save(histItem);

            mediaFile.PublishedOn = DateTime.UtcNow;
            mediaFile.Title       = request.Title;
            mediaFile.Description = request.Description;
            mediaFile.Version     = request.Version.ToIntOrDefault();
            mediaFile.Image       = request.Image != null && request.Image.ImageId.HasValue ? Repository.AsProxy <MediaImage>(request.Image.ImageId.Value) : null;

            categoryService.CombineEntityCategories <Media, MediaCategory>(mediaFile, request.Categories);

            Repository.Save(mediaFile);

            // Save tags.
            IList <Root.Models.Tag> newTags;

            tagService.SaveMediaTags(mediaFile, request.Tags, out newTags);

            // Save user access if enabled.
            if (cmsConfiguration.Security.AccessControlEnabled)
            {
                mediaFile.AccessRules.RemoveDuplicateEntities();

                var accessRules = request.UserAccessList != null?request.UserAccessList.Cast <IAccessRule>().Distinct().ToList() : null;

                accessControlService.UpdateAccessControl(mediaFile, accessRules);
            }

            UnitOfWork.Commit();

            // Notify.
            Events.MediaManagerEvents.Instance.OnMediaFileUpdated(mediaFile);
        }
Example #7
0
        /// <summary>
        /// Executes the specified request.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <returns>Save response.</returns>
        /// <exception cref="CmsException">Failed to save page properties.</exception>
        public SavePageResponse Execute(EditPagePropertiesViewModel request)
        {
            UnitOfWork.BeginTransaction();

            var pageQuery = Repository
                            .AsQueryable <PageProperties>(p => p.Id == request.Id)
                            .FetchMany(p => p.Options)
                            .Fetch(p => p.Layout).ThenFetchMany(l => l.LayoutOptions)
                            .AsQueryable();

            if (cmsConfiguration.Security.AccessControlEnabled)
            {
                pageQuery = pageQuery.FetchMany(f => f.AccessRules);
            }

            var page = pageQuery.ToList().FirstOne();

            if (cmsConfiguration.Security.AccessControlEnabled)
            {
                AccessControlService.DemandAccess(page, Context.Principal, AccessLevel.ReadWrite, RootModuleConstants.UserRoles.EditContent, RootModuleConstants.UserRoles.PublishContent);
            }
            else
            {
                AccessControlService.DemandAccess(Context.Principal, RootModuleConstants.UserRoles.EditContent, RootModuleConstants.UserRoles.PublishContent);
            }

            Models.Redirect redirectCreated  = null;
            bool            initialSeoStatus = page.HasSEO;

            request.PageUrl = urlService.FixUrl(request.PageUrl);

            if (!string.Equals(page.PageUrl, request.PageUrl))
            {
                pageService.ValidatePageUrl(request.PageUrl, request.Id);
                if (request.RedirectFromOldUrl)
                {
                    var redirect = redirectService.CreateRedirectEntity(page.PageUrl, request.PageUrl);
                    if (redirect != null)
                    {
                        Repository.Save(redirect);
                        redirectCreated = redirect;
                    }
                }

                page.NodeCountInSitemap = request.UpdateSitemap
                    ? sitemapService.ChangeUrl(page.PageUrl, request.PageUrl)
                    : sitemapService.NodesWithUrl(request.PageUrl);

                page.PageUrl = request.PageUrl;
            }

            page.PageUrlHash = page.PageUrl.UrlHash();
            page.Layout      = Repository.AsProxy <Root.Models.Layout>(request.TemplateId);
            page.Category    = request.CategoryId.HasValue ? Repository.AsProxy <CategoryEntity>(request.CategoryId.Value) : null;
            page.Title       = request.PageName;
            page.CustomCss   = request.PageCSS;
            page.CustomJS    = request.PageJavascript;

            var publishDraftContent = false;

            if (request.CanPublishPage)
            {
                AccessControlService.DemandAccess(Context.Principal, RootModuleConstants.UserRoles.PublishContent);

                if (request.IsPagePublished)
                {
                    if (page.Status != PageStatus.Published)
                    {
                        page.Status         = PageStatus.Published;
                        page.PublishedOn    = DateTime.Now;
                        publishDraftContent = true;
                    }
                }
                else
                {
                    page.Status = PageStatus.Unpublished;
                }
            }

            page.UseNoFollow     = request.UseNoFollow;
            page.UseNoIndex      = request.UseNoIndex;
            page.UseCanonicalUrl = request.UseCanonicalUrl;
            page.IsArchived      = request.IsArchived;
            page.Version         = request.Version;

            page.Image          = request.Image != null && request.Image.ImageId.HasValue ? Repository.AsProxy <MediaImage>(request.Image.ImageId.Value) : null;
            page.SecondaryImage = request.SecondaryImage != null && request.SecondaryImage.ImageId.HasValue ? Repository.AsProxy <MediaImage>(request.SecondaryImage.ImageId.Value) : null;
            page.FeaturedImage  = request.FeaturedImage != null && request.FeaturedImage.ImageId.HasValue ? Repository.AsProxy <MediaImage>(request.FeaturedImage.ImageId.Value) : null;

            var optionValues  = page.Options.Distinct();
            var parentOptions = page.Layout.LayoutOptions.Distinct();

            optionService.SaveOptionValues(request.OptionValues, optionValues, parentOptions, () => new PageOption {
                Page = page
            });

            if (cmsConfiguration.Security.AccessControlEnabled)
            {
                page.AccessRules.RemoveDuplicateEntities();

                var accessRules = request.UserAccessList != null?request.UserAccessList.Cast <IAccessRule>().ToList() : null;

                accessControlService.UpdateAccessControl(page, accessRules);
            }

            Repository.Save(page);

            // Save tags
            IList <Tag> newTags;

            tagService.SavePageTags(page, request.Tags, out newTags);

            if (publishDraftContent)
            {
                contentService.PublishDraftContent(page.Id);
            }

            UnitOfWork.Commit();

            // Notify about page properties change.
            Events.PageEvents.Instance.OnPagePropertiesChanged(page);

            // Notify about redirect creation.
            if (redirectCreated != null)
            {
                Events.PageEvents.Instance.OnRedirectCreated(redirectCreated);
            }

            // Notify about SEO status change.
            if (initialSeoStatus != page.HasSEO)
            {
                Events.PageEvents.Instance.OnPageSeoStatusChanged(page);
            }

            // Notify about new tags.
            Events.RootEvents.Instance.OnTagCreated(newTags);

            return(new SavePageResponse(page));
        }
Example #8
0
        /// <summary>
        /// Replaces the file or if it doesn't exist, creates it.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <returns>
        ///   <c>PutFileResponse</c> with a file id.
        /// </returns>
        public PutFileResponse Put(PutFileRequest request)
        {
            IEnumerable <MediaFolder> parentFolderFuture = null;

            if (request.Data.FolderId.HasValue)
            {
                parentFolderFuture = repository.AsQueryable <MediaFolder>()
                                     .Where(c => c.Id == request.Data.FolderId.Value && !c.IsDeleted)
                                     .ToFuture();
            }

            var mediaFile = repository.AsQueryable <MediaFile>()
                            .Where(file => file.Id == request.Id)
                            .FetchMany(f => f.AccessRules)
                            .ToFuture()
                            .FirstOrDefault();

            MediaFolder parentFolder = null;

            if (parentFolderFuture != null)
            {
                parentFolder = parentFolderFuture.First();
                if (parentFolder.Type != Module.MediaManager.Models.MediaType.File)
                {
                    throw new CmsApiValidationException("Folder must be type of an file.");
                }
            }

            var createFile = mediaFile == null;

            if (createFile)
            {
                mediaFile = new MediaFile
                {
                    Id          = request.Id.GetValueOrDefault(),
                    Type        = Module.MediaManager.Models.MediaType.File,
                    AccessRules = new List <AccessRule>()
                };
            }
            else if (request.Data.Version > 0)
            {
                mediaFile.Version = request.Data.Version;
            }

            unitOfWork.BeginTransaction();

            if (!createFile)
            {
                repository.Save(mediaFile.CreateHistoryItem());
            }

            mediaFile.Title                 = request.Data.Title;
            mediaFile.Description           = request.Data.Description;
            mediaFile.Size                  = request.Data.FileSize;
            mediaFile.PublicUrl             = request.Data.PublicUrl;
            mediaFile.Folder                = parentFolder;
            mediaFile.PublishedOn           = request.Data.PublishedOn;
            mediaFile.OriginalFileName      = request.Data.OriginalFileName;
            mediaFile.OriginalFileExtension = request.Data.OriginalFileExtension;

            mediaFile.Image = request.Data.ThumbnailId.GetValueOrDefault() != default(Guid)
                ? repository.AsProxy <MediaImage>(request.Data.ThumbnailId.Value)
                : null;

            mediaFile.FileUri     = new Uri(request.Data.FileUri);
            mediaFile.IsUploaded  = request.Data.IsUploaded;
            mediaFile.IsTemporary = request.Data.IsTemporary;
            mediaFile.IsCanceled  = request.Data.IsCanceled;

            var archivedMedias   = new List <Media>();
            var unarchivedMedias = new List <Media>();

            if (mediaFile.IsArchived != request.Data.IsArchived)
            {
                if (request.Data.IsArchived)
                {
                    archivedMedias.Add(mediaFile);
                    mediaService.ArchiveSubMedias(mediaFile, archivedMedias);
                }
                else
                {
                    unarchivedMedias.Add(mediaFile);
                    mediaService.UnarchiveSubMedias(mediaFile, unarchivedMedias);
                }
            }

            mediaFile.IsArchived = request.Data.IsArchived;

            IList <Tag> newTags = null;

            if (request.Data.Tags != null)
            {
                tagService.SaveMediaTags(mediaFile, request.Data.Tags, out newTags);
            }

            if (request.Data.AccessRules != null)
            {
                mediaFile.AccessRules.RemoveDuplicateEntities();
                var accessRules =
                    request.Data.AccessRules.Select(
                        r => (IAccessRule) new AccessRule {
                    AccessLevel = (Core.Security.AccessLevel)(int) r.AccessLevel, Identity = r.Identity, IsForRole = r.IsForRole
                })
                    .ToList();
                accessControlService.UpdateAccessControl(mediaFile, accessRules);
            }

            if (request.Data.Categories != null)
            {
                categoryService.CombineEntityCategories <Media, MediaCategory>(mediaFile, request.Data.Categories);
            }

            repository.Save(mediaFile);

            unitOfWork.Commit();

            // Fire events.
            Events.RootEvents.Instance.OnTagCreated(newTags);
            if (createFile)
            {
                Events.MediaManagerEvents.Instance.OnMediaFileUploaded(mediaFile);
            }
            else
            {
                Events.MediaManagerEvents.Instance.OnMediaFileUpdated(mediaFile);
            }

            foreach (var archivedMedia in archivedMedias.Distinct())
            {
                Events.MediaManagerEvents.Instance.OnMediaArchived(archivedMedia);
            }

            foreach (var archivedMedia in unarchivedMedias.Distinct())
            {
                Events.MediaManagerEvents.Instance.OnMediaUnarchived(archivedMedia);
            }

            return(new PutFileResponse
            {
                Data = mediaFile.Id
            });
        }
        /// <summary>
        /// Puts the specified request.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <returns><c>PutPageResponse</c> with created or updated item id.</returns>
        public PutPagePropertiesResponse Put(PutPagePropertiesRequest request)
        {
            if (request.Data.IsMasterPage)
            {
                accessControlService.DemandAccess(securityService.GetCurrentPrincipal(), RootModuleConstants.UserRoles.Administration);
            }
            else
            {
                accessControlService.DemandAccess(securityService.GetCurrentPrincipal(), RootModuleConstants.UserRoles.EditContent);
            }

            PageProperties pageProperties = null;

            var isNew = !request.Id.HasValue || request.Id.Value.HasDefaultValue();

            if (!isNew)
            {
                pageProperties =
                    repository.AsQueryable <PageProperties>(e => e.Id == request.Id.GetValueOrDefault())
                    .FetchMany(p => p.Options)
                    .Fetch(p => p.Layout)
                    .ThenFetchMany(l => l.LayoutOptions)
                    .FetchMany(p => p.MasterPages)
                    .FetchMany(f => f.AccessRules)
                    .ToList()
                    .FirstOrDefault();

                isNew = pageProperties == null;
            }
            UpdatingPagePropertiesModel beforeChange = null;

            if (isNew)
            {
                pageProperties = new PageProperties
                {
                    Id          = request.Id.GetValueOrDefault(),
                    Status      = PageStatus.Unpublished,
                    AccessRules = new List <AccessRule>()
                };
            }
            else if (request.Data.Version > 0)
            {
                pageProperties.Version = request.Data.Version;
            }

            if (!isNew)
            {
                beforeChange = new UpdatingPagePropertiesModel(pageProperties);
            }

            if (!isNew && pageProperties.IsMasterPage != request.Data.IsMasterPage)
            {
                const string message    = "IsMasterPage cannot be changed for updating page. It can be modified only when creating a page.";
                var          logMessage = string.Format("{0} PageId: {1}", message, request.Id);
                throw new ValidationException(() => message, logMessage);
            }

            // Load master pages for updating page's master path and page's children master path
            IList <Guid>       newMasterIds;
            IList <Guid>       oldMasterIds;
            IList <Guid>       childrenPageIds;
            IList <MasterPage> existingChildrenMasterPages;

            masterPageService.PrepareForUpdateChildrenMasterPages(pageProperties, request.Data.MasterPageId, out newMasterIds, out oldMasterIds, out childrenPageIds, out existingChildrenMasterPages);

            unitOfWork.BeginTransaction();

            if (!string.IsNullOrEmpty(request.Data.PageUrl) || string.IsNullOrEmpty(pageProperties.PageUrl))
            {
                var pageUrl = request.Data.PageUrl;
                if (string.IsNullOrEmpty(pageUrl) && !string.IsNullOrWhiteSpace(request.Data.Title))
                {
                    pageUrl = pageService.CreatePagePermalink(request.Data.Title, null, null, request.Data.LanguageId, request.Data.CategoryId);
                }
                else
                {
                    pageUrl = urlService.FixUrl(pageUrl);
                    pageService.ValidatePageUrl(pageUrl, request.Id);
                }

                pageProperties.PageUrl     = pageUrl;
                pageProperties.PageUrlHash = pageUrl.UrlHash();
            }

            pageProperties.Title       = request.Data.Title;
            pageProperties.Description = request.Data.Description;

            var newStatus = request.Data.IsMasterPage || request.Data.IsPublished ? PageStatus.Published : PageStatus.Unpublished;

            if (!request.Data.IsMasterPage && pageProperties.Status != newStatus)
            {
                accessControlService.DemandAccess(securityService.GetCurrentPrincipal(), RootModuleConstants.UserRoles.PublishContent);
            }

            pageProperties.Status      = newStatus;
            pageProperties.PublishedOn = request.Data.IsPublished && !request.Data.PublishedOn.HasValue ? DateTime.Now : request.Data.PublishedOn;

            masterPageService.SetMasterOrLayout(pageProperties, request.Data.MasterPageId, request.Data.LayoutId);

            pageProperties.Category = request.Data.CategoryId.HasValue
                                    ? repository.AsProxy <Category>(request.Data.CategoryId.Value)
                                    : null;
            pageProperties.IsArchived              = request.Data.IsArchived;
            pageProperties.IsMasterPage            = request.Data.IsMasterPage;
            pageProperties.LanguageGroupIdentifier = request.Data.LanguageGroupIdentifier;
            pageProperties.Language = request.Data.LanguageId.HasValue && !request.Data.LanguageId.Value.HasDefaultValue()
                                    ? repository.AsProxy <Language>(request.Data.LanguageId.Value)
                                    : null;

            pageProperties.Image = request.Data.MainImageId.HasValue
                                    ? repository.AsProxy <MediaImage>(request.Data.MainImageId.Value)
                                    : null;
            pageProperties.FeaturedImage = request.Data.FeaturedImageId.HasValue
                                    ? repository.AsProxy <MediaImage>(request.Data.FeaturedImageId.Value)
                                    : null;
            pageProperties.SecondaryImage = request.Data.SecondaryImageId.HasValue
                                    ? repository.AsProxy <MediaImage>(request.Data.SecondaryImageId.Value)
                                    : null;

            pageProperties.CustomCss       = request.Data.CustomCss;
            pageProperties.CustomJS        = request.Data.CustomJavaScript;
            pageProperties.UseCanonicalUrl = request.Data.UseCanonicalUrl;
            pageProperties.UseNoFollow     = request.Data.UseNoFollow;
            pageProperties.UseNoIndex      = request.Data.UseNoIndex;

            if (request.Data.MetaData != null)
            {
                pageProperties.MetaTitle       = request.Data.MetaData.MetaTitle;
                pageProperties.MetaDescription = request.Data.MetaData.MetaDescription;
                pageProperties.MetaKeywords    = request.Data.MetaData.MetaKeywords;
            }

            IList <Tag> newTags = null;

            if (request.Data.Tags != null)
            {
                tagService.SavePageTags(pageProperties, request.Data.Tags, out newTags);
            }

            if (request.Data.AccessRules != null)
            {
                pageProperties.AccessRules.RemoveDuplicateEntities();
                var accessRules =
                    request.Data.AccessRules.Select(
                        r => (IAccessRule) new AccessRule {
                    AccessLevel = (Core.Security.AccessLevel)(int) r.AccessLevel, Identity = r.Identity, IsForRole = r.IsForRole
                })
                    .ToList();
                accessControlService.UpdateAccessControl(pageProperties, accessRules);
            }

            if (request.Data.PageOptions != null)
            {
                var options = request.Data.PageOptions.ToServiceModel();

                var pageOptions = pageProperties.Options != null?pageProperties.Options.Distinct() : null;

                pageProperties.Options = optionService.SaveOptionValues(options, pageOptions, () => new PageOption {
                    Page = pageProperties
                });
            }

            if (!isNew)
            {
                // Notify about page properties changing.
                var cancelEventArgs = Events.PageEvents.Instance.OnPagePropertiesChanging(beforeChange, new UpdatingPagePropertiesModel(pageProperties));
                if (cancelEventArgs.Cancel)
                {
                    throw new CmsApiValidationException(
                              cancelEventArgs.CancellationErrorMessages != null && cancelEventArgs.CancellationErrorMessages.Count > 0
                            ? string.Join(",", cancelEventArgs.CancellationErrorMessages)
                            : "Page properties saving was canceled.");
                }
            }

            repository.Save(pageProperties);

            //
            // If creating new page, page id is unknown when children pages are loaded, so Guid may be empty
            // Updating id to saved page's Id manually
            //
            if (isNew && childrenPageIds != null && childrenPageIds.Count == 1 && childrenPageIds[0].HasDefaultValue())
            {
                childrenPageIds[0] = pageProperties.Id;
            }

            masterPageService.UpdateChildrenMasterPages(existingChildrenMasterPages, oldMasterIds, newMasterIds, childrenPageIds);

            unitOfWork.Commit();

            // Fire events.
            Events.RootEvents.Instance.OnTagCreated(newTags);
            if (isNew)
            {
                Events.PageEvents.Instance.OnPageCreated(pageProperties);
            }
            else
            {
                Events.PageEvents.Instance.OnPagePropertiesChanged(pageProperties);
            }

            return(new PutPagePropertiesResponse {
                Data = pageProperties.Id
            });
        }
        /// <summary>
        /// Executes the specified request.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <returns>Save response.</returns>
        /// <exception cref="CmsException">Failed to save page properties.</exception>
        public SavePageResponse Execute(EditPagePropertiesViewModel request)
        {
            var isMultilanguageEnabled = cmsConfiguration.EnableMultilanguage;

            ValidateRequest(request, isMultilanguageEnabled);

            var pageQuery =
                Repository.AsQueryable <PageProperties>(p => p.Id == request.Id)
                .FetchMany(p => p.Options)
                .Fetch(p => p.Layout)
                .ThenFetchMany(l => l.LayoutOptions)
                .FetchMany(p => p.MasterPages)
                .AsQueryable();

            if (cmsConfiguration.Security.AccessControlEnabled)
            {
                pageQuery = pageQuery.FetchMany(f => f.AccessRules);
            }

            var page         = pageQuery.ToList().FirstOne();
            var beforeChange = new UpdatingPagePropertiesModel(page);

            var roles = page.IsMasterPage
                            ? new[]
            {
                RootModuleConstants.UserRoles.EditContent, RootModuleConstants.UserRoles.PublishContent, RootModuleConstants.UserRoles.Administration
            }
                            : new[] { RootModuleConstants.UserRoles.EditContent, RootModuleConstants.UserRoles.PublishContent };

            if (cmsConfiguration.Security.AccessControlEnabled)
            {
                AccessControlService.DemandAccess(page, Context.Principal, AccessLevel.ReadWrite, roles);
            }
            else
            {
                AccessControlService.DemandAccess(Context.Principal, roles);
            }

            var canEdit = page.IsMasterPage
                              ? SecurityService.IsAuthorized(
                Context.Principal,
                RootModuleConstants.UserRoles.MultipleRoles(RootModuleConstants.UserRoles.EditContent, RootModuleConstants.UserRoles.Administration))
                              : SecurityService.IsAuthorized(Context.Principal, RootModuleConstants.UserRoles.EditContent);

            IList <PageProperties> translations = null;

            if (canEdit && isMultilanguageEnabled && !page.IsMasterPage)
            {
                translations = LoadAndValidateTranslations(page, request);
            }

            // Load master pages for updating page's master path and page's children master path
            IList <Guid>       newMasterIds;
            IList <Guid>       oldMasterIds;
            IList <Guid>       childrenPageIds;
            IList <MasterPage> existingChildrenMasterPages;

            masterPageService.PrepareForUpdateChildrenMasterPages(page, request.MasterPageId, out newMasterIds, out oldMasterIds, out childrenPageIds, out existingChildrenMasterPages);

            IList <SitemapNode> updatedNodes = null;

            // Start transaction, only when everything is already loaded
            UnitOfWork.BeginTransaction();

            Models.Redirect redirectCreated  = null;
            var             initialSeoStatus = page.HasSEO;

            request.PageUrl = urlService.FixUrl(request.PageUrl);

            if (canEdit && !string.Equals(page.PageUrl, request.PageUrl))
            {
                pageService.ValidatePageUrl(request.PageUrl, request.Id);
                if (request.RedirectFromOldUrl)
                {
                    var redirect = redirectService.CreateRedirectEntity(page.PageUrl, request.PageUrl);
                    if (redirect != null)
                    {
                        Repository.Save(redirect);
                        redirectCreated = redirect;
                    }
                }

                if (request.UpdateSitemap)
                {
                    updatedNodes = sitemapService.ChangeUrlsInAllSitemapsNodes(page.PageUrl, request.PageUrl);
                }

                page.PageUrl = request.PageUrl;
            }

            List <PageProperties> updatePageTranslations = null;

            if (canEdit)
            {
                page.PageUrlHash         = page.PageUrl.UrlHash();
                page.ForceAccessProtocol = request.ForceAccessProtocol;

                categoryService.CombineEntityCategories <PageProperties, PageCategory>(page, request.Categories);

                page.Title     = request.PageName;
                page.CustomCss = request.PageCSS;
                page.CustomJS  = request.PageJavascript;

                masterPageService.SetMasterOrLayout(page, request.MasterPageId, request.TemplateId);

                if (isMultilanguageEnabled && !page.IsMasterPage)
                {
                    updatePageTranslations = UpdatePageTranslations(page, translations, request);
                }
            }

            var publishDraftContent = false;

            if (request.CanPublishPage && !page.IsMasterPage)
            {
                AccessControlService.DemandAccess(Context.Principal, RootModuleConstants.UserRoles.PublishContent);

                if (request.IsPagePublished)
                {
                    if (page.Status != PageStatus.Published)
                    {
                        page.Status         = PageStatus.Published;
                        page.PublishedOn    = DateTime.Now;
                        publishDraftContent = true;
                    }
                }
                else
                {
                    page.Status = PageStatus.Unpublished;
                }
            }

            IList <PageOption> pageOptions = page.Options.Distinct().ToList();

            if (canEdit)
            {
                if (!page.IsMasterPage)
                {
                    page.UseNoFollow = request.UseNoFollow;
                    page.UseNoIndex  = request.UseNoIndex;
                    page.IsArchived  = request.IsArchived;
                }

                page.UseCanonicalUrl = request.UseCanonicalUrl;
                page.Version         = request.Version;

                page.Image          = request.Image != null && request.Image.ImageId.HasValue ? Repository.AsProxy <MediaImage>(request.Image.ImageId.Value) : null;
                page.SecondaryImage = request.SecondaryImage != null && request.SecondaryImage.ImageId.HasValue
                                          ? Repository.AsProxy <MediaImage>(request.SecondaryImage.ImageId.Value)
                                          : null;
                page.FeaturedImage = request.FeaturedImage != null && request.FeaturedImage.ImageId.HasValue
                                         ? Repository.AsProxy <MediaImage>(request.FeaturedImage.ImageId.Value)
                                         : null;

                pageOptions = optionService.SaveOptionValues(request.OptionValues, pageOptions, () => new PageOption {
                    Page = page
                });

                if (cmsConfiguration.Security.AccessControlEnabled)
                {
                    page.AccessRules.RemoveDuplicateEntities();

                    var accessRules = request.UserAccessList != null?request.UserAccessList.Cast <IAccessRule>().ToList() : null;

                    accessControlService.UpdateAccessControl(page, accessRules);
                }
            }

            // Notify about page properties changing.
            var cancelEventArgs = Events.PageEvents.Instance.OnPagePropertiesChanging(beforeChange, new UpdatingPagePropertiesModel(page));

            if (cancelEventArgs.Cancel)
            {
                Context.Messages.AddError(cancelEventArgs.CancellationErrorMessages.ToArray());
                return(null);
            }

            Repository.Save(page);

            IList <Tag> newTags = null;

            if (canEdit)
            {
                masterPageService.UpdateChildrenMasterPages(existingChildrenMasterPages, oldMasterIds, newMasterIds, childrenPageIds);
                tagService.SavePageTags(page, request.Tags, out newTags);
            }

            if (publishDraftContent)
            {
                contentService.PublishDraftContent(page.Id);
            }

            UnitOfWork.Commit();

            // Notify about page properties change.
            page.Options = pageOptions;
            Events.PageEvents.Instance.OnPagePropertiesChanged(page);

            // Notify about translation properties changed
            if (updatePageTranslations != null)
            {
                updatePageTranslations.ForEach(Events.PageEvents.Instance.OnPagePropertiesChanged);
            }

            // Notify about redirect creation.
            if (redirectCreated != null)
            {
                Events.PageEvents.Instance.OnRedirectCreated(redirectCreated);
            }

            // Notify about SEO status change.
            if (initialSeoStatus != page.HasSEO)
            {
                Events.PageEvents.Instance.OnPageSeoStatusChanged(page);
            }

            // Notify about new tags.
            Events.RootEvents.Instance.OnTagCreated(newTags);

            // Notify about updated sitemap nodes.
            if (updatedNodes != null)
            {
                var updatedSitemaps = new List <Models.Sitemap>();
                foreach (var node in updatedNodes)
                {
                    Events.SitemapEvents.Instance.OnSitemapNodeUpdated(node);
                    if (!updatedSitemaps.Contains(node.Sitemap))
                    {
                        updatedSitemaps.Add(node.Sitemap);
                    }
                }

                foreach (var updatedSitemap in updatedSitemaps)
                {
                    Events.SitemapEvents.Instance.OnSitemapUpdated(updatedSitemap);
                }
            }

            return(new SavePageResponse(page));
        }
Example #11
0
        /// <summary>
        /// Executes this command.
        /// </summary>
        public ConfirmUploadResponse Execute(MultiFileUploadViewModel request)
        {
            ConfirmUploadResponse response = new ConfirmUploadResponse {
                SelectedFolderId = request.SelectedFolderId ?? Guid.Empty, ReuploadMediaId = request.ReuploadMediaId
            };

            if (request.UploadedFiles != null && request.UploadedFiles.Count > 0)
            {
                MediaFolder folder = null;

                if (request.SelectedFolderId != null && request.SelectedFolderId.Value != Guid.Empty)
                {
                    folder = Repository.AsProxy <MediaFolder>(request.SelectedFolderId.Value);
                    if (folder.IsDeleted)
                    {
                        response.FolderIsDeleted = true;
                        return(response);
                    }
                }

                UnitOfWork.BeginTransaction();

                List <MediaFile> files  = new List <MediaFile>();
                var updateAccessControl = true;

                if (request.ReuploadMediaId.HasDefaultValue())
                {
                    UpdateMedia(request, folder, files);
                }
                else
                {
                    // Re-upload performed.
                    var fileId = request.UploadedFiles.FirstOrDefault();
                    var file   = Repository.FirstOrDefault <MediaFile>(fileId);

                    if (!fileId.HasDefaultValue())
                    {
                        var originalMedia = Repository.First <MediaFile>(request.ReuploadMediaId);
                        if (cmsConfiguration.Security.AccessControlEnabled && !(originalMedia is IAccessControlDisabled))
                        {
                            AccessControlService.DemandAccess(originalMedia, Context.Principal, AccessLevel.ReadWrite);
                        }

                        file.Original = originalMedia;

                        // Do not update access control, if re-uploading
                        updateAccessControl = false;

                        file.Title       = originalMedia.Title;
                        file.Description = originalMedia.Description;
                        file.IsArchived  = originalMedia.IsArchived;
                        file.Folder      = originalMedia.Folder;
                        file.Image       = originalMedia.Image;
                        if (file is MediaImage && originalMedia is MediaImage)
                        {
                            ((MediaImage)file).Caption    = ((MediaImage)originalMedia).Caption;
                            ((MediaImage)file).ImageAlign = ((MediaImage)originalMedia).ImageAlign;
                        }

                        file.IsTemporary = false;
                        file.PublishedOn = DateTime.Now;

                        var temp = (MediaFile)file.Clone();
                        originalMedia.CopyDataTo(file);
                        temp.CopyDataTo(originalMedia);
                        files.Add(originalMedia);
                    }
                }

                if (updateAccessControl && cmsConfiguration.Security.AccessControlEnabled)
                {
                    foreach (var file in files)
                    {
                        if (!(file is MediaImage))
                        {
                            var currentFile = file;
                            var fileEntity  = Repository.AsQueryable <MediaFile>().Where(f => f.Id == currentFile.Id).FetchMany(f => f.AccessRules).ToList().FirstOne();

                            accessControlService.UpdateAccessControl(
                                fileEntity, request.UserAccessList != null ? request.UserAccessList.Cast <IAccessRule>().ToList() : new List <IAccessRule>());
                        }
                    }
                }

                UnitOfWork.Commit();

                if (request.ReuploadMediaId.HasDefaultValue())
                {
                    foreach (var file in files)
                    {
                        if (file is MediaImage)
                        {
                            file.PublicUrl += string.Format("?{0}", DateTime.Now.ToString(MediaManagerModuleDescriptor.HardLoadImageDateTimeFormat));
                            ((MediaImage)file).PublicThumbnailUrl += string.Format("?{0}", DateTime.Now.ToString(MediaManagerModuleDescriptor.HardLoadImageDateTimeFormat));
                        }
                    }
                }

                response.Medias = files.Select(Convert).ToList();

                // Notify.
                foreach (var mediaFile in files)
                {
                    Events.MediaManagerEvents.Instance.OnMediaFileUpdated(mediaFile);
                }
            }

            return(response);
        }
Example #12
0
        /// <summary>
        /// Upload file from the stream.
        /// </summary>
        /// <param name="request">The upload file request.</param>
        /// <returns>The upload file response.</returns>
        public UploadFileResponse Post(UploadFileRequest request)
        {
            MediaFolder parentFolder = null;

            if (request.Data.FolderId.HasValue)
            {
                parentFolder = repository.AsQueryable <MediaFolder>()
                               .Where(c => c.Id == request.Data.FolderId.Value && !c.IsDeleted)
                               .FirstOne();

                if (parentFolder.Type != Module.MediaManager.Models.MediaType.File)
                {
                    throw new CmsApiValidationException("Folder must be type of an file.");
                }
            }

            var maxLength = configuration.Storage.MaximumFileNameLength > 0 ? configuration.Storage.MaximumFileNameLength : 100;
            // Fix for IIS express + IE (if full path is returned)
            var fileName = Path.GetFileName(request.Data.FileName);

            if (fileName.Length > maxLength)
            {
                fileName = string.Concat(Path.GetFileNameWithoutExtension(fileName.Substring(0, maxLength)), Path.GetExtension(fileName));
            }

            var savedFile = mediaFileService.UploadFileWithStream(
                Module.MediaManager.Models.MediaType.File,
                parentFolder != null ? parentFolder.Id : Guid.Empty,
                fileName,
                request.Data.FileStream.Length,
                request.Data.FileStream,
                request.Data.WaitForUploadResult,
                request.Data.Title,
                request.Data.Description);

            if (savedFile != null)
            {
                if (request.Data.AccessRules != null)
                {
                    if (savedFile.AccessRules != null)
                    {
                        savedFile.AccessRules.RemoveDuplicateEntities();
                    }
                    var accessRules =
                        request.Data.AccessRules.Select(
                            r => (IAccessRule) new AccessRule {
                        AccessLevel = (AccessLevel)(int)r.AccessLevel, Identity = r.Identity, IsForRole = r.IsForRole
                    })
                        .ToList();
                    accessControlService.UpdateAccessControl(savedFile, accessRules);
                    mediaFileService.SaveMediaFile(savedFile);
                }

                Events.MediaManagerEvents.Instance.OnMediaFileUploaded(savedFile);
            }

            return(new UploadFileResponse
            {
                Data = savedFile.Id
            });
        }
Example #13
0
        /// <summary>
        /// Executes the specified request.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <returns>Save response.</returns>
        /// <exception cref="CmsException">Failed to save page properties.</exception>
        public SavePageResponse Execute(EditPagePropertiesViewModel request)
        {
            UnitOfWork.BeginTransaction();

            var page = Repository
                       .AsQueryable <PageProperties>(p => p.Id == request.Id)
                       .FetchMany(p => p.Options)
                       .Fetch(p => p.Layout).ThenFetchMany(l => l.LayoutOptions)
                       .ToList()
                       .FirstOrDefault();

            Models.Redirect redirectCreated  = null;
            bool            initialSeoStatus = page.HasSEO;

            request.PageUrl = urlService.FixUrl(request.PageUrl);

            if (!string.Equals(page.PageUrl, request.PageUrl))
            {
                pageService.ValidatePageUrl(request.PageUrl, request.Id);
                if (request.RedirectFromOldUrl)
                {
                    var redirect = redirectService.CreateRedirectEntity(page.PageUrl, request.PageUrl);
                    if (redirect != null)
                    {
                        Repository.Save(redirect);
                        redirectCreated = redirect;
                    }
                }

                page.NodeCountInSitemap = request.UpdateSitemap
                    ? sitemapService.ChangeUrl(page.PageUrl, request.PageUrl)
                    : sitemapService.NodesWithUrl(request.PageUrl);

                page.PageUrl = request.PageUrl;
            }

            page.PageUrlLowerTrimmed = page.PageUrl.LowerTrimmedUrl();
            page.Layout    = Repository.AsProxy <Root.Models.Layout>(request.TemplateId);
            page.Category  = request.CategoryId.HasValue ? Repository.AsProxy <CategoryEntity>(request.CategoryId.Value) : null;
            page.Title     = request.PageName;
            page.CustomCss = request.PageCSS;
            page.CustomJS  = request.PageJavascript;

            if (request.IsVisibleToEveryone)
            {
                page.Status      = PageStatus.Published;
                page.PublishedOn = DateTime.Now;
            }
            else
            {
                page.Status = PageStatus.Unpublished;
            }

            page.UseNoFollow     = request.UseNoFollow;
            page.UseNoIndex      = request.UseNoIndex;
            page.UseCanonicalUrl = request.UseCanonicalUrl;
            page.IsArchived      = request.IsArchived;
            page.Version         = request.Version;

            page.Image          = request.Image != null && request.Image.ImageId.HasValue ? Repository.AsProxy <MediaImage>(request.Image.ImageId.Value) : null;
            page.SecondaryImage = request.SecondaryImage != null && request.SecondaryImage.ImageId.HasValue ? Repository.AsProxy <MediaImage>(request.SecondaryImage.ImageId.Value) : null;
            page.FeaturedImage  = request.FeaturedImage != null && request.FeaturedImage.ImageId.HasValue ? Repository.AsProxy <MediaImage>(request.FeaturedImage.ImageId.Value) : null;

            var optionValues  = page.Options.Distinct();
            var parentOptions = page.Layout.LayoutOptions.Distinct();

            optionService.SaveOptionValues(request.OptionValues, optionValues, parentOptions, () => new Root.Models.PageOption {
                Page = page
            });

            if (cmsConfiguration.AccessControlEnabled)
            {
                accessControlService.UpdateAccessControl(request.UserAccessList, request.Id);
            }

            Repository.Save(page);

            // Save tags
            IList <Root.Models.Tag> newTags;

            tagService.SavePageTags(page, request.Tags, out newTags);

            UnitOfWork.Commit();

            // Notify about page properties change.
            Events.PageEvents.Instance.OnPagePropertiesChanged(page);

            // Notify about redirect creation.
            if (redirectCreated != null)
            {
                Events.PageEvents.Instance.OnRedirectCreated(redirectCreated);
            }

            // Notify about SEO status change.
            if (initialSeoStatus != page.HasSEO)
            {
                Events.PageEvents.Instance.OnPageSeoStatusChanged(page);
            }

            // Notify about new tags.
            Events.RootEvents.Instance.OnTagCreated(newTags);

            return(new SavePageResponse(page));
        }
Example #14
0
        /// <summary>
        /// Puts the sitemap specified in request.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <returns>
        ///   <c>PutSitemapsResponse</c> with updated sitemap data.
        /// </returns>
        public PutSitemapResponse Put(PutSitemapRequest request)
        {
            IEnumerable <SitemapNode> nodesFuture = null;

            if (request.Data.Nodes != null)
            {
                nodesFuture =
                    repository.AsQueryable <SitemapNode>()
                    .Where(node => node.Sitemap.Id == request.Id && !node.IsDeleted)
                    .FetchMany(node => node.Translations)
                    .ToFuture();
            }

            var sitemap =
                repository.AsQueryable <Module.Pages.Models.Sitemap>(e => e.Id == request.Id.GetValueOrDefault())
                .FetchMany(f => f.AccessRules)
                .ToFuture()
                .ToList()
                .FirstOrDefault();

            var isNew = sitemap == null;

            if (isNew)
            {
                sitemap = new Module.Pages.Models.Sitemap {
                    Id = request.Id.GetValueOrDefault(), AccessRules = new List <AccessRule>()
                };
            }
            else if (request.Data.Version > 0)
            {
                sitemap.Version = request.Data.Version;
            }

            if (cmsConfiguration.Security.AccessControlEnabled)
            {
                accessControlService.DemandAccess(sitemap, securityService.GetCurrentPrincipal(), AccessLevel.ReadWrite);
            }

            unitOfWork.BeginTransaction();

            if (!isNew)
            {
                sitemapService.ArchiveSitemap(sitemap.Id);
            }

            sitemap.Title = request.Data.Title;

            IList <Tag> newTags = null;

            if (request.Data.Tags != null)
            {
                tagService.SaveTags(sitemap, request.Data.Tags, out newTags);
            }

            if (request.Data.AccessRules != null)
            {
                sitemap.AccessRules.RemoveDuplicateEntities();
                var accessRules =
                    request.Data.AccessRules.Select(
                        r => (IAccessRule) new AccessRule {
                    AccessLevel = (AccessLevel)(int)r.AccessLevel, Identity = r.Identity, IsForRole = r.IsForRole
                })
                    .ToList();
                accessControlService.UpdateAccessControl(sitemap, accessRules);
            }

            repository.Save(sitemap);

            var createdNodes = (IList <SitemapNode>) new List <SitemapNode>();
            var updatedNodes = (IList <SitemapNode>) new List <SitemapNode>();
            var deletedNodes = (IList <SitemapNode>) new List <SitemapNode>();

            if (request.Data.Nodes != null)
            {
                SaveNodes(sitemap, request.Data.Nodes, nodesFuture != null ? nodesFuture.ToList() : new List <SitemapNode>(), ref createdNodes, ref updatedNodes, ref deletedNodes);
            }

            unitOfWork.Commit();

            // Fire events.
            Events.RootEvents.Instance.OnTagCreated(newTags);
            foreach (var node in createdNodes)
            {
                Events.SitemapEvents.Instance.OnSitemapNodeCreated(node);
            }

            foreach (var node in updatedNodes)
            {
                Events.SitemapEvents.Instance.OnSitemapNodeUpdated(node);
            }

            foreach (var node in deletedNodes)
            {
                Events.SitemapEvents.Instance.OnSitemapNodeDeleted(node);
            }

            if (isNew)
            {
                Events.SitemapEvents.Instance.OnSitemapCreated(sitemap);
            }
            else
            {
                Events.SitemapEvents.Instance.OnSitemapUpdated(sitemap);
            }

            return(new PutSitemapResponse {
                Data = sitemap.Id
            });
        }