/// <summary>
        /// Gets a shortcode definition for the specified shortcode name.
        /// </summary>
        /// <param name="shortcodeName"></param>
        /// <returns></returns>
        public static DynamicShortcodeDefinition GetShortcodeDefinition(string shortcodeName)
        {
            DynamicShortcodeDefinition newShortcode = null;

            var shortcodeDefinition = LavaShortcodeCache.All().Where(c => c.TagName != null && c.TagName.Equals(shortcodeName, StringComparison.OrdinalIgnoreCase)).FirstOrDefault();

            if (shortcodeDefinition == null)
            {
                return(null);
            }

            newShortcode = new DynamicShortcodeDefinition();

            newShortcode.Name           = shortcodeDefinition.Name;
            newShortcode.TemplateMarkup = shortcodeDefinition.Markup;

            var parameters = RockSerializableDictionary.FromUriEncodedString(shortcodeDefinition.Parameters);

            newShortcode.Parameters = new Dictionary <string, string>(parameters.Dictionary);

            newShortcode.EnabledLavaCommands = shortcodeDefinition.EnabledLavaCommands.SplitDelimitedValues(",").ToList();

            if (shortcodeDefinition.TagType == TagType.Block)
            {
                newShortcode.ElementType = LavaShortcodeTypeSpecifier.Block;
            }
            else
            {
                newShortcode.ElementType = LavaShortcodeTypeSpecifier.Inline;
            }

            return(newShortcode);
        }
        /// <summary>
        /// Register the specified shortcodes with the Lava Engine.
        /// </summary>
        /// <param name="engine"></param>
        public static void RegisterShortcodes(ILavaEngine engine)
        {
            ClearCache();

            // Register shortcodes defined in the code base.
            try
            {
                var shortcodeTypes = Rock.Reflection.FindTypes(typeof(ILavaShortcode)).Select(a => a.Value).ToList();

                foreach (var shortcodeType in shortcodeTypes)
                {
                    engine.RegisterShortcode(shortcodeType.Name, (shortcodeName) =>
                    {
                        var shortcode = Activator.CreateInstance(shortcodeType) as ILavaShortcode;

                        return(shortcode);
                    });
                }
            }
            catch (Exception ex)
            {
                ExceptionLogService.LogException(ex, null);
            }

            // Register shortcodes defined in the current database.
            var shortCodes = LavaShortcodeCache.All();

            foreach (var shortcode in shortCodes)
            {
                engine.RegisterShortcode(shortcode.TagName, (shortcodeName) => GetShortcodeDefinition(shortcodeName));
            }
        }
        /// <summary>
        /// Initializes the specified tag name.
        /// </summary>
        /// <param name="tagName">Name of the tag.</param>
        /// <param name="markup">The markup.</param>
        /// <param name="tokens">The tokens.</param>
        /// <exception cref="System.Exception">Could not find the variable to place results in.</exception>
        public override void Initialize(string tagName, string markup, List <string> tokens)
        {
            _markup    = markup;
            _tagName   = tagName;
            _shortcode = LavaShortcodeCache.All().Where(c => c.TagName == tagName).FirstOrDefault();

            base.Initialize(tagName, markup, tokens);
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Initializes the specified tag name.
        /// </summary>
        /// <param name="tagName">Name of the tag.</param>
        /// <param name="markup">The markup.</param>
        /// <param name="tokens">The tokens.</param>
        /// <exception cref="System.Exception">Could not find the variable to place results in.</exception>
        public override void Initialize(string tagName, string markup, List <string> tokens)
        {
            _markup    = markup;
            _tagName   = tagName;
            _shortcode = LavaShortcodeCache.Read(_tagName);

            base.Initialize(tagName, markup, tokens);
        }
        /// <summary>
        /// Handles the Click event of the btnSave 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 btnSave_Click(object sender, EventArgs e)
        {
            LavaShortcode lavaShortcode;
            var           rockContext          = new RockContext();
            var           lavaShortCodeService = new LavaShortcodeService(rockContext);

            if (lavaShortCodeService.Queryable().Any(a => a.TagName == tbTagName.Text) && hfOriginalTagName.Value != tbTagName.Text)
            {
                Page.ModelState.AddModelError("DuplicateTag", "Tag with the same name is already in use.");
                return;
            }

            int lavaShortCode = hfLavaShortcodeId.ValueAsInt();

            if (lavaShortCode == 0)
            {
                lavaShortcode = new LavaShortcode();
                lavaShortCodeService.Add(lavaShortcode);
            }
            else
            {
                lavaShortcode = lavaShortCodeService.Get(lavaShortCode);
            }

            lavaShortcode.Name                = tbLavaShortcodeName.Text;
            lavaShortcode.IsActive            = cbIsActive.Checked;
            lavaShortcode.Description         = tbDescription.Text;
            lavaShortcode.Documentation       = htmlDocumentation.Text;
            lavaShortcode.TagType             = rblTagType.SelectedValueAsEnum <TagType>();
            lavaShortcode.TagName             = tbTagName.Text;
            lavaShortcode.Markup              = ceMarkup.Text;
            lavaShortcode.Parameters          = kvlParameters.Value;
            lavaShortcode.EnabledLavaCommands = String.Join(",", lcpLavaCommands.SelectedLavaCommands);

            rockContext.SaveChanges();

            // unregister shortcode
            if (hfOriginalTagName.Value.IsNotNullOrWhitespace())
            {
                Template.UnregisterShortcode(hfOriginalTagName.Value);
            }

            // register shortcode
            if (lavaShortcode.TagType == TagType.Block)
            {
                Template.RegisterShortcode <DynamicShortcodeBlock>(lavaShortcode.TagName);
            }
            else
            {
                Template.RegisterShortcode <DynamicShortcodeInline>(lavaShortcode.TagName);
            }

            LavaShortcodeCache.Flush(lavaShortcode.Id);

            NavigateToParentPage();
        }
        /// <summary>
        /// Method that will be run at Rock startup
        /// </summary>
        public override void OnStartup()
        {
            // get all the block dynamic shortcodes and register them
            var blockShortCodes = LavaShortcodeCache.All().Where(s => s.TagType == TagType.Block);

            foreach (var shortcode in blockShortCodes)
            {
                // register this shortcode
                Template.RegisterShortcode <DynamicShortcodeBlock>(shortcode.TagName);
            }
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Method that will be run at Rock startup
        /// </summary>
        public override void OnStartup()
        {
            // get all the inline dynamic shortcodes and register them
            var inlineShortCodes = LavaShortcodeCache.All().Where(s => s.TagType == TagType.Inline);

            foreach (var shortcode in inlineShortCodes)
            {
                // register this shortcode
                Template.RegisterShortcode <DynamicShortcodeInline>(shortcode.TagName);
            }
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Raises the <see cref="E:System.Web.UI.Control.Load" /> event.
        /// </summary>
        /// <param name="e">The <see cref="T:System.EventArgs" /> object that contains the event data.</param>
        protected override void OnLoad(EventArgs e)
        {
            RouteCollection routes = RouteTable.Routes;

            PageRouteService pageRouteService = new PageRouteService(new Rock.Data.RockContext());
            var pageRoutes = pageRouteService.Queryable().ToList();


            // Check to see if we have any missing routes.  If so, simply run reregister.
            foreach (var pageRoute in pageRoutes)
            {
                var route = routes.OfType <Route>().Where(a => a.Url == pageRoute.Route && a.PageIds().Contains(pageRoute.PageId)).FirstOrDefault();

                if (route == null)
                {
                    nbNotification.NotificationBoxType = Rock.Web.UI.Controls.NotificationBoxType.Warning;
                    nbNotification.Text = "Routes were out-of-date.  Running reregister routes.";

                    ReRegisterRoutes();
                    break;
                }
            }

            // Check to see if we have any missing shortcodes
            var outOfDate = RockDateTime.Now.AddMinutes(-30);
            var sc        = new LavaShortcodeService(new Rock.Data.RockContext()).Queryable().Where(l => l.CreatedDateTime > outOfDate || l.ModifiedDateTime > outOfDate).ToList();

            if (sc.Count > 0)
            {
                nbNotification.NotificationBoxType = Rock.Web.UI.Controls.NotificationBoxType.Warning;
                nbNotification.Text = "Shortcodes were out-of-date.  Running register shortcodes. " + sc.Count;
                foreach (var code in sc)
                {
                    // register shortcode
                    if (code.TagType == TagType.Block)
                    {
                        Template.RegisterShortcode <DynamicShortcodeBlock>(code.TagName);
                    }
                    else
                    {
                        Template.RegisterShortcode <DynamicShortcodeInline>(code.TagName);
                    }
                }

                LavaShortcodeCache.Clear();
            }
        }
Ejemplo n.º 9
0
        private static void InitializeLavaShortcodes(ILavaEngine engine)
        {
            // Register shortcodes defined in the codebase.
            try
            {
                var shortcodeTypes = Rock.Reflection.FindTypes(typeof(ILavaShortcode)).Select(a => a.Value).ToList();

                foreach (var shortcodeType in shortcodeTypes)
                {
                    // Create an instance of the shortcode to get the registration name.
                    var instance = Activator.CreateInstance(shortcodeType) as ILavaShortcode;

                    var name = instance.SourceElementName;

                    if (string.IsNullOrWhiteSpace(name))
                    {
                        name = shortcodeType.Name;
                    }

                    // Register the shortcode with a factory method to create a new instance of the shortcode from the System.Type defined in the codebase.
                    engine.RegisterShortcode(name, (shortcodeName) =>
                    {
                        var shortcode = Activator.CreateInstance(shortcodeType) as ILavaShortcode;

                        return(shortcode);
                    });
                }
            }
            catch (Exception ex)
            {
                ExceptionLogService.LogException(ex, null);
            }

            // Register shortcodes defined in the current database.
            var shortCodes = LavaShortcodeCache.All();

            foreach (var shortcode in shortCodes)
            {
                // Register the shortcode with the current Lava Engine.
                // The provider is responsible for retrieving the shortcode definition from the data store and managing the web-based shortcode cache.
                WebsiteLavaShortcodeProvider.RegisterShortcode(engine, shortcode.TagName);
            }
        }
        private static void RegisterDynamicShortcodes(ILavaEngine engine)
        {
            // Register dynamic shortcodes with a factory method to ensure that the latest definition is retrieved from the global cache each time the shortcode is used.
            Func <string, DynamicShortcodeDefinition> shortCodeFactory = (shortcodeName) =>
            {
                var shortcodeDefinition = LavaShortcodeCache.All().Where(c => c.TagName == shortcodeName).FirstOrDefault();

                if (shortcodeDefinition == null)
                {
                    return(null);
                }

                var newShortcode = new DynamicShortcodeDefinition();

                newShortcode.Name           = shortcodeDefinition.Name;
                newShortcode.TemplateMarkup = shortcodeDefinition.Markup;

                var parameters = RockSerializableDictionary.FromUriEncodedString(shortcodeDefinition.Parameters);

                newShortcode.Parameters = new Dictionary <string, string>(parameters.Dictionary);

                newShortcode.EnabledLavaCommands = shortcodeDefinition.EnabledLavaCommands.SplitDelimitedValues(",", StringSplitOptions.RemoveEmptyEntries).ToList();

                if (shortcodeDefinition.TagType == TagType.Block)
                {
                    newShortcode.ElementType = LavaShortcodeTypeSpecifier.Block;
                }
                else
                {
                    newShortcode.ElementType = LavaShortcodeTypeSpecifier.Inline;
                }

                return(newShortcode);
            };

            var shortCodes = LavaShortcodeCache.All();

            foreach (var shortcode in shortCodes)
            {
                engine.RegisterShortcode(shortcode.TagName, shortCodeFactory);
            }
        }
Ejemplo n.º 11
0
 /// <summary>
 /// Updates any Cache Objects that are associated with this entity
 /// </summary>
 /// <param name="entityState">State of the entity.</param>
 /// <param name="dbContext">The database context.</param>
 public void UpdateCache(EntityState entityState, Rock.Data.DbContext dbContext)
 {
     LavaShortcodeCache.UpdateCachedEntity(this.Id, entityState);
 }
Ejemplo n.º 12
0
 /// <summary>
 /// Gets the cache object associated with this Entity
 /// </summary>
 /// <returns></returns>
 public IEntityCache GetCacheObject()
 {
     return(LavaShortcodeCache.Get(this.Id));
 }
        /// <summary>
        /// Renders the specified context.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="result">The result.</param>
        public override void Render(Context context, TextWriter result)
        {
            // get enabled security commands
            if (context.Registers.ContainsKey("EnabledCommands"))
            {
                _enabledSecurityCommands = context.Registers["EnabledCommands"].ToString();
            }

            var shortcode = LavaShortcodeCache.Get(_shortcode.Id);

            if (shortcode != null)
            {
                var parms = ParseMarkup(_markup, context);

                // add a unique id so shortcodes have easy access to one
                parms.AddOrReplace("uniqueid", "id-" + Guid.NewGuid().ToString());

                // keep track of the recursion depth
                int currentRecurrsionDepth = 0;
                if (parms.ContainsKey("RecursionDepth"))
                {
                    currentRecurrsionDepth = parms["RecursionDepth"].ToString().AsInteger() + 1;

                    if (currentRecurrsionDepth > _maxRecursionDepth)
                    {
                        result.Write("A recursive loop was detected and processing of this shortcode has stopped.");
                        return;
                    }
                }
                parms.AddOrReplace("RecursionDepth", currentRecurrsionDepth);

                var lavaTemplate = shortcode.Markup;
                var blockMarkup  = _blockMarkup.ToString().ResolveMergeFields(_internalMergeFields, _enabledSecurityCommands);

                // pull child parameters from block content
                Dictionary <string, object> childParamters;
                blockMarkup = GetChildParameters(blockMarkup, out childParamters);
                foreach (var item in childParamters)
                {
                    parms.AddOrReplace(item.Key, item.Value);
                }

                // merge the block markup in
                if (blockMarkup.IsNotNullOrWhiteSpace())
                {
                    Regex rgx = new Regex(@"{{\s*blockContent\s*}}", RegexOptions.IgnoreCase);
                    lavaTemplate = rgx.Replace(lavaTemplate, blockMarkup);

                    parms.AddOrReplace("blockContentExists", true);
                }
                else
                {
                    parms.AddOrReplace("blockContentExists", false);
                }

                // next ensure they did not use any entity commands in the block that are not allowed
                // this is needed as the shortcode it configured to allow entities for processing that
                // might allow more entities than the source block, template, action, etc allows
                var securityCheck = blockMarkup.ResolveMergeFields(new Dictionary <string, object>(), _enabledSecurityCommands);

                Regex securityPattern = new Regex(String.Format(RockLavaBlockBase.NotAuthorizedMessage, ".*"));
                Match securityMatch   = securityPattern.Match(securityCheck);

                if (securityMatch.Success)
                {
                    result.Write(securityMatch.Value);   // return security error message
                }
                else
                {
                    if (shortcode.EnabledLavaCommands.IsNotNullOrWhiteSpace())
                    {
                        _enabledSecurityCommands = shortcode.EnabledLavaCommands;
                    }

                    var results = lavaTemplate.ResolveMergeFields(parms, _enabledSecurityCommands);
                    result.Write(results.Trim());
                    base.Render(context, result);
                }
            }
            else
            {
                result.Write($"An error occurred while processing the {0} shortcode.", _tagName);
            }
        }
 /// <summary>
 /// Clears all of the entries from the shortcode cache.
 /// </summary>
 public static void ClearCache()
 {
     LavaShortcodeCache.Clear();
 }