private async ValueTask BuildViewModel(MarkdownBodyPartViewModel model, MarkdownBodyPart markdownBodyPart, BuildPartDisplayContext context)
        {
            model.Markdown         = markdownBodyPart.Markdown;
            model.MarkdownBodyPart = markdownBodyPart;
            model.ContentItem      = markdownBodyPart.ContentItem;

            // The default Markdown option is to entity escape html
            // so filters must be run after the markdown has been processed.
            model.Html = _markdownService.ToHtml(model.Markdown ?? "");

            var settings = context.TypePartDefinition.GetSettings <MarkdownBodyPartSettings>();

            // The liquid rendering is for backwards compatibility and can be removed in a future version.
            if (!settings.SanitizeHtml)
            {
                model.Html = await _liquidTemplateManager.RenderStringAsync(model.Html, _htmlEncoder, model,
                                                                            new Dictionary <string, FluidValue>() { ["ContentItem"] = new ObjectValue(model.ContentItem) });
            }

            model.Html = await _shortcodeService.ProcessAsync(model.Html,
                                                              new Context
            {
                ["ContentItem"]        = markdownBodyPart.ContentItem,
                ["TypePartDefinition"] = context.TypePartDefinition
            });

            if (settings.SanitizeHtml)
            {
                model.Html = _htmlSanitizerService.Sanitize(model.Html ?? "");
            }
        }
示例#2
0
        public override async Task UpdatedAsync(UpdateContentContext context, TitlePart part)
        {
            var settings = GetSettings(part);

            // Do not compute the title if the user can modify it and the text is already set.
            if (settings.Options == TitlePartOptions.Editable && !String.IsNullOrWhiteSpace(part.ContentItem.DisplayText))
            {
                return;
            }

            if (!String.IsNullOrEmpty(settings.Pattern))
            {
                var model = new TitlePartViewModel()
                {
                    Title       = part.Title,
                    TitlePart   = part,
                    ContentItem = part.ContentItem
                };

                var title = await _liquidTemplateManager.RenderStringAsync(settings.Pattern, NullEncoder.Default, model,
                                                                           new Dictionary <string, FluidValue>() { ["ContentItem"] = new ObjectValue(model.ContentItem) });

                title = title.Replace("\r", String.Empty).Replace("\n", String.Empty);

                part.Title = title;
                part.ContentItem.DisplayText = title;
                part.Apply();
            }
        }
示例#3
0
        public async Task <ExecuteGQLQueryResults> ExecuteQuery(string queryTemplate, IDictionary <string, object> parameters)
        {
            var schema = await _schemaService.GetSchemaAsync();

            var gqlSettings    = _settingsAccessor.Value;
            var tokenizedQuery = await _liquidTemplateManager.RenderStringAsync(queryTemplate, NullEncoder.Default, parameters.Select(x => new KeyValuePair <string, FluidValue>(x.Key, FluidValue.Create(x.Value, _templateOptions))));

            var result = new ExecuteGQLQueryResults()
            {
                TokenizedQuery = tokenizedQuery
            };

            result.Result = await _executer.ExecuteAsync(_ =>
            {
                _.Schema           = schema;
                _.Query            = tokenizedQuery;
                _.UserContext      = gqlSettings.BuildUserContext?.Invoke(_httpContextAccessor.HttpContext);
                _.ExposeExceptions = gqlSettings.ExposeExceptions;
                _.ValidationRules  = DocumentValidator.CoreRules()
                                     .Concat(_validationRules);
                _.ComplexityConfiguration = new ComplexityConfiguration
                {
                    MaxDepth      = gqlSettings.MaxDepth,
                    MaxComplexity = gqlSettings.MaxComplexity,
                    FieldImpact   = gqlSettings.FieldImpact
                };
                _.Listeners.Add(_dataLoaderDocumentListener);
            });

            return(result);
        }
示例#4
0
        public override async Task GetContentItemAspectAsync(ContentItemAspectContext context, PreviewPart part)
        {
            var pattern = GetPattern(part);

            if (!String.IsNullOrEmpty(pattern))
            {
                await context.ForAsync <PreviewAspect>(async previewAspect =>
                {
                    var model = new PreviewPartViewModel()
                    {
                        PreviewPart = part,
                        ContentItem = part.ContentItem
                    };

                    previewAspect.PreviewUrl = await _liquidTemplateManager.RenderStringAsync(pattern, NullEncoder.Default, model,
                                                                                              new Dictionary <string, FluidValue>()
                    {
                        ["ContentItem"] = new ObjectValue(model.ContentItem)
                    });

                    previewAspect.PreviewUrl = previewAspect.PreviewUrl.Replace("\r", String.Empty).Replace("\n", String.Empty);
                });
            }

            return;
        }
        public override IDisplayResult Display(HtmlField field, BuildFieldDisplayContext context)
        {
            return(Initialize <DisplayHtmlFieldViewModel>(GetDisplayShapeType(context), async model =>
            {
                model.Html = field.Html;
                model.Field = field;
                model.Part = context.ContentPart;
                model.PartFieldDefinition = context.PartFieldDefinition;

                var settings = context.PartFieldDefinition.GetSettings <HtmlFieldSettings>();
                if (!settings.SanitizeHtml)
                {
                    model.Html = await _liquidTemplateManager.RenderStringAsync(field.Html, _htmlEncoder, model,
                                                                                new Dictionary <string, FluidValue>()
                    {
                        ["ContentItem"] = new ObjectValue(field.ContentItem)
                    });
                }

                model.Html = await _shortcodeService.ProcessAsync(model.Html,
                                                                  new Context
                {
                    ["ContentItem"] = field.ContentItem,
                    ["PartFieldDefinition"] = context.PartFieldDefinition
                });
            })
                   .Location("Detail", "Content")
                   .Location("Summary", "Content"));
        }
示例#6
0
 public Task <string> RenderLiquid(string liquid, object model)
 {
     if (!string.IsNullOrWhiteSpace(liquid))
     {
         return(_liquidTemplateManager.RenderStringAsync(liquid, _htmlEncoder, model, null));
     }
     return(Task.FromResult(liquid));
 }
示例#7
0
        public override Task GetContentItemAspectAsync(ContentItemAspectContext context, AttachContentPart part)
        {
            return(context.ForAsync <BodyAspect>(async bodyAspect =>
            {
                if (_bodyAspect != null)
                {
                    bodyAspect.Body = _bodyAspect;
                    return;
                }

                try
                {
                    var contentTypeDefinition = _contentDefinitionManager.GetTypeDefinition(part.ContentItem.ContentType);
                    var contentTypePartDefinition = contentTypeDefinition.Parts.FirstOrDefault(x => String.Equals(x.PartDefinition.Name, "MarkdownBodyPart"));
                    var settings = contentTypePartDefinition.GetSettings <MarkdownBodyPartSettings>();

                    // The default Markdown option is to entity escape html
                    // so filters must be run after the markdown has been processed.
                    var html = _markdownService.ToHtml(part.AttachContent);

                    // The liquid rendering is for backwards compatability and can be removed in a future version.
                    if (!settings.SanitizeHtml)
                    {
                        var model = new AttachContentPartViewModel()
                        {
                            AttachContentPart = part,
                            ContentItem = part.ContentItem
                        };

                        html = await _liquidTemplateManager.RenderStringAsync(html, _htmlEncoder, model,
                                                                              new Dictionary <string, FluidValue>()
                        {
                            ["ContentItem"] = new ObjectValue(model.ContentItem)
                        });
                    }

                    html = await _shortcodeService.ProcessAsync(html,
                                                                new Context
                    {
                        ["ContentItem"] = part.ContentItem,
                        ["TypePartDefinition"] = contentTypePartDefinition
                    });

                    if (settings.SanitizeHtml)
                    {
                        html = _htmlSanitizerService.Sanitize(html);
                    }

                    bodyAspect.Body = _bodyAspect = new HtmlString(html);
                }
                catch
                {
                    bodyAspect.Body = HtmlString.Empty;
                }
            }));
        }
        private async Task <DefaultMetaTags> GetDefaultMetaTagsAsync(ISite siteSettings, MetaTagsPart part)
        {
            var settings = siteSettings.As <ContentItem>("DefaultMetaTags")?.Get <ContentPart>("DefaultMetaTags");

            if (settings == null)
            {
                return(new DefaultMetaTags());
            }

            var imagePath = settings.Get <MediaField>("Image")?.Paths?.FirstOrDefault() ?? string.Empty;
            var values    = new Dictionary <string, FluidValue>()
            {
                ["ContentItem"] = new ObjectValue(part.ContentItem)
            };

            return(new DefaultMetaTags
            {
                Custom = settings.Get <DictionaryField>("Custom")?.Data,
                Description = await _liquidTemplateManager.RenderStringAsync(settings.Get <TextField>("Description")?.Text, NullEncoder.Default, null, values),
                ImagePath = imagePath,
                Title = await _liquidTemplateManager.RenderStringAsync(settings.Get <TextField>("Title")?.Text, NullEncoder.Default, null, values)
            });
        }
示例#9
0
        public async Task <IActionResult> Query(AdminQueryViewModel model)
        {
            if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageSqlQueries))
            {
                return(Forbid());
            }

            if (String.IsNullOrWhiteSpace(model.DecodedQuery))
            {
                return(View(model));
            }

            if (String.IsNullOrEmpty(model.Parameters))
            {
                model.Parameters = "{ }";
            }

            var stopwatch = new Stopwatch();

            stopwatch.Start();

            var connection = _store.Configuration.ConnectionFactory.CreateConnection();
            var dialect    = _store.Configuration.SqlDialect;

            var parameters = JsonConvert.DeserializeObject <Dictionary <string, object> >(model.Parameters);

            var tokenizedQuery = await _liquidTemplateManager.RenderStringAsync(model.DecodedQuery, NullEncoder.Default, parameters.Select(x => new KeyValuePair <string, FluidValue>(x.Key, FluidValue.Create(x.Value, _templateOptions))));

            model.FactoryName = _store.Configuration.ConnectionFactory.GetType().FullName;

            if (SqlParser.TryParse(tokenizedQuery, dialect, _store.Configuration.TablePrefix, parameters, out var rawQuery, out var messages))
            {
                model.RawSql     = rawQuery;
                model.Parameters = JsonConvert.SerializeObject(parameters, Formatting.Indented);

                try
                {
                    using (connection)
                    {
                        await connection.OpenAsync();

                        model.Documents = await connection.QueryAsync(rawQuery, parameters);
                    }
                }
                catch (Exception e)
                {
                    ModelState.AddModelError("", S["An error occurred while executing the SQL query: {0}", e.Message]);
                }
            }
示例#10
0
        public async Task <T> EvaluateAsync <T>(WorkflowExpression <T> expression, WorkflowExecutionContext workflowContext, TextEncoder encoder)
        {
            var templateContext   = new TemplateContext(_templateOptions);
            var expressionContext = new WorkflowExecutionExpressionContext(templateContext, workflowContext);

            await _workflowContextHandlers.InvokeAsync((h, expressionContext) => h.EvaluatingExpressionAsync(expressionContext), expressionContext, _logger);

            // Set WorkflowContext as a local scope property.
            var result = await _liquidTemplateManager.RenderStringAsync(
                expression.Expression,
                encoder ?? NullEncoder.Default,
                new Dictionary <string, FluidValue>() { ["Workflow"] = new ObjectValue(workflowContext) }
                );

            return(String.IsNullOrWhiteSpace(result) ? default : (T)Convert.ChangeType(result, typeof(T)));
        }
示例#11
0
        public async Task <IQueryResults> ExecuteQueryAsync(Query query, IDictionary <string, object> parameters)
        {
            var luceneQuery        = query as LuceneQuery;
            var luceneQueryResults = new LuceneQueryResults();

            await _luceneIndexProvider.SearchAsync(luceneQuery.Index, async searcher =>
            {
                var tokenizedContent = await _liquidTemplateManager.RenderStringAsync(luceneQuery.Template, _javaScriptEncoder, parameters.Select(x => new KeyValuePair <string, FluidValue>(x.Key, FluidValue.Create(x.Value, _templateOptions))));

                var parameterizedQuery = JObject.Parse(tokenizedContent);

                var analyzer             = _luceneAnalyzerManager.CreateAnalyzer(await _luceneIndexSettingsService.GetIndexAnalyzerAsync(luceneQuery.Index));
                var context              = new LuceneQueryContext(searcher, LuceneSettings.DefaultVersion, analyzer);
                var docs                 = await _queryService.SearchAsync(context, parameterizedQuery);
                luceneQueryResults.Count = docs.Count;

                if (luceneQuery.ReturnContentItems)
                {
                    // We always return an empty collection if the bottom lines queries have no results.
                    luceneQueryResults.Items = new List <ContentItem>();

                    // Load corresponding content item versions
                    var indexedContentItemVersionIds = docs.TopDocs.ScoreDocs.Select(x => searcher.Doc(x.Doc).Get("Content.ContentItem.ContentItemVersionId")).ToArray();
                    var dbContentItems = await _session.Query <ContentItem, ContentItemIndex>(x => x.ContentItemVersionId.IsIn(indexedContentItemVersionIds)).ListAsync();

                    // Reorder the result to preserve the one from the lucene query
                    if (dbContentItems.Any())
                    {
                        var dbContentItemVersionIds = dbContentItems.ToDictionary(x => x.ContentItemVersionId, x => x);
                        var indexedAndInDB          = indexedContentItemVersionIds.Where(dbContentItemVersionIds.ContainsKey);
                        luceneQueryResults.Items    = indexedAndInDB.Select(x => dbContentItemVersionIds[x]).ToArray();
                    }
                }
                else
                {
                    var results = new List <JObject>();
                    foreach (var document in docs.TopDocs.ScoreDocs.Select(hit => searcher.Doc(hit.Doc)))
                    {
                        results.Add(new JObject(document.Select(x => new JProperty(x.Name, x.GetStringValue()))));
                    }

                    luceneQueryResults.Items = results;
                }
            });

            return(luceneQueryResults);
        }
示例#12
0
        public override Task GetContentItemAspectAsync(ContentItemAspectContext context)
        {
            var contentTypeDefinition = _contentDefinitionManager.GetTypeDefinition(context.ContentItem.ContentType);

            if (contentTypeDefinition == null)
            {
                return(Task.CompletedTask);
            }

            return(context.ForAsync <FullTextAspect>(async fullTextAspect =>
            {
                var contentTypeDefinition = _contentDefinitionManager.GetTypeDefinition(context.ContentItem.ContentType);
                var settings = contentTypeDefinition.GetSettings <FullTextAspectSettings>();

                if (settings.IncludeDisplayText)
                {
                    fullTextAspect.Segments.Add(context.ContentItem.DisplayText);
                }

                if (settings.IncludeBodyAspect)
                {
                    // Lazy resolution to prevent cyclic dependency of content handlers
                    var contentManager = _serviceProvider.GetRequiredService <IContentManager>();
                    var bodyAspect = await contentManager.PopulateAspectAsync <BodyAspect>(context.ContentItem);

                    if (bodyAspect != null && bodyAspect.Body != null)
                    {
                        using var sw = new ZStringWriter();
                        // Don't encode the body
                        bodyAspect.Body.WriteTo(sw, NullHtmlEncoder.Default);
                        fullTextAspect.Segments.Add(sw.ToString());
                    }
                }

                if (settings.IncludeFullTextTemplate && !String.IsNullOrEmpty(settings.FullTextTemplate))
                {
                    var result = await _liquidTemplateManager.RenderStringAsync(settings.FullTextTemplate, NullEncoder.Default, context.ContentItem,
                                                                                new Dictionary <string, FluidValue>()
                    {
                        ["ContentItem"] = new ObjectValue(context.ContentItem)
                    });

                    fullTextAspect.Segments.Add(result);
                }
            }));
        }
        private async Task GenerateContainerPathFromPatternAsync(AutoroutePart part)
        {
            // Compute the Path only if it's empty
            if (!String.IsNullOrWhiteSpace(part.Path))
            {
                return;
            }

            var pattern = GetPattern(part);

            if (!String.IsNullOrEmpty(pattern))
            {
                var model = new AutoroutePartViewModel()
                {
                    Path          = part.Path,
                    AutoroutePart = part,
                    ContentItem   = part.ContentItem
                };

                _contentManager ??= _serviceProvider.GetRequiredService <IContentManager>();

                var cultureAspect = await _contentManager.PopulateAspectAsync(part.ContentItem, new CultureAspect());

                using (CultureScope.Create(cultureAspect.Culture))
                {
                    part.Path = await _liquidTemplateManager.RenderStringAsync(pattern, NullEncoder.Default, model,
                                                                               new Dictionary <string, FluidValue>() { [nameof(ContentItem)] = new ObjectValue(model.ContentItem) });
                }

                part.Path = part.Path.Replace("\r", String.Empty).Replace("\n", String.Empty);

                if (part.Path?.Length > AutoroutePart.MaxPathLength)
                {
                    part.Path = part.Path.Substring(0, AutoroutePart.MaxPathLength);
                }

                if (!await IsAbsolutePathUniqueAsync(part.Path, part.ContentItem.ContentItemId))
                {
                    part.Path = await GenerateUniqueAbsolutePathAsync(part.Path, part.ContentItem.ContentItemId);
                }

                part.Apply();
            }
        }
        public override Task GetContentItemAspectAsync(ContentItemAspectContext context, HtmlBodyPart part)
        {
            return(context.ForAsync <BodyAspect>(async bodyAspect =>
            {
                try
                {
                    var contentTypeDefinition = _contentDefinitionManager.GetTypeDefinition(part.ContentItem.ContentType);
                    var contentTypePartDefinition = contentTypeDefinition.Parts.FirstOrDefault(x => string.Equals(x.PartDefinition.Name, "HtmlBodyPart"));
                    var settings = contentTypePartDefinition.GetSettings <HtmlBodyPartSettings>();

                    var html = part.Html;

                    if (!settings.SanitizeHtml)
                    {
                        var model = new HtmlBodyPartViewModel()
                        {
                            Html = part.Html,
                            HtmlBodyPart = part,
                            ContentItem = part.ContentItem
                        };

                        html = await _liquidTemplateManager.RenderStringAsync(html, _htmlEncoder, model,
                                                                              new Dictionary <string, FluidValue>()
                        {
                            ["ContentItem"] = new ObjectValue(model.ContentItem)
                        });
                    }

                    html = await _shortcodeService.ProcessAsync(html,
                                                                new Context
                    {
                        ["ContentItem"] = part.ContentItem,
                        ["TypePartDefinition"] = contentTypePartDefinition
                    });

                    bodyAspect.Body = new HtmlString(html);
                }
                catch
                {
                    bodyAspect.Body = HtmlString.Empty;
                }
            }));
        }
        private async ValueTask BuildViewModelAsync(HtmlBodyPartViewModel model, HtmlBodyPart htmlBodyPart, BuildPartDisplayContext context)
        {
            model.Html         = htmlBodyPart.Html;
            model.HtmlBodyPart = htmlBodyPart;
            model.ContentItem  = htmlBodyPart.ContentItem;
            var settings = context.TypePartDefinition.GetSettings <HtmlBodyPartSettings>();

            if (!settings.SanitizeHtml)
            {
                model.Html = await _liquidTemplateManager.RenderStringAsync(htmlBodyPart.Html, _htmlEncoder, model,
                                                                            new Dictionary <string, FluidValue>() { ["ContentItem"] = new ObjectValue(model.ContentItem) });
            }

            model.Html = await _shortcodeService.ProcessAsync(model.Html,
                                                              new Context
            {
                ["ContentItem"]        = htmlBodyPart.ContentItem,
                ["TypePartDefinition"] = context.TypePartDefinition
            });
        }
示例#16
0
        public async ValueTask <string> EvaluateAsync(string identifier, Arguments arguments, string content, Context context)
        {
            _shortcodeTemplatesDocument ??= await _shortcodeTemplatesManager.GetShortcodeTemplatesDocumentAsync();

            if (!_shortcodeTemplatesDocument.ShortcodeTemplates.TryGetValue(identifier, out var template))
            {
                return(null);
            }

            // Check if a shortcode template is recursively called.
            if (_identifiers.Contains(identifier))
            {
                return(null);
            }
            else
            {
                _identifiers.Add(identifier);
            }

            var model = new ShortcodeViewModel
            {
                Args    = arguments,
                Content = content,
                Context = context
            };

            var parameters = new Dictionary <string, FluidValue>
            {
                [identifier] = new StringValue(""),
                ["Args"]     = new ObjectValue(model.Args),
                ["Content"]  = new ObjectValue(new Content(model.Content)),
                ["Context"]  = new ObjectValue(model.Context)
            };

            var result = await _liquidTemplateManager.RenderStringAsync(template.Content, _htmlEncoder, model, parameters);

            // Allow multiple serial calls of this shortcode template.
            _identifiers.Remove(identifier);

            return(result);
        }
        public override IDisplayResult Display(MarkdownField field, BuildFieldDisplayContext context)
        {
            return(Initialize <MarkdownFieldViewModel>(GetDisplayShapeType(context), async model =>
            {
                var settings = context.PartFieldDefinition.GetSettings <MarkdownFieldSettings>();
                model.Markdown = field.Markdown;
                model.Field = field;
                model.Part = context.ContentPart;
                model.PartFieldDefinition = context.PartFieldDefinition;

                // The default Markdown option is to entity escape html
                // so filters must be run after the markdown has been processed.
                model.Html = _markdownService.ToHtml(model.Markdown ?? "");

                // The liquid rendering is for backwards compatability and can be removed in a future version.
                if (!settings.SanitizeHtml)
                {
                    model.Markdown = await _liquidTemplateManager.RenderStringAsync(model.Html, _htmlEncoder, model,
                                                                                    new Dictionary <string, FluidValue>()
                    {
                        ["ContentItem"] = new ObjectValue(field.ContentItem)
                    });
                }

                model.Html = await _shortcodeService.ProcessAsync(model.Html,
                                                                  new Context
                {
                    ["ContentItem"] = field.ContentItem,
                    ["PartFieldDefinition"] = context.PartFieldDefinition
                });

                if (settings.SanitizeHtml)
                {
                    model.Html = _htmlSanitizerService.Sanitize(model.Html ?? "");
                }
            })
                   .Location("Detail", "Content")
                   .Location("Summary", "Content"));
        }
示例#18
0
        public async override Task UpdatedAsync(UpdateContentContext context, AliasPart part)
        {
            // Compute the Alias only if it's empty
            if (!String.IsNullOrEmpty(part.Alias))
            {
                return;
            }

            var pattern = GetPattern(part);

            if (!String.IsNullOrEmpty(pattern))
            {
                var model = new AliasPartViewModel()
                {
                    Alias       = part.Alias,
                    AliasPart   = part,
                    ContentItem = part.ContentItem
                };

                part.Alias = await _liquidTemplateManager.RenderStringAsync(pattern, NullEncoder.Default, model,
                                                                            new Dictionary <string, FluidValue>() { [nameof(ContentItem)] = new ObjectValue(model.ContentItem) });

                part.Alias = part.Alias.Replace("\r", String.Empty).Replace("\n", String.Empty);

                if (part.Alias?.Length > AliasPart.MaxAliasLength)
                {
                    part.Alias = part.Alias.Substring(0, AliasPart.MaxAliasLength);
                }

                if (!await part.IsAliasUniqueAsync(_session, part.Alias))
                {
                    part.Alias = await GenerateUniqueAliasAsync(part.Alias, part);
                }

                part.Apply();
            }
        }
 public static Task <string> RenderStringAsync(this ILiquidTemplateManager manager, string template, TextEncoder encoder, IEnumerable <KeyValuePair <string, FluidValue> > properties)
 => manager.RenderStringAsync(template, encoder, model: null, properties);
 public static Task <string> RenderStringAsync(this ILiquidTemplateManager manager, string template, TextEncoder encoder, object model)
 => manager.RenderStringAsync(template, encoder, model, properties: null);
示例#21
0
        public async ValueTask <FluidValue> ProcessAsync(FluidValue input, FilterArguments arguments, LiquidTemplateContext ctx)
        {
            var content = await _liquidTemplateManager.RenderStringAsync(input.ToStringValue(), _htmlEncoder, arguments.At(0));

            return(new StringValue(content, false));
        }
示例#22
0
        public async Task <IActionResult> Query(AdminQueryViewModel model)
        {
            if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageIndexes))
            {
                return(Forbid());
            }

            model.Indices = (await _luceneIndexSettingsService.GetSettingsAsync()).Select(x => x.IndexName).ToArray();

            // Can't query if there are no indices
            if (model.Indices.Length == 0)
            {
                return(RedirectToAction(nameof(Index)));
            }

            if (String.IsNullOrEmpty(model.IndexName))
            {
                model.IndexName = model.Indices[0];
            }

            if (!_luceneIndexManager.Exists(model.IndexName))
            {
                return(NotFound());
            }

            if (String.IsNullOrWhiteSpace(model.DecodedQuery))
            {
                return(View(model));
            }

            if (String.IsNullOrEmpty(model.Parameters))
            {
                model.Parameters = "{ }";
            }

            var stopwatch = new Stopwatch();

            stopwatch.Start();

            await _luceneIndexManager.SearchAsync(model.IndexName, async searcher =>
            {
                var analyzer = _luceneAnalyzerManager.CreateAnalyzer(await _luceneIndexSettingsService.GetIndexAnalyzerAsync(model.IndexName));
                var context  = new LuceneQueryContext(searcher, LuceneSettings.DefaultVersion, analyzer);

                var parameters = JsonConvert.DeserializeObject <Dictionary <string, object> >(model.Parameters);

                var tokenizedContent = await _liquidTemplateManager.RenderStringAsync(model.DecodedQuery, _javaScriptEncoder, parameters.Select(x => new KeyValuePair <string, FluidValue>(x.Key, FluidValue.Create(x.Value, _templateOptions.Value))));

                try
                {
                    var parameterizedQuery = JObject.Parse(tokenizedContent);
                    var luceneTopDocs      = await _queryService.SearchAsync(context, parameterizedQuery);

                    if (luceneTopDocs != null)
                    {
                        model.Documents = luceneTopDocs.TopDocs.ScoreDocs.Select(hit => searcher.Doc(hit.Doc)).ToList();
                        model.Count     = luceneTopDocs.Count;
                    }
                }
                catch (Exception e)
                {
                    _logger.LogError(e, "Error while executing query");
                    ModelState.AddModelError(nameof(model.DecodedQuery), S["Invalid query : {0}", e.Message]);
                }

                stopwatch.Stop();
                model.Elapsed = stopwatch.Elapsed;
            });

            return(View(model));
        }
示例#23
0
        public async Task <IQueryResults> ExecuteQueryAsync(Query query, IDictionary <string, object> parameters)
        {
            var sqlQuery        = query as SqlQuery;
            var sqlQueryResults = new SQLQueryResults();

            var tokenizedQuery = await _liquidTemplateManager.RenderStringAsync(sqlQuery.Template, NullEncoder.Default,
                                                                                parameters.Select(x => new KeyValuePair <string, FluidValue>(x.Key, FluidValue.Create(x.Value, _templateOptions))));

            var connection = _dbConnectionAccessor.CreateConnection();
            var dialect    = _session.Store.Configuration.SqlDialect;

            if (!SqlParser.TryParse(tokenizedQuery, dialect, _session.Store.Configuration.TablePrefix, parameters, out var rawQuery, out var messages))
            {
                sqlQueryResults.Items = new object[0];
                connection.Dispose();
                return(sqlQueryResults);
            }

            if (sqlQuery.ReturnDocuments)
            {
                IEnumerable <int> documentIds;

                using (connection)
                {
                    await connection.OpenAsync();

                    using (var transaction = connection.BeginTransaction(_session.Store.Configuration.IsolationLevel))
                    {
                        documentIds = await connection.QueryAsync <int>(rawQuery, parameters, transaction);
                    }
                }

                sqlQueryResults.Items = await _session.GetAsync <ContentItem>(documentIds.ToArray());

                return(sqlQueryResults);
            }
            else
            {
                IEnumerable <dynamic> queryResults;

                using (connection)
                {
                    await connection.OpenAsync();

                    using (var transaction = connection.BeginTransaction(_session.Store.Configuration.IsolationLevel))
                    {
                        queryResults = await connection.QueryAsync(rawQuery, parameters, transaction);
                    }
                }

                var results = new List <JObject>();

                foreach (var document in queryResults)
                {
                    results.Add(JObject.FromObject(document));
                }

                sqlQueryResults.Items = results;
                return(sqlQueryResults);
            }
        }
        public async Task <IActionResult> Submit(string formId)
        {
            var canView = ContentTypePermissionsHelper.CreateDynamicPermission(ContentTypePermissionsHelper.PermissionTemplates[CommonPermissions.ViewContent.Name], "VueForm");

            if (!await _authorizationService.AuthorizeAsync(User, canView))
            {
                return(NotFound());
            }

            var form = await _contentManager.GetAsync(formId, VersionOptions.Published);

            if (form == null)
            {
                return(NotFound());
            }

            var formPart = form.As <VueForm>();

            if (formPart.Disabled.Value)
            {
                return(NotFound());
            }

            if (!_contentPermissionsService.CanAccess(form))
            {
                return(NotFound());
            }

            var scriptingProvider = new VueFormMethodsProvider(form);

            var script = form.As <VueFormScripts>();

            // This object holds the return value of the script
            object serverScriptResult = EvaluateScript(script?.OnValidation?.Text, scriptingProvider, formPart, "OnValidation");

            // Return if any errors are returned in the OnValidation script
            if (ModelState.ErrorCount > 0)
            {
                return(Json(new VueFormSubmitResult(GetErrorDictionary(), serverScriptResult, GetDebugLogs(formPart))));
            }

            serverScriptResult = EvaluateScript(script?.OnSubmitted?.Text, scriptingProvider, formPart, "OnSubmitted");

            // Return if any errors are returned from the OnSubmitted script
            if (ModelState.ErrorCount > 0)
            {
                return(Json(new VueFormSubmitResult(GetErrorDictionary(), serverScriptResult, GetDebugLogs(formPart))));
            }

            // _workflow manager is null if workflow feature is not enabled
            if (_workflowManager != null)
            {
                await _workflowManager.TriggerEventAsync(nameof(VueFormSubmittedEvent),
                                                         input : new { VueForm = form },
                                                         correlationId : form.ContentItemId
                                                         );
            }

            // Return if any errors are returned from the Workflow
            if (ModelState.ErrorCount > 0)
            {
                return(Json(new VueFormSubmitResult(GetErrorDictionary(), serverScriptResult, GetDebugLogs(formPart))));
            }

            // Handle the redirects with ajax requests.
            // 302 are equivalent to 301 in this case. No permanent redirect.
            // This can come from a scripting method or the HttpRedirect Workflow Task
            if (HttpContext.Response.StatusCode == 301 || HttpContext.Response.StatusCode == 302)
            {
                var returnValue = new { redirect = WebUtility.UrlDecode(HttpContext.Response.Headers["Location"]) };
                HttpContext.Response.Clear();
                return(Json(returnValue));
            }

            // This get's set by either the workflow's HttpRedirectTask or HttpResponseTask
            if (HttpContext.Items[WorkflowHttpResult.Instance] != null)
            {
                // Let the HttpResponseTask control the response. This will fail on the client if it's anything other than json
                return(new EmptyResult());
            }

            //try to get the message from the http context as set by the addSuccessMessage() scripting function
            var successMessage = string.Empty;

            if (HttpContext.Items[Constants.VueFormSuccessMessage] != null)
            {
                successMessage = (string)HttpContext.Items[Constants.VueFormSuccessMessage];
            }
            else
            {
                if (!string.IsNullOrWhiteSpace(formPart.SuccessMessage?.Text))
                {
                    var formSuccessMessage = await _liquidTemplateManager.RenderStringAsync(formPart.SuccessMessage.Text, _htmlEncoder);

                    successMessage = await _shortcodeService.ProcessAsync(formSuccessMessage);
                }
            }

            return(Json(new VueFormSubmitResult(successMessage, serverScriptResult, GetDebugLogs(formPart))));
        }