Data access and service class for Rock.Model.HtmlContent entity objects.
Example #1
0
        /// <summary>
        /// Copies any HtmlContent in the original page tree over to the corresponding blocks on the copied page tree.
        /// </summary>
        /// <param name="blockGuidDictionary">The dictionary containing the original block guids and the corresponding copied block guids.</param>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="currentPersonAliasId">The current person alias identifier.</param>
        private void CloneHtmlContent(Dictionary <Guid, Guid> blockGuidDictionary, RockContext rockContext, int?currentPersonAliasId = null)
        {
            var htmlContentService = new HtmlContentService(rockContext);
            var blockService       = new BlockService(rockContext);

            Dictionary <Guid, int> blockIntDictionary = blockService.Queryable()
                                                        .Where(p => blockGuidDictionary.Keys.Contains(p.Guid) || blockGuidDictionary.Values.Contains(p.Guid))
                                                        .ToDictionary(p => p.Guid, p => p.Id);

            var htmlContents = htmlContentService.Queryable().Where(a =>
                                                                    blockIntDictionary.Values.Contains(a.BlockId))
                               .ToList();

            foreach (var htmlContent in htmlContents)
            {
                var newHtmlContent = htmlContent.Clone(false);
                newHtmlContent.CreatedByPersonAlias    = null;
                newHtmlContent.CreatedByPersonAliasId  = currentPersonAliasId;
                newHtmlContent.CreatedDateTime         = RockDateTime.Now;
                newHtmlContent.ModifiedByPersonAlias   = null;
                newHtmlContent.ModifiedByPersonAliasId = currentPersonAliasId;
                newHtmlContent.ModifiedDateTime        = RockDateTime.Now;
                newHtmlContent.Id      = 0;
                newHtmlContent.Guid    = Guid.NewGuid();
                newHtmlContent.BlockId = blockIntDictionary[blockGuidDictionary[blockIntDictionary.Where(d => d.Value == htmlContent.BlockId).FirstOrDefault().Key]];

                htmlContentService.Add(newHtmlContent);
            }

            rockContext.SaveChanges();
        }
Example #2
0
        /// <summary>
        /// Handles the CheckChanged event of the gContentList IsApproved field.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="RowEventArgs" /> instance containing the event data.</param>
        protected void gContentList_CheckedChanged( object sender, RowEventArgs e )
        {
            bool cannotApprove = true;

            if ( e.RowKeyValue != null )
            {
                var rockContext = new RockContext();
                var htmlContentService = new HtmlContentService( rockContext );
                var htmlContent = htmlContentService.Get( e.RowKeyId );

                if ( htmlContent != null )
                {
                    cannotApprove = false;
                    // if it was approved, set it to unapproved... otherwise
                    if ( htmlContent.IsApproved )
                    {
                        htmlContent.IsApproved = false;
                        htmlContent.ApprovedByPersonId = null;
                        htmlContent.ApprovedDateTime = null;
                    }
                    else
                    {
                        htmlContent.IsApproved = true;
                        htmlContent.ApprovedByPersonId = CurrentPersonId;
                        htmlContent.ApprovedDateTime = RockDateTime.Now;
                    }

                    rockContext.SaveChanges();
                    FlushSharedBlock( htmlContent.BlockId );
                }

                BindGrid();
            }

            if ( cannotApprove )
            {
                mdGridWarning.Show( "Unable to approve this HTML Content", ModalAlertType.Warning );
            }
        }
Example #3
0
        /// <summary>
        /// Handles the Click event of the lbSave control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void lbSave_Click( object sender, EventArgs e )
        {
            bool supportVersioning = GetAttributeValue( "SupportVersions" ).AsBoolean();
            bool requireApproval = GetAttributeValue( "RequireApproval" ).AsBoolean();
            HtmlContentService htmlContentService = new HtmlContentService();

            // get settings
            string entityValue = EntityValue();

            // get current content
            int version = hfVersion.ValueAsInt();
            HtmlContent htmlContent = htmlContentService.GetByBlockIdAndEntityValueAndVersion( this.BlockId, entityValue, version );

            // if the existing content changed, and the overwrite option was not checked, create a new version
            string newContent = ceHtml.Visible ? ceHtml.Text : htmlEditor.Text;

            if ( htmlContent != null && supportVersioning && htmlContent.Content != newContent && !cbOverwriteVersion.Checked )
            {
                htmlContent = null;
            }

            // if a record doesn't exist then create one
            if ( htmlContent == null )
            {
                htmlContent = new HtmlContent();
                htmlContent.BlockId = this.BlockId;
                htmlContent.EntityValue = entityValue;

                if ( supportVersioning )
                {
                    int? maxVersion = GetMaxVersionOfHtmlContent();

                    htmlContent.Version = maxVersion.HasValue ? maxVersion.Value + 1 : 1;
                }
                else
                {
                    htmlContent.Version = 1;
                }

                htmlContentService.Add( htmlContent, CurrentPersonId );
            }

            htmlContent.StartDateTime = drpDateRange.LowerValue;
            htmlContent.ExpireDateTime = drpDateRange.UpperValue;

            if ( !requireApproval || IsUserAuthorized( "Approve" ) )
            {
                htmlContent.IsApproved = !requireApproval || hfApprovalStatus.Value.AsBoolean();
                if ( htmlContent.IsApproved )
                {
                    int personId = hfApprovalStatusPersonId.ValueAsInt();
                    if ( personId > 0 )
                    {
                        htmlContent.ApprovedByPersonId = personId;
                        htmlContent.ApprovedDateTime = DateTime.Now;
                    }
                }
            }

            htmlContent.LastModifiedPersonId = this.CurrentPersonId;
            htmlContent.LastModifiedDateTime = DateTime.Now;
            htmlContent.Content = newContent;

            if ( htmlContentService.Save( htmlContent, CurrentPersonId ) )
            {
                // flush cache content 
                this.FlushCacheItem( entityValue );

                // force the updatepanel for the view to update since we have two update panels and we only want the View to update when it is edited and Saved
                upnlHtmlContent.Update();
                ShowView();
            }
            else
            {
                // TODO: service.ErrorMessages;
            }
        }
Example #4
0
        /// <summary>
        /// Handles the Click event of the lbEdit control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void lbEdit_Click( object sender, EventArgs e )
        {
            // only enable viewstate for htmlEditor when needed (it is really big)
            pnlEdit.EnableViewState = true;

            pnlEdit.Visible = true;
            pnlVersionGrid.Visible = false;
            mdEdit.Show();

            bool useCodeEditor = GetAttributeValue( "UseCodeEditor" ).AsBoolean();

            ceHtml.Visible = useCodeEditor;
            htmlEditor.Visible = !useCodeEditor;

            htmlEditor.Toolbar = HtmlEditor.ToolbarConfig.Full;

            // if the current user can't approve their own edits, set the approval to Not-Approved when they change something
            if ( !IsUserAuthorized( "Approve" ) )
            {
                string onchangeScriptFormat = @"
   $('#{0}').removeClass('label label-success label-danger').addClass('label label-danger');
   $('#{0}').text('Not-Approved');
   $('#{1}').val('false');
   $('#{2}').val('');
   $('#{3}').hide();";

                string onchangeScript = string.Format( onchangeScriptFormat, lblApprovalStatus.ClientID, hfApprovalStatus.ClientID, hfApprovalStatusPersonId.ClientID, lblApprovalStatusPerson.ClientID );

                htmlEditor.OnChangeScript = onchangeScript;
                ceHtml.OnChangeScript = onchangeScript;
            }

            htmlEditor.MergeFields.Clear();
            htmlEditor.MergeFields.Add( "GlobalAttribute" );

            bool supportsVersioning = GetAttributeValue( "SupportVersions" ).AsBoolean();
            bool requireApproval = GetAttributeValue( "RequireApproval" ).AsBoolean();

            lVersion.Visible = supportsVersioning;
            lbShowVersionGrid.Visible = supportsVersioning;
            cbOverwriteVersion.Visible = supportsVersioning;
            cbOverwriteVersion.Checked = false;

            // RequireApproval only applies if SupportsVersioning=True
            upnlApproval.Visible = supportsVersioning && requireApproval;
            lbApprove.Enabled = IsUserAuthorized( "Approve" );
            lbDeny.Enabled = IsUserAuthorized( "Approve" );

            string entityValue = EntityValue();
            HtmlContent htmlContent = new HtmlContentService().GetActiveContent( this.BlockId, entityValue );

            ShowEditDetail( htmlContent );
        }
Example #5
0
        /// <summary>
        /// Binds the grid.
        /// </summary>
        private void BindGrid()
        {
            var rockContext = new RockContext();

            int entityTypeIdBlock = EntityTypeCache.Read( typeof( Rock.Model.Block ), true, rockContext ).Id;
            string entityTypeQualifier = BlockTypeCache.Read( Rock.SystemGuid.BlockType.HTML_CONTENT.AsGuid(), rockContext ).Id.ToString();
            var htmlContentService = new HtmlContentService( rockContext );
            var attributeValueQry = new AttributeValueService( rockContext ).Queryable()
                .Where( a => a.Attribute.Key == "RequireApproval" && a.Attribute.EntityTypeId == entityTypeIdBlock )
                .Where( a => a.Attribute.EntityTypeQualifierColumn == "BlockTypeId" && a.Attribute.EntityTypeQualifierValue == entityTypeQualifier )
                .Where( a => a.Value == "True" )
                .Select( a => a.EntityId );

            var qry = htmlContentService.Queryable().Where( a => attributeValueQry.Contains( a.BlockId ) );

            // Filter by approved/unapproved
            if ( ddlApprovedFilter.SelectedIndex > -1 )
            {
                if ( ddlApprovedFilter.SelectedValue.ToLower() == "unapproved" )
                {
                    qry = qry.Where( a => a.IsApproved == false );
                }
                else if ( ddlApprovedFilter.SelectedValue.ToLower() == "approved" )
                {
                    qry = qry.Where( a => a.IsApproved == true );
                }
            }

            // Filter by the person that approved the content
            if ( _canApprove )
            {
                int? personId = gContentListFilter.GetUserPreference( "Approved By" ).AsIntegerOrNull();
                if ( personId.HasValue )
                {
                    qry = qry.Where( a => a.ApprovedByPersonAliasId.HasValue && a.ApprovedByPersonAlias.PersonId == personId );
                }
            }

            SortProperty sortProperty = gContentList.SortProperty;
            if ( sortProperty != null )
            {
                qry = qry.Sort( sortProperty );
            }
            else
            {
                qry = qry.OrderByDescending( a => a.ModifiedDateTime );
            }

            var selectQry = qry.Select( a => new
            {
                a.Id,
                SiteName = a.Block.PageId.HasValue ? a.Block.Page.Layout.Site.Name : a.Block.Layout.Site.Name,
                PageName = a.Block.Page.InternalName,
                a.ModifiedDateTime,
                a.IsApproved,
                ApprovedDateTime = a.IsApproved ? a.ApprovedDateTime : null,
                ApprovedByPerson = a.IsApproved ? a.ApprovedByPersonAlias.Person : null,
                BlockPageId = a.Block.PageId,
                BlockLayoutId = a.Block.LayoutId,
            } );

            gContentList.EntityTypeId = EntityTypeCache.Read<HtmlContent>().Id;

            // Filter by Site
            if ( ddlSiteFilter.SelectedIndex > 0 )
            {
                if ( ddlSiteFilter.SelectedValue.ToLower() != "all" )
                {
                    selectQry = selectQry.Where( h => h.SiteName == ddlSiteFilter.SelectedValue );
                }
            }

            gContentList.DataSource = selectQry.ToList();
            gContentList.DataBind();
        }
Example #6
0
 /// <summary>
 /// Handles the RowSelected event of the gContentList control.
 /// </summary>
 /// <param name="sender">The source of the event.</param>
 /// <param name="e">The <see cref="RowEventArgs"/> instance containing the event data.</param>
 protected void gContentList_RowSelected( object sender, RowEventArgs e )
 {
     var htmlContent = new HtmlContentService(new RockContext()).Get(e.RowKeyId);
     if ( htmlContent != null )
     {
         lPreviewHtml.Text = htmlContent.Content;
         mdPreview.Show();
     }
 }
Example #7
0
        /// <summary>
        /// Copies any HtmlContent in the original page tree over to the corresponding blocks on the copied page tree.
        /// </summary>
        /// <param name="blockGuidDictionary">The dictionary containing the original block guids and the corresponding copied block guids.</param>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="currentPersonAliasId">The current person alias identifier.</param>
        private void CloneHtmlContent( Dictionary<Guid, Guid> blockGuidDictionary, RockContext rockContext, int? currentPersonAliasId = null )
        {
            var htmlContentService = new HtmlContentService( rockContext );
            var blockService = new BlockService( rockContext );

            Dictionary<Guid, int> blockIntDictionary = blockService.Queryable()
                .Where( p => blockGuidDictionary.Keys.Contains( p.Guid ) || blockGuidDictionary.Values.Contains( p.Guid ) )
                .ToDictionary( p => p.Guid, p => p.Id );

            var htmlContents = htmlContentService.Queryable().Where( a =>
                blockIntDictionary.Values.Contains( a.BlockId ) )
                .ToList();

            foreach ( var htmlContent in htmlContents )
            {
                var newHtmlContent = htmlContent.Clone( false );
                newHtmlContent.CreatedByPersonAlias = null;
                newHtmlContent.CreatedByPersonAliasId = currentPersonAliasId;
                newHtmlContent.CreatedDateTime = RockDateTime.Now;
                newHtmlContent.ModifiedByPersonAlias = null;
                newHtmlContent.ModifiedByPersonAliasId = currentPersonAliasId;
                newHtmlContent.ModifiedDateTime = RockDateTime.Now;
                newHtmlContent.Id = 0;
                newHtmlContent.Guid = Guid.NewGuid();
                newHtmlContent.BlockId = blockIntDictionary[blockGuidDictionary[blockIntDictionary.Where( d => d.Value == htmlContent.BlockId ).FirstOrDefault().Key]];

                htmlContentService.Add( newHtmlContent );
            }

            rockContext.SaveChanges();
        }
Example #8
0
 /// <summary>
 /// Gets the maximum version that this HtmlContent block 
 /// </summary>
 /// <returns></returns>
 private int? GetMaxVersionOfHtmlContent()
 {
     string entityValue = this.EntityValue();
     int? maxVersion = new HtmlContentService().Queryable()
         .Where( c => c.BlockId == this.BlockId && c.EntityValue == entityValue )
         .Select( c => (int?)c.Version ).Max();
     return maxVersion;
 }
        /// <summary>
        /// Shows the view.
        /// </summary>
        protected void ShowView()
        {
            mdEdit.Hide();
            pnlEditModel.Visible = false;
            upnlHtmlContent.Update();

            // prevent htmlEditor from using viewstate when not needed
            pnlEdit.EnableViewState = false;

            pnlEdit.Visible = false;
            pnlVersionGrid.Visible = false;
            string entityValue = EntityValue();
            string html = string.Empty;

            string cachedContent = HtmlContentService.GetCachedContent( this.BlockId, entityValue );

            // if content not cached load it from DB
            if ( cachedContent == null )
            {
                using ( var rockContext = new RockContext() )
                {
                    var htmlContentService = new HtmlContentService( rockContext );
                    HtmlContent content = htmlContentService.GetActiveContent( this.BlockId, entityValue );

                    if ( content != null )
                    {
                        bool enableDebug = GetAttributeValue( "EnableDebug" ).AsBoolean();

                        if ( content.Content.HasMergeFields() || enableDebug )
                        {
                            var mergeFields = Rock.Web.Cache.GlobalAttributesCache.GetMergeFields( CurrentPerson );
                            if ( CurrentPerson != null )
                            {
                                // TODO: When support for "Person" is not supported anymore (should use "CurrentPerson" instead), remove this line
                                mergeFields.Add( "Person", CurrentPerson );
                                mergeFields.Add( "CurrentPerson", CurrentPerson );
                            }

                            mergeFields.Add( "Campuses", CampusCache.All() );
                            mergeFields.Add( "PageParameter", PageParameters() );

                            var contextObjects = new Dictionary<string, object>();
                            foreach ( var contextEntityType in RockPage.GetContextEntityTypes() )
                            {
                                var contextEntity = RockPage.GetCurrentContext( contextEntityType );
                                if ( contextEntity != null && contextEntity is DotLiquid.ILiquidizable )
                                {
                                    var type = Type.GetType( contextEntityType.AssemblyName ?? contextEntityType.Name );
                                    if ( type != null )
                                    {
                                        contextObjects.Add( type.Name, contextEntity );
                                    }
                                }

                            }

                            if ( contextObjects.Any() )
                            {
                                mergeFields.Add( "Context", contextObjects );
                            }

                            mergeFields.Add( "RockVersion", Rock.VersionInfo.VersionInfo.GetRockProductVersionNumber() );

                            html = content.Content.ResolveMergeFields( mergeFields );

                            // show merge fields if enable debug true
                            if ( enableDebug && IsUserAuthorized( Authorization.EDIT ) )
                            {
                                // TODO: When support for "Person" is not supported anymore (should use "CurrentPerson" instead), remove this line
                                mergeFields.Remove( "Person" );
                                html += mergeFields.lavaDebugInfo();
                            }
                        }
                        else
                        {
                            html = content.Content;
                        }
                    }
                    else
                    {
                        html = string.Empty;
                    }
                }

                // Resolve any dynamic url references
                string appRoot = ResolveRockUrl( "~/" );
                string themeRoot = ResolveRockUrl( "~~/" );
                html = html.Replace( "~~/", themeRoot ).Replace( "~/", appRoot );

                // cache content
                int cacheDuration = GetAttributeValue( "CacheDuration" ).AsInteger();
                if ( cacheDuration > 0 )
                {
                    HtmlContentService.AddCachedContent( this.BlockId, entityValue, html, cacheDuration );
                }
            }
            else
            {
                html = cachedContent;
            }

            // add content to the content window
            lHtmlContent.Text = html;
        }
        /// <summary>
        /// Shows the settings.
        /// </summary>
        /// <exception cref="System.NotImplementedException"></exception>
        protected override void ShowSettings()
        {
            // only enable viewstate for htmlEditor when needed (it is really big)
            pnlEdit.EnableViewState = true;

            pnlEdit.Visible = true;
            pnlVersionGrid.Visible = false;
            pnlEditModel.Visible = true;
            upnlHtmlContent.Update();
            mdEdit.Show();

            bool useCodeEditor = GetAttributeValue( "UseCodeEditor" ).AsBoolean();

            ceHtml.Visible = useCodeEditor;
            htmlEditor.Visible = !useCodeEditor;

            htmlEditor.Toolbar = HtmlEditor.ToolbarConfig.Full;

            // if the current user can't approve their own edits, set the approval to Not-Approved when they change something
            if ( !IsUserAuthorized( "Approve" ) )
            {
                string onchangeScriptFormat = @"
               $('#{0}').removeClass('label label-success label-danger').addClass('label label-danger');
               $('#{0}').text('Not-Approved');
               $('#{1}').val('false');
               $('#{2}').val('');
               $('#{3}').hide();";

                string onchangeScript = string.Format( onchangeScriptFormat, lblApprovalStatus.ClientID, hfApprovalStatus.ClientID, hfApprovalStatusPersonId.ClientID, lblApprovalStatusPerson.ClientID );

                htmlEditor.OnChangeScript = onchangeScript;
                ceHtml.OnChangeScript = onchangeScript;
            }

            htmlEditor.MergeFields.Clear();
            htmlEditor.MergeFields.Add( "GlobalAttribute" );
            htmlEditor.MergeFields.Add( "CurrentPerson^Rock.Model.Person|Current Person" );
            htmlEditor.MergeFields.Add( "Campuses" );
            htmlEditor.MergeFields.Add( "PageParameter" );
            htmlEditor.MergeFields.Add( "RockVersion" );
            htmlEditor.MergeFields.Add( "Date" );
            htmlEditor.MergeFields.Add( "Time" );
            htmlEditor.MergeFields.Add( "DayOfWeek" );

            ceHtml.MergeFields.Clear();
            ceHtml.MergeFields.Add( "GlobalAttribute" );
            ceHtml.MergeFields.Add( "CurrentPerson^Rock.Model.Person|Current Person" );
            ceHtml.MergeFields.Add( "Campuses" );
            ceHtml.MergeFields.Add( "RockVersion" );
            ceHtml.MergeFields.Add( "PageParameter" );
            ceHtml.MergeFields.Add( "Date" );
            ceHtml.MergeFields.Add( "Time" );
            ceHtml.MergeFields.Add( "DayOfWeek" );

            var contextObjects = new Dictionary<string, object>();
            foreach ( var contextEntityType in RockPage.GetContextEntityTypes() )
            {
                var contextEntity = RockPage.GetCurrentContext( contextEntityType );
                if ( contextEntity != null && contextEntity is Rock.Lava.ILiquidizable )
                {
                    var type = Type.GetType( contextEntityType.AssemblyName ?? contextEntityType.Name );
                    if ( type != null )
                    {
                        string mergeField = string.Format( "Context.{0}^{1}|Current {0} (Context)|Context", type.Name, type.FullName );
                        htmlEditor.MergeFields.Add( mergeField );
                        ceHtml.MergeFields.Add( mergeField );
                    }
                }
            }

            string documentRoot = GetAttributeValue( "DocumentRootFolder" );
            string imageRoot = GetAttributeValue( "ImageRootFolder" );
            htmlEditor.UserSpecificRoot = GetAttributeValue( "UserSpecificFolders" ).AsBoolean();
            htmlEditor.DocumentFolderRoot = documentRoot;
            htmlEditor.ImageFolderRoot = imageRoot;

            bool supportsVersioning = GetAttributeValue( "SupportVersions" ).AsBoolean();
            bool requireApproval = GetAttributeValue( "RequireApproval" ).AsBoolean();

            lVersion.Visible = supportsVersioning;
            lbShowVersionGrid.Visible = supportsVersioning;
            cbOverwriteVersion.Visible = supportsVersioning;
            cbOverwriteVersion.Checked = false;

            // RequireApproval only applies if SupportsVersioning=True
            upnlApproval.Visible = supportsVersioning && requireApproval;
            lbApprove.Enabled = IsUserAuthorized( "Approve" );
            lbDeny.Enabled = IsUserAuthorized( "Approve" );

            string entityValue = EntityValue();
            HtmlContent htmlContent = new HtmlContentService( new RockContext() ).GetActiveContent( this.BlockId, entityValue );

            // set Height of editors
            if ( supportsVersioning && requireApproval )
            {
                ceHtml.EditorHeight = "280";
                htmlEditor.Height = 280;
            }
            else if ( supportsVersioning )
            {
                ceHtml.EditorHeight = "350";
                htmlEditor.Height = 350;
            }
            else
            {
                ceHtml.EditorHeight = "380";
                htmlEditor.Height = 380;
            }

            ShowEditDetail( htmlContent );
        }
        /// <summary>
        /// Handles the Click event of the lbSave control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void lbSave_Click( object sender, EventArgs e )
        {
            bool supportVersioning = GetAttributeValue( "SupportVersions" ).AsBoolean();
            bool requireApproval = GetAttributeValue( "RequireApproval" ).AsBoolean();

            var rockContext = new RockContext();
            HtmlContentService htmlContentService = new HtmlContentService( rockContext );

            // get settings
            string entityValue = EntityValue();

            // get current content
            int version = hfVersion.ValueAsInt();
            HtmlContent htmlContent = htmlContentService.GetByBlockIdAndEntityValueAndVersion( this.BlockId, entityValue, version );

            // get the content depending on which mode we are in (codeeditor or ckeditor)
            string newContent = ceHtml.Visible ? ceHtml.Text : htmlEditor.Text;

            //// create a new record only in the following situations:
            ////   - this is the first time this htmlcontent block got content (new block and edited for the first time)
            ////   - the content was changed, versioning is enabled, and OverwriteVersion is not checked

            // if the existing content changed, and the overwrite option was not checked, create a new version
            if (htmlContent != null)
            {
                // Editing existing content. Check if content has changed
                if (htmlContent.Content != newContent)
                {
                    // The content has changed (different than database). Check if versioning is enabled
                    if (supportVersioning && !cbOverwriteVersion.Checked)
                    {
                        //// versioning is enabled, and they didn't choose to overwrite
                        //// set to null so that we'll create a new record
                        htmlContent = null;
                    }
                }
            }

            // if a record doesn't exist then create one
            if ( htmlContent == null )
            {
                htmlContent = new HtmlContent();
                htmlContent.BlockId = this.BlockId;
                htmlContent.EntityValue = entityValue;

                if ( supportVersioning )
                {
                    int? maxVersion = GetMaxVersionOfHtmlContent();

                    htmlContent.Version = maxVersion.HasValue ? maxVersion.Value + 1 : 1;
                }
                else
                {
                    htmlContent.Version = 1;
                }

                htmlContentService.Add( htmlContent );
            }

            htmlContent.StartDateTime = drpDateRange.LowerValue;
            htmlContent.ExpireDateTime = drpDateRange.UpperValue;
            bool currentUserCanApprove = IsUserAuthorized( "Approve" );

            if ( !requireApproval )
            {
                // if this block doesn't require Approval, mark it as approved
                htmlContent.IsApproved = true;
                htmlContent.ApprovedByPersonAliasId = CurrentPersonAliasId;
                htmlContent.ApprovedDateTime = RockDateTime.Now;
            }
            else
            {
                // since this content requires Approval, mark it as approved ONLY if the current user can approve
                // and they set the hfApprovalStatus flag to true.
                if ( currentUserCanApprove && hfApprovalStatus.Value.AsBoolean() )
                {
                    htmlContent.IsApproved = true;
                    htmlContent.ApprovedByPersonAliasId = CurrentPersonAliasId;
                    htmlContent.ApprovedDateTime = RockDateTime.Now;
                }
                else
                {
                    // if the content has changed
                    if ( htmlContent.Content != newContent )
                    {
                        nbApprovalRequired.Visible = true;
                        htmlContent.IsApproved = false;
                    }
                }
            }

            htmlContent.Content = newContent;

            rockContext.SaveChanges();

            // flush cache content
            HtmlContentService.FlushCachedContent( htmlContent.BlockId, htmlContent.EntityValue );

            ShowView();
        }
Example #12
0
        /// <summary>
        /// Shows the view.
        /// </summary>
        protected void ShowView()
        {
            mdEdit.Hide();
            pnlEditModel.Visible = false;
            upnlHtmlContent.Update();

            // prevent htmlEditor from using viewstate when not needed
            pnlEdit.EnableViewState = false;

            pnlEdit.Visible = false;
            pnlVersionGrid.Visible = false;
            string entityValue = EntityValue();
            string html = string.Empty;

            string cachedContent = GetCacheItem( entityValue ) as string;

            // if content not cached load it from DB
            if ( cachedContent == null )
            {
                HtmlContent content = new HtmlContentService( new RockContext() ).GetActiveContent( this.BlockId, entityValue );

                if ( content != null )
                {
                    if ( content.Content.HasMergeFields() )
                    {
                        var mergeFields = Rock.Web.Cache.GlobalAttributesCache.GetMergeFields( CurrentPerson );
                        if ( CurrentPerson != null )
                        {
                            mergeFields.Add( "Person", CurrentPerson );
                            mergeFields.Add( "Date", RockDateTime.Today.ToShortDateString() );
                            mergeFields.Add( "Time", RockDateTime.Now.ToShortTimeString() );
                            mergeFields.Add( "DayOfWeek", RockDateTime.Today.DayOfWeek.ConvertToString() );
                            mergeFields.Add( "RockVersion", Rock.VersionInfo.VersionInfo.GetRockProductVersionNumber() );

                            var contextObjects = new Dictionary<string, object>();
                            foreach( var contextEntityType in RockPage.GetContextEntityTypes() )
                            {
                                var contextEntity = RockPage.GetCurrentContext( contextEntityType );
                                if (contextEntity != null && contextEntity is DotLiquid.ILiquidizable)
                                {
                                    var type = Type.GetType(contextEntityType.AssemblyName ?? contextEntityType.Name);
                                    if (type != null)
                                    {
                                        contextObjects.Add( type.Name, contextEntity );
                                    }
                                }

                            }

                            if ( contextObjects.Any() )
                            {
                                mergeFields.Add( "Context", contextObjects );
                            }
                        }

                        html = content.Content.ResolveMergeFields( mergeFields );
                    }
                    else
                    {
                        html = content.Content;
                    }
                }
                else
                {
                    html = string.Empty;
                }

                // Resolve any dynamic url references
                string appRoot = ResolveRockUrl( "~/" );
                string themeRoot = ResolveRockUrl( "~~/" );
                html = html.Replace( "~~/", themeRoot ).Replace( "~/", appRoot );

                // cache content
                int cacheDuration = GetAttributeValue( "CacheDuration" ).AsInteger();
                if ( cacheDuration > 0 )
                {
                    AddCacheItem( entityValue, html, cacheDuration );
                }
            }
            else
            {
                html = cachedContent;
            }

            // add content to the content window
            lHtmlContent.Text = html;
        }
        /// <summary>
        /// Shows the view.
        /// </summary>
        protected void ShowView()
        {
            mdEdit.Hide();
            pnlEditModel.Visible = false;
            upnlHtmlContent.Update();

            // prevent htmlEditor from using viewstate when not needed
            pnlEdit.EnableViewState = false;

            pnlEdit.Visible = false;
            pnlVersionGrid.Visible = false;
            string entityValue = EntityValue();
            string html = string.Empty;

            string cachedContent = HtmlContentService.GetCachedContent( this.BlockId, entityValue );

            // if content not cached load it from DB
            if ( cachedContent == null )
            {
                using ( var rockContext = new RockContext() )
                {
                    var htmlContentService = new HtmlContentService( rockContext );
                    HtmlContent content = htmlContentService.GetActiveContent( this.BlockId, entityValue );

                    if ( content != null )
                    {
                        bool enableDebug = GetAttributeValue( "EnableDebug" ).AsBoolean();

                        if ( content.Content.HasMergeFields() || enableDebug )
                        {
                            var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields( this.RockPage, this.CurrentPerson );
                            mergeFields.Add( "CurrentPage", Rock.Lava.LavaHelper.GetPagePropertiesMergeObject( this.RockPage ) );
                            if ( CurrentPerson != null )
                            {
                                // TODO: When support for "Person" is not supported anymore (should use "CurrentPerson" instead), remove this line
                                mergeFields.AddOrIgnore( "Person", CurrentPerson );
                            }

                            mergeFields.Add( "RockVersion", Rock.VersionInfo.VersionInfo.GetRockProductVersionNumber() );
                            mergeFields.Add( "CurrentPersonCanEdit", IsUserAuthorized( Authorization.EDIT ) );
                            mergeFields.Add( "CurrentPersonCanAdministrate", IsUserAuthorized( Authorization.ADMINISTRATE ) );

                            html = content.Content.ResolveMergeFields( mergeFields );

                            // show merge fields if enable debug true
                            if ( enableDebug && IsUserAuthorized( Authorization.EDIT ) )
                            {
                                // TODO: When support for "Person" is not supported anymore (should use "CurrentPerson" instead), remove this line
                                mergeFields.Remove( "Person" );
                                html += mergeFields.lavaDebugInfo();
                            }
                        }
                        else
                        {
                            html = content.Content;
                        }
                    }
                    else
                    {
                        html = string.Empty;
                    }
                }

                // Resolve any dynamic url references
                string appRoot = ResolveRockUrl( "~/" );
                string themeRoot = ResolveRockUrl( "~~/" );
                html = html.Replace( "~~/", themeRoot ).Replace( "~/", appRoot );

                // cache content
                int cacheDuration = GetAttributeValue( "CacheDuration" ).AsInteger();
                if ( cacheDuration > 0 )
                {
                    HtmlContentService.AddCachedContent( this.BlockId, entityValue, html, cacheDuration );
                }
            }
            else
            {
                html = cachedContent;
            }

            // add content to the content window
            lHtmlContent.Text = html;
        }
        /// <summary>
        /// Handles the Click event of the lbSave control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void lbSave_Click( object sender, EventArgs e )
        {
            bool supportVersioning = GetAttributeValue( "SupportVersions" ).AsBoolean();
            bool requireApproval = GetAttributeValue( "RequireApproval" ).AsBoolean();

            var rockContext = new RockContext();
            HtmlContentService htmlContentService = new HtmlContentService( rockContext );

            // get settings
            string entityValue = EntityValue();

            // get current content
            int version = hfVersion.ValueAsInt();
            HtmlContent htmlContent = htmlContentService.GetByBlockIdAndEntityValueAndVersion( this.BlockId, entityValue, version );

            // get the content depending on which mode we are in (codeeditor or ckeditor)
            string newContent = ceHtml.Visible ? ceHtml.Text : htmlEditor.Text;

            // check if the new content is valid
            // NOTE: This is a limited check that will only warn of invalid HTML the first
            // time a user clicks the save button. Any errors encountered on the second runthrough
            // are assumed to be intentional.
            HtmlDocument doc = new HtmlDocument();
            doc.LoadHtml( newContent );
            if ( doc.ParseErrors.Count() > 0 && !nbInvalidHtml.Visible )
            {
                var reasons = doc.ParseErrors.Select( r => r.Reason ).ToList();
                StringBuilder sb = new StringBuilder();
                sb.AppendLine( "Warning: The HTML has the following errors:<ul>" );
                foreach ( var reason in reasons )
                {
                    sb.AppendLine( String.Format( "<li>{0}</li>", reason.EncodeHtml() ) );
                }
                sb.AppendLine( "</ul> <br/> If you wish to save anyway, click the save button again." );
                nbInvalidHtml.Text = sb.ToString();
                nbInvalidHtml.Visible = true;
                return;
            }

            //// create a new record only in the following situations:
            ////   - this is the first time this htmlcontent block got content (new block and edited for the first time)
            ////   - the content was changed, versioning is enabled, and OverwriteVersion is not checked

            // if the existing content changed, and the overwrite option was not checked, create a new version
            if (htmlContent != null)
            {
                // Editing existing content. Check if content has changed
                if (htmlContent.Content != newContent)
                {
                    // The content has changed (different than database). Check if versioning is enabled
                    if (supportVersioning && !cbOverwriteVersion.Checked)
                    {
                        //// versioning is enabled, and they didn't choose to overwrite
                        //// set to null so that we'll create a new record
                        htmlContent = null;
                    }
                }
            }

            // if a record doesn't exist then create one
            if ( htmlContent == null )
            {
                htmlContent = new HtmlContent();
                htmlContent.BlockId = this.BlockId;
                htmlContent.EntityValue = entityValue;

                if ( supportVersioning )
                {
                    int? maxVersion = GetMaxVersionOfHtmlContent();

                    htmlContent.Version = maxVersion.HasValue ? maxVersion.Value + 1 : 1;
                }
                else
                {
                    htmlContent.Version = 1;
                }

                htmlContentService.Add( htmlContent );
            }

            htmlContent.StartDateTime = drpDateRange.LowerValue;
            htmlContent.ExpireDateTime = drpDateRange.UpperValue;
            bool currentUserCanApprove = IsUserAuthorized( "Approve" );

            if ( !requireApproval )
            {
                // if this block doesn't require Approval, mark it as approved
                htmlContent.IsApproved = true;
                htmlContent.ApprovedByPersonAliasId = CurrentPersonAliasId;
                htmlContent.ApprovedDateTime = RockDateTime.Now;
            }
            else
            {
                // since this content requires Approval, mark it as approved ONLY if the current user can approve
                // and they set the hfApprovalStatus flag to true.
                if ( currentUserCanApprove && hfApprovalStatus.Value.AsBoolean() )
                {
                    htmlContent.IsApproved = true;
                    htmlContent.ApprovedByPersonAliasId = CurrentPersonAliasId;
                    htmlContent.ApprovedDateTime = RockDateTime.Now;
                }
                else
                {
                    // if the content has changed
                    if ( htmlContent.Content != newContent )
                    {
                        nbApprovalRequired.Visible = true;
                        htmlContent.IsApproved = false;
                    }
                }
            }

            htmlContent.Content = newContent;

            rockContext.SaveChanges();

            // flush cache content
            HtmlContentService.FlushCachedContent( htmlContent.BlockId, htmlContent.EntityValue );

            ShowView();
        }
Example #15
0
 /// <summary>
 /// Handles the Click event of the SelectVersion control.
 /// </summary>
 /// <param name="sender">The source of the event.</param>
 /// <param name="e">The <see cref="Rock.Web.UI.Controls.RowEventArgs"/> instance containing the event data.</param>
 protected void SelectVersion_Click( object sender, Rock.Web.UI.Controls.RowEventArgs e )
 {
     HtmlContent htmlContent = new HtmlContentService().Get( e.RowKeyId );
     pnlVersionGrid.Visible = false;
     pnlEdit.Visible = true;
     ShowEditDetail( htmlContent );
 }
Example #16
0
        /// <summary>
        /// Binds the grid.
        /// </summary>
        private void BindGrid()
        {
            var htmlContentService = new HtmlContentService();
            var content = htmlContentService.GetContent( this.BlockId, EntityValue() );

            var versions = content.Select( v =>
                new
                {
                    v.Id,
                    v.Version,
                    VersionText = "Version " + v.Version.ToString(),
                    ModifiedDateTime = "(" + v.LastModifiedDateTime.ToElapsedString() + ")",
                    ModifiedByPerson = v.LastModifiedPerson,
                    Approved = v.IsApproved,
                    ApprovedByPerson = v.ApprovedByPerson,
                    v.StartDateTime,
                    v.ExpireDateTime
                } ).ToList();

            gVersions.DataSource = versions;
            gVersions.GridRebind += gVersions_GridRebind;
            gVersions.DataBind();
        }
        /// <summary>
        /// Binds the grid.
        /// </summary>
        private void BindGrid()
        {
            var htmlContentService = new HtmlContentService( new RockContext() );
            var content = htmlContentService.GetContent( this.BlockId, EntityValue() ).OrderByDescending( a => a.Version ).ThenByDescending( a => a.ModifiedDateTime ).ToList();

            var versions = content.Select( v =>
                new
                {
                    v.Id,
                    v.Version,
                    VersionText = "Version " + v.Version.ToString(),
                    ModifiedDateTime = "(" + v.ModifiedDateTime.ToElapsedString() + ")",
                    ModifiedByPerson = v.ModifiedByPersonAlias != null ? v.ModifiedByPersonAlias.Person : null,
                    Approved = v.IsApproved,
                    ApprovedByPerson = v.ApprovedByPersonAlias != null ? v.ApprovedByPersonAlias.Person : null,
                    v.StartDateTime,
                    v.ExpireDateTime
                } ).ToList();

            gVersions.DataSource = versions;

            gVersions.DataBind();
        }
Example #18
0
        /// <summary>
        /// Shows the view.
        /// </summary>
        protected void ShowView()
        {
            mdEdit.Hide();

            // prevent htmlEditor from using viewstate when not needed
            pnlEdit.EnableViewState = false;

            pnlEdit.Visible = false;
            pnlVersionGrid.Visible = false;
            string entityValue = EntityValue();
            string html = string.Empty;

            string cachedContent = GetCacheItem( entityValue ) as string;

            // if content not cached load it from DB
            if ( cachedContent == null )
            {
                HtmlContent content = new HtmlContentService().GetActiveContent( this.BlockId, entityValue );

                if ( content != null )
                {
                    html = content.Content.ResolveMergeFields( Rock.Web.Cache.GlobalAttributesCache.GetMergeFields( CurrentPerson ) );
                }
                else
                {
                    html = string.Empty;
                }

                // Resolve any dynamic url references
                string appRoot = ResolveRockUrl( "~/" );
                string themeRoot = ResolveRockUrl( "~~/" );
                html = html.Replace( "~~/", themeRoot ).Replace( "~/", appRoot );

                // cache content
                int cacheDuration = GetAttributeValue( "CacheDuration" ).AsInteger() ?? 0;
                if ( cacheDuration > 0 )
                {
                    AddCacheItem( entityValue, html, cacheDuration );
                }
            }
            else
            {
                html = cachedContent;
            }

            // add content to the content window
            lHtmlContent.Text = html;
        }
Example #19
0
        /// <summary>
        /// Binds the grid.
        /// </summary>
        private void BindGrid()
        {
            var rockContext = new RockContext();

            var htmlContentService = new HtmlContentService( rockContext );
            var htmlContent = htmlContentService.Queryable();

            string pageName = "";
            string siteName = "";
            var htmlList = new List<HtmlApproval>();
            foreach ( var content in htmlContent )
            {
                content.Block.LoadAttributes();
                var blah = content.Block.GetAttributeValue( "RequireApproval" );
                if ( !string.IsNullOrEmpty( blah ) && blah.ToLower() == "true" )
                {
                    var pageService = new PageService( rockContext );
                    if ( content.Block.PageId != null )
                    {
                        var page = pageService.Get( (int)content.Block.PageId );
                        if ( page != null )
                        {
                            pageName = page.InternalName;
                            while ( page.ParentPageId != null )
                            {
                                page = pageService.Get( (int)page.ParentPageId );
                            }
                            var siteService = new SiteService( rockContext );
                            siteName = siteService.GetByDefaultPageId( page.Id ).Select( s => s.Name ).FirstOrDefault();
                        }
                    }

                    var htmlApprovalClass = new HtmlApproval();
                    htmlApprovalClass.SiteName = siteName;
                    htmlApprovalClass.PageName = pageName;
                    htmlApprovalClass.Block = content.Block;
                    htmlApprovalClass.BlockId = content.BlockId;
                    htmlApprovalClass.Content = content.Content;
                    htmlApprovalClass.Id = content.Id;
                    htmlApprovalClass.IsApproved = content.IsApproved;
                    htmlApprovalClass.ApprovedByPerson = content.ApprovedByPerson;
                    htmlApprovalClass.ApprovedByPersonId = content.ApprovedByPersonId;
                    htmlApprovalClass.ApprovedDateTime = content.ApprovedDateTime;

                    htmlList.Add( htmlApprovalClass );
                }
            }

            // Filter by Site
            if ( ddlSiteFilter.SelectedIndex > 0 )
            {
                if ( ddlSiteFilter.SelectedValue.ToLower() != "all" )
                {
                    htmlList = htmlList.Where( h => h.SiteName == ddlSiteFilter.SelectedValue ).ToList();
                }
            }

            // Filter by approved/unapproved
            if ( ddlApprovedFilter.SelectedIndex > -1 )
            {
                if ( ddlApprovedFilter.SelectedValue.ToLower() == "unapproved" )
                {
                    htmlList = htmlList.Where( a => a.IsApproved == false ).ToList();
                }
                else if ( ddlApprovedFilter.SelectedValue.ToLower() == "approved" )
                {
                    htmlList = htmlList.Where( a => a.IsApproved == true ).ToList();
                }
            }

            // Filter by the person that approved the content
            if ( _canApprove )
            {
                int personId = 0;
                if ( int.TryParse( gContentListFilter.GetUserPreference( "Approved By" ), out personId ) && personId != 0 )
                {
                    htmlList = htmlList.Where( a => a.ApprovedByPersonId.HasValue && a.ApprovedByPersonId.Value == personId ).ToList();
                }
            }

            SortProperty sortProperty = gContentList.SortProperty;
            if ( sortProperty != null )
            {
                gContentList.DataSource = htmlList.AsQueryable().Sort( sortProperty ).ToList();
            }
            else
            {
                gContentList.DataSource = htmlList.OrderBy( h => h.Id ).ToList();
            }

            gContentList.DataBind();
        }