Beispiel #1
0
        ///// <summary>
        ///// This is a deprecated function for when multiple items was enabled. It was poorly implemented and has been removed as of 2.3.0.0
        ///// </summary>
        ///// <param name="sender"></param>
        ///// <param name="e"></param>
        //private void btnDelete_Click(object sender, EventArgs e)
        //{
        //    //if(this.itemId > -1)
        //    if(html != null)
        //    {
        //        //HtmlContent htmlContent = new HtmlContent(this.moduleId, this.itemId);
        //        //htmlContent.ContentChanged += new ContentChangedEventHandler(html_ContentChanged);
        //        //htmlContent.Delete();
        //        html.ContentChanged += new ContentChangedEventHandler(html_ContentChanged);
        //        repository.Delete(html);
        //        CurrentPage.UpdateLastModifiedTime();
        //        SiteUtils.QueueIndexing();
        //    }
        //    if (hdnReturnUrl.Value.Length > 0)
        //    {
        //        WebUtils.SetupRedirect(this, hdnReturnUrl.Value);
        //        return;
        //    }

        //    WebUtils.SetupRedirect(this, SiteUtils.GetCurrentPageUrl());

        //}



        //private void btnCancel_Click(Object sender, EventArgs e)
        //{
        //    if (hdnReturnUrl.Value.Length > 0)
        //    {
        //        WebUtils.SetupRedirect(this, hdnReturnUrl.Value);
        //        return;
        //    }

        //    WebUtils.SetupRedirect(this, SiteUtils.GetCurrentPageUrl());
        //}

        private void BindHistory()
        {
            if ((html == null))
            {
                pnlHistory.Visible = false;
                return;
            }

            if ((module != null) && (html.ModuleGuid == Guid.Empty))
            {
                html.ModuleGuid = module.ModuleGuid;
            }


            List <ContentHistory> history = ContentHistory.GetPage(html.ModuleGuid, pageNumber, pageSize, out totalPages);

            pgrHistory.ShowFirstLast = true;
            pgrHistory.PageSize      = pageSize;
            pgrHistory.PageCount     = totalPages;
            pgrHistory.Visible       = (this.totalPages > 1);

            grdHistory.DataSource = history;
            grdHistory.DataBind();

            btnDeleteHistory.Visible = (grdHistory.Rows.Count > 0);
            pnlHistory.Visible       = (grdHistory.Rows.Count > 0);
        }
 public static int Insert(ContentHistory contentHistory)
 {
     return((int)(decimal)Execute($@"
         INSERT INTO [dbo].[ContentHistory] (ContentId, Field, OldValue, Changed, ChangedBy) 
         VALUES ( '{contentHistory.ContentId}', '{contentHistory.ChangedField}', '{contentHistory.OldValue.SqlEncode()}', '{FormatDate(contentHistory.Changed)}', '{contentHistory.ChangedByUserId}'); 
         SELECT SCOPE_IDENTITY();"));
 }
Beispiel #3
0
        void grdHistory_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            string g = e.CommandArgument.ToString();

            if (g.Length != 36)
            {
                return;
            }
            Guid historyGuid = new Guid(g);

            switch (e.CommandName)
            {
            case "RestoreToEditor":
                ContentHistory history = new ContentHistory(historyGuid);
                if (history.Guid == Guid.Empty)
                {
                    return;
                }

                edContent.Text = history.ContentText;
                BindHistory();
                break;

            case "DeleteHistory":
                ContentHistory.Delete(historyGuid);
                BindHistory();
                break;

            default:

                break;
            }
        }
 public ContentHistoryViewModel(ContentHistory contentHistory)
 {
     Changed      = contentHistory.Changed;
     ChangedField = contentHistory.ChangedField;
     OldValue     = contentHistory.OldValue;
     ChangedBy    = UserApi.GetById(contentHistory.ChangedByUserId);
 }
Beispiel #5
0
        private void ShowVsHistory()
        {
            HtmlContent    html    = repository.Fetch(moduleId);
            ContentHistory history = new ContentHistory(historyGuid);

            if (history.ContentGuid != html.ModuleGuid)
            {
                return;
            }

            litCurrentHeading.Text = string.Format(Resource.CurrentVersionHeadingFormat,
                                                   DateTimeHelper.Format(html.LastModUtc, timeZone, "g", timeOffset));

            if ((HtmlConfiguration.UseHtmlDiff) && (highlightDiff))
            {
                HtmlDiff diffHelper = new HtmlDiff(history.ContentText, html.Body);
                litCurrentVersion.Text = diffHelper.Build();
            }
            else
            {
                litCurrentVersion.Text = html.Body;
            }

            litHistoryHead.Text = string.Format(Resource.VersionAsOfHeadingFormat,
                                                DateTimeHelper.Format(history.CreatedUtc, timeZone, "g", timeOffset));



            litHistoryVersion.Text = history.ContentText;

            string onClick = "top.window.LoadHistoryInEditor('" + historyGuid.ToString() + "');  return false;";

            btnRestore.Attributes.Add("onclick", onClick);
        }
Beispiel #6
0
        public override void DeleteContent(int moduleId, Guid moduleGuid)
        {
            ContentHistory.DeleteByContent(moduleGuid);
            ContentWorkflow.DeleteByModule(moduleGuid);
            HtmlRepository repository = new HtmlRepository();

            repository.DeleteByModule(moduleId);
        }
        /// <summary>
        /// Gets the node by identifier.
        /// </summary>
        /// <param name="id">The identifier.</param>
        /// <returns>The content node.</returns>
        public ContentHistory GetNodeById(int id, string userLocale)
        {
            // Get the Umbraco db
            var db = ApplicationContext.DatabaseContext.Database;

            // Gets the content being visualized from the approveit DB
            IList <ChangeHistory> changeHistoryArray = db.Fetch <ChangeHistory>(
                string.Format("SELECT * FROM {0} WHERE [nodeId]=@0", Settings.APPROVE_IT_CHANGE_HISTORY_TABLE),
                id);

            // Get content being visualized
            IContent content = ApplicationContext.Services.ContentService.GetById(id);

            CultureInfo userCulture = new CultureInfo(userLocale);

            // Start the nodes to remove list
            IList <int> nodesToRemove = new List <int>();

            if (content != null)
            {
                ContentHistory currentContent = new ContentHistory()
                {
                    Name       = content.Name,
                    Id         = content.Id,
                    Properties = new List <PropertyHistory>()
                };

                foreach (ChangeHistory change in changeHistoryArray)
                {
                    // Get the user that updated the content
                    IUser writer = ApplicationContext.Services.UserService.GetByUsername(change.UpdatedBy);

                    currentContent.Properties.Add(new PropertyHistory()
                    {
                        Alias       = change.PropertyAlias,
                        AuthorEmail = writer.Email,
                        AuthorName  = writer.Username,
                        ChangeDate  = change.UpdateDate.ToString("F", userCulture),
                        Id          = change.Id
                    });
                }

                return(currentContent);
            }
            else
            {
                // It has been removed from the content tree, add it to a list to remove it from the db
                if (!nodesToRemove.Contains(id))
                {
                    nodesToRemove.Add(id);
                }

                return(null);
            }
        }
Beispiel #8
0
 public Task <ContentSnapshot> HistoryToContentAsync(ContentHistory history)
 {
     if (history.snapshotVersion == 1)
     {
         return(ExtractV1Snapshot <ContentSnapshot>(history.snapshot));
     }
     else
     {
         throw new InvalidOperationException($"Unknown snapshot version {history.snapshotVersion}");
     }
 }
Beispiel #9
0
        void btnDeleteHistory_Click(object sender, EventArgs e)
        {
            if (html == null)
            {
                return;
            }

            ContentHistory.DeleteByContent(html.ModuleGuid);
            BindHistory();
            updHx.Update();
        }
 public async Task Create(
     string projectId,
     ContentHistory contentHistory,
     CancellationToken cancellationToken = default(CancellationToken)
     )
 {
     using (var _db = _contextFactory.CreateContext())
     {
         _db.ContentHistory.Add(contentHistory);
         int rowsAffected = await _db.SaveChangesAsync().ConfigureAwait(false);
     }
 }
Beispiel #11
0
        private void PopulateControls()
        {
            if (moduleId == -1)
            {
                return;
            }
            if (itemId == -1)
            {
                return;
            }
            //if (module == null) { return; }
            if (historyGuid == Guid.Empty)
            {
                return;
            }

            Blog blog = new Blog(itemId);

            if (blog.ModuleId != moduleId)
            {
                SiteUtils.RedirectToAccessDeniedPage(this);
                return;
            }

            ContentHistory history = new ContentHistory(historyGuid);

            if (history.ContentGuid != blog.BlogGuid)
            {
                return;
            }

            litCurrentHeading.Text = string.Format(BlogResources.CurrentVersionHeadingFormat,
                                                   DateTimeHelper.Format(blog.LastModUtc, timeZone, "g", timeOffset));

            if (BlogConfiguration.UseHtmlDiff)
            {
                HtmlDiff diffHelper = new HtmlDiff(history.ContentText, blog.Description);
                litCurrentVersion.Text = diffHelper.Build();
            }
            else
            {
                litCurrentVersion.Text = blog.Description;
            }

            litHistoryHead.Text = string.Format(BlogResources.VersionAsOfHeadingFormat,
                                                DateTimeHelper.Format(history.CreatedUtc, timeZone, "g", timeOffset));

            litHistoryVersion.Text = history.ContentText;

            string onClick = "top.window.LoadHistoryInEditor('" + historyGuid.ToString() + "');  return false;";

            btnRestore.Attributes.Add("onclick", onClick);
        }
        public override void DeleteSiteContent(int siteId)
        {
            SiteSettings siteSettings = new SiteSettings(siteId);

            CommerceReport.DeleteBySite(siteSettings.SiteGuid);
            FileAttachment.DeleteBySite(siteSettings.SiteGuid);
            EmailSendLog.DeleteBySite(siteSettings.SiteGuid);
            EmailTemplate.DeleteBySite(siteSettings.SiteGuid);
            ContentHistory.DeleteBySite(siteSettings.SiteGuid);
            ContentWorkflow.DeleteBySite(siteSettings.SiteGuid);
            ContentMetaRespository metaRepository = new ContentMetaRespository();

            metaRepository.DeleteBySite(siteSettings.SiteGuid);
        }
Beispiel #13
0
    public async Task <ContentHistory> ContentToHistoryAsync(ContentSnapshot content, long user, UserAction action, DateTime?specificTime = null)
    {
        var history = new ContentHistory()
        {
            action          = action,
            createDate      = specificTime ?? DateTime.UtcNow,
            createUserId    = user,
            contentId       = content.id,
            snapshotVersion = 1,
            snapshot        = await GetV1Snapshot(content)
        };

        return(history);
    }
Beispiel #14
0
 public async Task Create(
     string projectId,
     ContentHistory contentHistory,
     CancellationToken cancellationToken = default(CancellationToken)
     )
 {
     if (string.IsNullOrWhiteSpace(contentHistory.ProjectId))
     {
         contentHistory.ProjectId = projectId;
     }
     await _commands.CreateAsync(
         projectId,
         contentHistory.Id.ToString(),
         contentHistory,
         cancellationToken).ConfigureAwait(false);
 }
Beispiel #15
0
 public PageEditContext(
     IProjectSettings projectSettings,
     IPage currentPage,
     ContentHistory contentHistory,
     bool canEdit,
     bool didReplaceDraft,
     bool didRestoreDeleted,
     int rootPageCount = -1
     )
 {
     Project           = projectSettings;
     CurrentPage       = currentPage;
     History           = contentHistory;
     CanEdit           = canEdit;
     DidReplaceDraft   = didReplaceDraft;
     DidRestoreDeleted = didRestoreDeleted;
     RootPageCount     = rootPageCount;
 }
Beispiel #16
0
        private void PopulateControls()
        {
            if (moduleId == -1)
            {
                return;
            }
            if (itemId == -1)
            {
                return;
            }
            //if (module == null) { return; }
            if (historyGuid == Guid.Empty)
            {
                return;
            }

            Blog blog = new Blog(itemId);

            if (blog.ModuleId != moduleId)
            {
                return;
            }

            ContentHistory history = new ContentHistory(historyGuid);

            if (history.ContentGuid != blog.BlogGuid)
            {
                return;
            }

            litCurrentHeading.Text = string.Format(BlogResources.CurrentVersionHeadingFormat,
                                                   DateTimeHelper.GetTimeZoneAdjustedDateTimeString(blog.LastModUtc, timeOffset));

            litCurrentVersion.Text = blog.Description;

            litHistoryHead.Text = string.Format(BlogResources.VersionAsOfHeadingFormat,
                                                DateTimeHelper.GetTimeZoneAdjustedDateTimeString(history.CreatedUtc, timeOffset));

            litHistoryVersion.Text = history.ContentText;

            string onClick = "top.window.LoadHistoryInEditor('" + historyGuid.ToString() + "');  return false;";

            btnRestore.Attributes.Add("onclick", onClick);
        }
        public static List <ContentHistory> Map(SqlDataReader reader)
        {
            var results = new List <ContentHistory>();

            while (reader.Read())
            {
                var item = new ContentHistory()
                {
                    Id              = reader.GetInt32(0),
                    ContentId       = reader.GetInt32(1),
                    ChangedField    = reader.GetString(2),
                    OldValue        = reader.GetString(3),
                    Changed         = reader.GetDateTime(4),
                    ChangedByUserId = reader.GetInt32(5)
                };
                results.Add(item);
            }
            return(results);
        }
Beispiel #18
0
        void btnRestoreFromGreyBox_Click(object sender, ImageClickEventArgs e)
        {
            if (hdnHxToRestore.Value.Length != 36)
            {
                BindHistory();
                return;
            }

            Guid h = new Guid(hdnHxToRestore.Value);

            ContentHistory history = new ContentHistory(h);

            if (history.Guid == Guid.Empty)
            {
                return;
            }

            edContent.Text = history.ContentText;
            BindHistory();
        }
Beispiel #19
0
        private void ShowVsHistory()
        {
            HtmlContent    html    = repository.Fetch(moduleId);
            ContentHistory history = new ContentHistory(historyGuid);

            if (history.ContentGuid != html.ModuleGuid)
            {
                return;
            }

            litCurrentHeading.Text = string.Format(Resource.CurrentVersionHeadingFormat,
                                                   DateTimeHelper.GetTimeZoneAdjustedDateTimeString(html.LastModUtc, timeOffset));

            litCurrentVersion.Text = html.Body;

            litHistoryHead.Text = string.Format(Resource.VersionAsOfHeadingFormat,
                                                DateTimeHelper.GetTimeZoneAdjustedDateTimeString(history.CreatedUtc, timeOffset));

            litHistoryVersion.Text = history.ContentText;

            string onClick = "top.window.LoadHistoryInEditor('" + historyGuid.ToString() + "');  return false;";

            btnRestore.Attributes.Add("onclick", onClick);
        }
Beispiel #20
0
 public PageViewContext(
     IProjectSettings project,
     IPage currentPage,
     ContentHistory history,
     bool canEdit,
     bool hasDraft,
     bool hasPublishedVersion,
     bool didReplaceDraft,
     bool didRestoreDeleted,
     bool showingDraft,
     int rootPageCount
     )
 {
     Project             = project;
     CurrentPage         = currentPage;
     History             = history;
     HasDraft            = hasDraft;
     CanEdit             = canEdit;
     HasPublishedVersion = hasPublishedVersion;
     DidReplaceDraft     = didReplaceDraft;
     DidRestoreDeleted   = didRestoreDeleted;
     ShowingDraft        = showingDraft;
     RootPageCount       = rootPageCount;
 }
Beispiel #21
0
        public async Task <PageEditContext> Handle(PageEditContextRequest request, CancellationToken cancellationToken = default(CancellationToken))
        {
            IPage            page              = null;
            ContentHistory   history           = null;
            var              canEdit           = false;
            var              didReplaceDraft   = false;
            var              didRestoreDeleted = false;
            var              rootPageCount     = -1;
            IProjectSettings project           = await _projectService.GetCurrentProjectSettings();

            if (project != null)
            {
                canEdit = await request.User.CanEditPages(project.Id, _authorizationService);

                var slug = request.Slug;
                if (slug == "none")
                {
                    slug = string.Empty;
                }

                if (!string.IsNullOrEmpty(slug))
                {
                    page = await _pageService.GetPageBySlug(slug, cancellationToken);
                }
                else if (!string.IsNullOrWhiteSpace(request.PageId))
                {
                    page = await _pageService.GetPage(request.PageId, cancellationToken);
                }

                if (request.HistoryId.HasValue)
                {
                    history = await _historyQueries.Fetch(project.Id, request.HistoryId.Value).ConfigureAwait(false);

                    if (history != null)
                    {
                        //if (!string.IsNullOrWhiteSpace(history.TemplateKey))
                        //{
                        //    return RedirectToRoute(PageRoutes.PageEditWithTemplateRouteName, routeVals);
                        //}

                        if (page == null) // page was deleted, restore it from history
                        {
                            page = new Page();
                            history.CopyTo(page);
                            if (history.IsDraftHx)
                            {
                                page.PromoteDraftTemporarilyForRender();
                            }
                            didRestoreDeleted = true;
                        }
                        else
                        {
                            didReplaceDraft = page.HasDraftVersion();
                            var pageCopy = new Page();
                            page.CopyTo(pageCopy);
                            if (history.IsDraftHx)
                            {
                                pageCopy.DraftAuthor          = history.DraftAuthor;
                                pageCopy.DraftContent         = history.DraftContent;
                                pageCopy.DraftSerializedModel = history.DraftSerializedModel;
                            }
                            else
                            {
                                pageCopy.DraftAuthor          = history.Author;
                                pageCopy.DraftContent         = history.Content;
                                pageCopy.DraftSerializedModel = history.SerializedModel;
                            }
                            page = pageCopy;
                        }

                        //model.HistoryArchiveDate = history.ArchivedUtc;
                        //model.HistoryId = history.Id;
                        //model.DidReplaceDraft = didReplaceDraft;
                        //model.DidRestoreDeleted = didRestoreDeleted;
                    }
                }

                if (page == null)
                {
                    var rootList = await _pageService.GetRootPages(cancellationToken).ConfigureAwait(false);

                    rootPageCount = rootList.Count;
                }
            }


            return(new PageEditContext(
                       project,
                       page,
                       history,
                       canEdit,
                       didReplaceDraft,
                       didRestoreDeleted,
                       rootPageCount
                       ));
        }
Beispiel #22
0
        public async Task <CommandResult <IPage> > Handle(CreateOrUpdatePageRequest request, CancellationToken cancellationToken = default(CancellationToken))
        {
            var errors = new List <string>();

            try
            {
                bool isNew   = false;
                var  project = await _projectService.GetProjectSettings(request.ProjectId);

                var            page    = request.Page;
                ContentHistory history = null;
                if (page == null)
                {
                    isNew = true;
                    page  = new Page()
                    {
                        ProjectId     = request.ProjectId,
                        ParentId      = "0",
                        CreatedByUser = request.UserName,
                        Slug          = ContentUtils.CreateSlug(request.ViewModel.Title),
                        ContentType   = request.ViewModel.ContentType
                    };
                }
                else
                {
                    history = page.CreateHistory(request.UserName);
                }


                if (!string.IsNullOrEmpty(request.ViewModel.Slug))
                {
                    // remove any bad characters
                    request.ViewModel.Slug = ContentUtils.CreateSlug(request.ViewModel.Slug);
                    if (request.ViewModel.Slug != page.Slug)
                    {
                        var slugIsAvailable = await _pageService.SlugIsAvailable(request.ViewModel.Slug);

                        if (!slugIsAvailable)
                        {
                            errors.Add(_localizer["The page slug was invalid because the requested slug is already in use."]);
                            request.ModelState.AddModelError("Slug", _localizer["The page slug was not changed because the requested slug is already in use."]);
                        }
                    }
                }

                if (request.ModelState.IsValid)
                {
                    page.Title              = request.ViewModel.Title;
                    page.CorrelationKey     = request.ViewModel.CorrelationKey;
                    page.LastModified       = DateTime.UtcNow;
                    page.LastModifiedByUser = request.UserName;
                    page.MenuFilters        = request.ViewModel.MenuFilters;
                    page.MetaDescription    = request.ViewModel.MetaDescription;
                    page.PageOrder          = request.ViewModel.PageOrder;

                    page.ShowHeading   = request.ViewModel.ShowHeading;
                    page.ShowMenu      = request.ViewModel.ShowMenu;
                    page.MenuOnly      = request.ViewModel.MenuOnly;
                    page.DisableEditor = request.ViewModel.DisableEditor;
                    page.ShowComments  = request.ViewModel.ShowComments;
                    page.MenuFilters   = request.ViewModel.MenuFilters;
                    page.ExternalUrl   = request.ViewModel.ExternalUrl;
                    page.ViewRoles     = request.ViewModel.ViewRoles;


                    if (!string.IsNullOrEmpty(request.ViewModel.Slug))
                    {
                        page.Slug = request.ViewModel.Slug;
                    }

                    if (!string.IsNullOrEmpty(request.ViewModel.ParentSlug))
                    {
                        var parentPage = await _pageService.GetPageBySlug(request.ViewModel.ParentSlug);

                        if (parentPage != null)
                        {
                            if (parentPage.Id != page.ParentId)
                            {
                                page.ParentId   = parentPage.Id;
                                page.ParentSlug = parentPage.Slug;
                            }
                        }
                    }
                    else
                    {
                        // empty means root level
                        page.ParentSlug = string.Empty;
                        page.ParentId   = "0";
                    }

                    if (page.ParentSlug == project.DefaultPageSlug)
                    {
                        _log.LogWarning($"{request.UserName} tried to explicitely set the default page slug as the parent slug which is not allowed since all root pages are already children of the default page");
                        page.ParentSlug = string.Empty;
                        page.ParentId   = "0";
                    }


                    var shouldFirePublishEvent = false;
                    //var shouldFireUnPublishEvent = false;
                    switch (request.ViewModel.SaveMode)
                    {
                    //case SaveMode.UnPublish:

                    //    page.DraftContent = request.ViewModel.Content;
                    //    page.DraftAuthor = request.ViewModel.Author;
                    //    page.DraftPubDate = null;
                    //    page.IsPublished = false;
                    //    page.PubDate = null;

                    //    shouldFireUnPublishEvent = true;

                    //    break;

                    case SaveMode.SaveDraft:

                        page.DraftContent = request.ViewModel.Content;
                        page.DraftAuthor  = request.ViewModel.Author;
                        // should we clear the draft pub date if save draft clicked?
                        //page.DraftPubDate = null;
                        if (!page.PubDate.HasValue)
                        {
                            page.IsPublished = false;
                        }

                        break;

                    case SaveMode.PublishLater:

                        page.DraftContent = request.ViewModel.Content;
                        page.DraftAuthor  = request.ViewModel.Author;
                        if (request.ViewModel.NewPubDate.HasValue)
                        {
                            var tzId = await _timeZoneIdResolver.GetUserTimeZoneId(CancellationToken.None);

                            page.DraftPubDate = _timeZoneHelper.ConvertToUtc(request.ViewModel.NewPubDate.Value, tzId);
                        }
                        if (!page.PubDate.HasValue)
                        {
                            page.IsPublished = false;
                        }

                        break;

                    case SaveMode.PublishNow:

                        page.Content           = request.ViewModel.Content;
                        page.Author            = request.ViewModel.Author;
                        page.PubDate           = DateTime.UtcNow;
                        page.IsPublished       = true;
                        shouldFirePublishEvent = true;

                        page.DraftAuthor  = null;
                        page.DraftContent = null;
                        page.DraftPubDate = null;

                        break;
                    }

                    if (history != null)
                    {
                        await _historyCommands.Create(request.ProjectId, history).ConfigureAwait(false);
                    }

                    if (isNew)
                    {
                        await _pageService.Create(page);
                    }
                    else
                    {
                        await _pageService.Update(page);
                    }

                    if (shouldFirePublishEvent)
                    {
                        await _pageService.FirePublishEvent(page).ConfigureAwait(false);

                        await _historyCommands.DeleteDraftHistory(project.Id, page.Id).ConfigureAwait(false);
                    }

                    //if (shouldFireUnPublishEvent)
                    //{
                    //    await _pageService.FireUnPublishEvent(page).ConfigureAwait(false);
                    //}

                    _pageService.ClearNavigationCache();
                }

                return(new CommandResult <IPage>(page, request.ModelState.IsValid, errors));
            }
            catch (Exception ex)
            {
                _log.LogError($"{ex.Message}:{ex.StackTrace}");

                errors.Add(_localizer["Updating a page failed. An error has been logged."]);

                return(new CommandResult <IPage>(null, false, errors));
            }
        }
Beispiel #23
0
        private void PopulateControls()
        {
            if (html == null)
            {
                return;
            }
            this.itemId = html.ItemId;

            edContent.Text = html.Body;

            if ((workInProgress != null) && (ViewMode == PageViewMode.WorkInProgress))
            {
                pnlWorkflowStatus.Visible = true;
                edContent.Text            = workInProgress.ContentText;

                litRecentActionBy.Text            = workInProgress.RecentActionByUserLogin;
                litRecentActionOn.Text            = workInProgress.RecentActionOn.ToString();
                lnkCompareDraftToLive.Visible     = true;
                lnkCompareDraftToLive.NavigateUrl = SiteRoot
                                                    + "/HtmlCompare.aspx?pageid=" + pageId.ToString(CultureInfo.InvariantCulture)
                                                    + "&mid=" + moduleId.ToString(CultureInfo.InvariantCulture) + "&d=" + workInProgress.Guid.ToString();

                switch (workInProgress.Status)
                {
                case ContentWorkflowStatus.ApprovalRejected:

                    litWorkflowStatus.Text      = Resource.ContentWasRejected;
                    lblRecentActionBy.ConfigKey = "RejectedBy";
                    lblRecentActionOn.ConfigKey = "RejectedOn";
                    litCreatedBy.Text           = workInProgress.CreatedByUserName;
                    ltlRejectionReason.Text     = workInProgress.Notes;
                    divRejection.Visible        = true;

                    break;

                case ContentWorkflowStatus.AwaitingApproval:

                    litWorkflowStatus.Text      = Resource.ContentAwaitingApproval;
                    lblRecentActionBy.ConfigKey = "ContentLastEditBy";
                    lblRecentActionOn.ConfigKey = "ContentLastEditDate";
                    ltlRejectionReason.Text     = string.Empty;
                    divRejection.Visible        = false;

                    break;

                case ContentWorkflowStatus.Draft:

                    litWorkflowStatus.Text      = Resource.ContentEditsInProgress;
                    lblRecentActionBy.ConfigKey = "ContentLastEditBy";
                    lblRecentActionOn.ConfigKey = "ContentLastEditDate";
                    ltlRejectionReason.Text     = string.Empty;
                    divRejection.Visible        = false;

                    break;
                }
            }


            if ((this.itemId == -1) || (!this.useMultipleItems))
            {
                this.btnDelete.Visible = false;
            }

            if (enableContentVersioning)
            {
                BindHistory();
            }

            if (restoreGuid != Guid.Empty)
            {
                ContentHistory rHistory = new ContentHistory(restoreGuid);
                if (rHistory.ContentGuid == html.ModuleGuid)
                {
                    edContent.Text = rHistory.ContentText;
                }
            }
        }
        public async Task <PageViewContext> Handle(PageViewContextRequest request, CancellationToken cancellationToken = default(CancellationToken))
        {
            IPage            page                = null;
            ContentHistory   history             = null;
            var              canEdit             = false;
            var              hasDraft            = false;
            var              hasPublishedVersion = false;
            var              didReplaceDraft     = false;
            var              didRestoreDeleted   = false;
            var              showingDraft        = false;
            var              rootPageCount       = -1;
            IProjectSettings project             = await _projectService.GetCurrentProjectSettings();

            if (project != null)
            {
                canEdit = await request.User.CanEditPages(project.Id, _authorizationService);

                var slug = request.Slug;
                if (string.IsNullOrEmpty(slug) || slug == "none")
                {
                    slug = project.DefaultPageSlug;
                }

                page = await _pageService.GetPageBySlug(slug, cancellationToken);

                if (page != null)
                {
                    hasDraft            = page.HasDraftVersion();
                    hasPublishedVersion = page.HasPublishedVersion();
                }

                if (canEdit && request.HistoryId.HasValue)
                {
                    history = await _historyQueries.Fetch(project.Id, request.HistoryId.Value);

                    if (history != null)
                    {
                        if (page == null) //page must have been deleted, restore from hx
                        {
                            page = new Page();
                            history.CopyTo(page);
                            if (history.IsDraftHx)
                            {
                                page.PromoteDraftTemporarilyForRender();
                            }
                            didRestoreDeleted = true;
                        }
                        else
                        {
                            var pageCopy = new Page();
                            page.CopyTo(pageCopy);
                            if (history.IsDraftHx)
                            {
                                pageCopy.Content = history.DraftContent;
                                pageCopy.Author  = history.DraftAuthor;
                            }
                            else
                            {
                                pageCopy.Content = history.Content;
                                pageCopy.Author  = history.Author;
                            }

                            page            = pageCopy;
                            didReplaceDraft = hasDraft;
                        }
                    }
                }
                else if (canEdit && page != null && ((request.ShowDraft && page.HasDraftVersion()) || !page.HasPublishedVersion()))
                {
                    var pageCopy = new Page();
                    page.CopyTo(pageCopy);
                    pageCopy.PromoteDraftTemporarilyForRender();
                    page         = pageCopy;
                    showingDraft = true;
                }

                if (page == null)
                {
                    var rootList = await _pageService.GetRootPages(cancellationToken).ConfigureAwait(false);

                    rootPageCount = rootList.Count;
                }
            }

            return(new PageViewContext(
                       project,
                       page,
                       history,
                       canEdit,
                       hasDraft,
                       hasPublishedVersion,
                       didReplaceDraft,
                       didRestoreDeleted,
                       showingDraft,
                       rootPageCount
                       ));
        }
Beispiel #25
0
        public async Task <CommandResult <IPost> > Handle(CreateOrUpdatePostRequest request, CancellationToken cancellationToken = default(CancellationToken))
        {
            var errors = new List <string>();

            try
            {
                bool isNew   = false;
                var  project = await _projectService.GetProjectSettings(request.ProjectId);

                var            post    = request.Post;
                ContentHistory history = null;
                if (post == null)
                {
                    isNew = true;
                    post  = new Post()
                    {
                        BlogId          = request.ProjectId,
                        Title           = request.ViewModel.Title,
                        MetaDescription = request.ViewModel.MetaDescription,
                        Slug            = ContentUtils.CreateSlug(request.ViewModel.Title),
                        CreatedByUser   = request.UserName
                    };
                }
                else
                {
                    history = post.CreateHistory(request.UserName);
                }

                if (!string.IsNullOrEmpty(request.ViewModel.Slug))
                {
                    // remove any bad characters
                    request.ViewModel.Slug = ContentUtils.CreateSlug(request.ViewModel.Slug);
                    if (request.ViewModel.Slug != post.Slug)
                    {
                        var slugIsAvailable = await _blogService.SlugIsAvailable(request.ViewModel.Slug);

                        if (!slugIsAvailable)
                        {
                            request.ModelState.AddModelError("Slug", _localizer["The page slug was not changed because the requested slug is already in use."]);
                        }
                    }
                }

                if (request.ModelState.IsValid)
                {
                    post.Title              = request.ViewModel.Title;
                    post.CorrelationKey     = request.ViewModel.CorrelationKey;
                    post.ImageUrl           = request.ViewModel.ImageUrl;
                    post.ThumbnailUrl       = request.ViewModel.ThumbnailUrl;
                    post.IsFeatured         = request.ViewModel.IsFeatured;
                    post.ContentType        = request.ViewModel.ContentType;
                    post.TeaserOverride     = request.ViewModel.TeaserOverride;
                    post.SuppressTeaser     = request.ViewModel.SuppressTeaser;
                    post.LastModified       = DateTime.UtcNow;
                    post.LastModifiedByUser = request.UserName;

                    if (!string.IsNullOrEmpty(request.ViewModel.Slug))
                    {
                        post.Slug = request.ViewModel.Slug;
                    }


                    var categories = new List <string>();

                    if (!string.IsNullOrEmpty(request.ViewModel.Categories))
                    {
                        if (_editOptions.ForceLowerCaseCategories)
                        {
                            categories = request.ViewModel.Categories.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(x => x.Trim().ToLower())
                                         .Where(x =>
                                                !string.IsNullOrWhiteSpace(x) &&
                                                x != ","
                                                )
                                         .Distinct()
                                         .ToList();
                        }
                        else
                        {
                            categories = request.ViewModel.Categories.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(x => x.Trim())
                                         .Where(x =>
                                                !string.IsNullOrWhiteSpace(x) &&
                                                x != ","
                                                )
                                         .Distinct()
                                         .ToList();
                        }
                    }
                    post.Categories = categories;


                    var shouldFirePublishEvent = false;
                    switch (request.ViewModel.SaveMode)
                    {
                    case SaveMode.SaveDraft:

                        post.DraftContent = request.ViewModel.Content;
                        post.DraftAuthor  = request.ViewModel.Author;

                        break;

                    case SaveMode.PublishLater:

                        post.DraftContent = request.ViewModel.Content;
                        post.DraftAuthor  = request.ViewModel.Author;
                        if (request.ViewModel.NewPubDate.HasValue)
                        {
                            var tzId = await _timeZoneIdResolver.GetUserTimeZoneId(CancellationToken.None);

                            post.DraftPubDate = _timeZoneHelper.ConvertToUtc(request.ViewModel.NewPubDate.Value, tzId);
                        }
                        if (!post.PubDate.HasValue)
                        {
                            post.IsPublished = false;
                        }

                        break;

                    case SaveMode.PublishNow:

                        post.Content = request.ViewModel.Content;
                        post.Author  = request.ViewModel.Author;
                        if (!post.PubDate.HasValue)
                        {
                            post.PubDate = DateTime.UtcNow;
                        }
                        else if (post.PubDate > DateTime.UtcNow)
                        {
                            post.PubDate = DateTime.UtcNow;
                        }

                        post.IsPublished       = true;
                        shouldFirePublishEvent = true;

                        post.DraftAuthor  = null;
                        post.DraftContent = null;
                        post.DraftPubDate = null;

                        break;
                    }

                    if (project.TeaserMode != TeaserMode.Off)
                    {
                        // need to generate the teaser on save
                        string html = null;
                        if (post.ContentType == "markdown")
                        {
                            var mdPipeline = new MarkdownPipelineBuilder().UseAdvancedExtensions().Build();
                            html = Markdown.ToHtml(post.Content, mdPipeline);
                        }
                        else
                        {
                            html = post.Content;
                        }
                        var teaserResult = _teaserService.GenerateTeaser(
                            project.TeaserTruncationMode,
                            project.TeaserTruncationLength,
                            html,
                            Guid.NewGuid().ToString(),//cache key
                            post.Slug,
                            project.LanguageCode,
                            false //logWarnings
                            );
                        post.AutoTeaser = teaserResult.Content;
                    }

                    if (history != null)
                    {
                        await _historyCommands.Create(request.ProjectId, history).ConfigureAwait(false);
                    }

                    if (isNew)
                    {
                        await _blogService.Create(post);
                    }
                    else
                    {
                        await _blogService.Update(post);
                    }

                    if (shouldFirePublishEvent)
                    {
                        await _blogService.FirePublishEvent(post);

                        await _historyCommands.DeleteDraftHistory(request.ProjectId, post.Id).ConfigureAwait(false);
                    }
                }

                return(new CommandResult <IPost>(post, request.ModelState.IsValid, errors));
            }
            catch (Exception ex)
            {
                _log.LogError($"{ex.Message}:{ex.StackTrace}");

                errors.Add(_localizer["Updating a page failed. An error has been logged."]);

                return(new CommandResult <IPost>(null, false, errors));
            }
        }