コード例 #1
0
        public override async Task <IViewProviderResult> BuildDisplayAsync(Article entity, IViewProviderContext context)
        {
            // Build view model
            var baseUrl = await _contextFacade.GetBaseUrlAsync();

            var viewModel = new ShareViewModel
            {
                Url = baseUrl + _contextFacade.GetRouteUrl(new RouteValueDictionary()
                {
                    ["area"]       = "Plato.Articles",
                    ["controller"] = "Home",
                    ["action"]     = "Display",
                    ["opts.id"]    = entity.Id,
                    ["opts.alias"] = entity.Alias
                })
            };

            return(Views(
                       View <ShareViewModel>("Article.Share.Display.Sidebar", model => viewModel)
                       .Zone("sidebar")
                       .Order(int.MaxValue - 100)
                       ));
        }
コード例 #2
0
ファイル: AdminController.cs プロジェクト: radtek/Plato
        // ------------

        async Task <LabelIndexViewModel <Label> > GetIndexViewModelAsync(LabelIndexOptions options, PagerOptions pager)
        {
            // Get questions feature
            options.FeatureId = await GetFeatureIdAsync();

            if (options.Sort == LabelSortBy.Auto)
            {
                options.Sort  = LabelSortBy.Modified;
                options.Order = OrderBy.Desc;
            }

            // Indicate administrator view
            options.EnableEdit = true;

            // Set pager call back Url
            pager.Url = _contextFacade.GetRouteUrl(pager.Route(RouteData));

            return(new LabelIndexViewModel <Label>()
            {
                Options = options,
                Pager = pager
            });
        }
コード例 #3
0
ファイル: UserController.cs プロジェクト: vdandrade/Plato
        async Task<EntityIndexViewModel<Article>> GetIndexViewModelAsync(EntityIndexOptions options, PagerOptions pager)
        {

            // Get current feature
            var feature = await _featureFacade.GetFeatureByIdAsync(RouteData.Values["area"].ToString());

            // Restrict results to current feature
            if (feature != null)
            {
                options.FeatureId = feature.Id;
            }

            // Set pager call back Url
            pager.Url = _contextFacade.GetRouteUrl(pager.Route(RouteData));
            
            // Return updated model
            return new EntityIndexViewModel<Article>()
            {
                Options = options,
                Pager = pager
            };

        }
コード例 #4
0
ファイル: HomeController.cs プロジェクト: radtek/Plato
        public async Task <IActionResult> Login(string returnUrl)
        {
            if (string.IsNullOrEmpty(_demoOptions.AdminUserName))
            {
                throw new ArgumentNullException(nameof(_demoOptions.AdminUserName));
            }

            if (string.IsNullOrEmpty(_demoOptions.AdminPassword))
            {
                throw new ArgumentNullException(nameof(_demoOptions.AdminPassword));
            }

            // Get sign in result
            var result = await _signInManager.PasswordSignInAsync(
                _demoOptions.AdminUserName,
                _demoOptions.AdminPassword,
                isPersistent : true,
                lockoutOnFailure : false);

            // Success
            if (result.Succeeded)
            {
                // Add alert
                _alerter.Success(T["Admin Login Successful!"]);

                // Redirect to Plato.Admin
                return(Redirect(_contextFacade.GetRouteUrl(new RouteValueDictionary()
                {
                    ["area"] = "Plato.Admin",
                    ["controller"] = "Admin",
                    ["action"] = "Index"
                })));
            }

            // Redirect to return url
            return(RedirectToLocal(returnUrl));
        }
コード例 #5
0
        // -----------------
        // Index
        // -----------------

        public async Task <IActionResult> Index(EntityIndexOptions opts, PagerOptions pager)
        {
            // Build options
            if (opts == null)
            {
                opts = new EntityIndexOptions();
            }

            // Build pager
            if (pager == null)
            {
                pager = new PagerOptions();
            }

            // Get default options
            var defaultViewOptions  = new EntityIndexOptions();
            var defaultPagerOptions = new PagerOptions();

            // Add non default route data for pagination purposes
            if (opts.Search != defaultViewOptions.Search)
            {
                this.RouteData.Values.Add("opts.search", opts.Search);
            }
            if (opts.Sort != defaultViewOptions.Sort)
            {
                this.RouteData.Values.Add("opts.sort", opts.Sort);
            }
            if (opts.Order != defaultViewOptions.Order)
            {
                this.RouteData.Values.Add("opts.order", opts.Order);
            }
            if (opts.Filter != defaultViewOptions.Filter)
            {
                this.RouteData.Values.Add("opts.filter", opts.Filter);
            }
            if (pager.Page != defaultPagerOptions.Page)
            {
                this.RouteData.Values.Add("pager.page", pager.Page);
            }
            if (pager.Size != defaultPagerOptions.Size)
            {
                this.RouteData.Values.Add("pager.size", pager.Size);
            }

            // Build view model
            var viewModel = await GetIndexViewModelAsync(null, opts, pager);

            // Add view model to context
            HttpContext.Items[typeof(EntityIndexViewModel <Doc>)] = viewModel;

            // If we have a pager.page query string value return paged results
            if (int.TryParse(HttpContext.Request.Query["pager.page"], out var page))
            {
                if (page > 0 && !pager.Enabled)
                {
                    return(View("GetDocs", viewModel));
                }
            }

            // Return Url for authentication purposes
            ViewData["ReturnUrl"] = _contextFacade.GetRouteUrl(new RouteValueDictionary()
            {
                ["area"]       = "Plato.Docs.Categories",
                ["controller"] = "Home",
                ["action"]     = "Index"
                                 //["opts.categoryId"] = category != null ? category.Id.ToString() : string.Empty,
                                 //["opts.alias"] = category != null ? category.Alias.ToString() : string.Empty
            });

            //// Build page title
            //if (category != null)
            //{
            //    _pageTitleBuilder.AddSegment(S[category.Name], int.MaxValue);
            //}

            // Build breadcrumb
            _breadCrumbManager.Configure(async builder =>
            {
                builder
                .Add(S["Home"], home => home
                     .Action("Index", "Home", "Plato.Core")
                     .LocalNav()
                     ).Add(S["Docs"], docs => docs
                           .Action("Index", "Home", "Plato.Docs")
                           .LocalNav()
                           ).Add(S["Categories"]);
            });

            // Return view
            return(View((LayoutViewModel)await _categoryViewProvider.ProvideIndexAsync(new Category(), this)));
        }
コード例 #6
0
        // ------------

        async Task <string> ParseLinkTokensAsync(string input)
        {
            // We need input to parse
            if (string.IsNullOrEmpty(input))
            {
                return(input);
            }

            // Build tokens
            var tokens = _linkTokenizer.Tokenize(input);

            // Ensure we have tokens to parse
            if (tokens == null)
            {
                return(input);
            }

            // Prevent multiple enumeration
            var tokenList = tokens.ToList();

            // Get all referenced entities
            var entities = await GetEntitiesAsync(tokenList);

            if (entities != null)
            {
                var entityList = entities.ToList();
                var sb         = new StringBuilder();

                var insideHtmlTag = false;
                var hasLinkText   = false;

                for (var i = 0; i < input.Length; i++)
                {
                    if (input[i] == '<')
                    {
                        insideHtmlTag = true;
                    }
                    if (input[i] == '>')
                    {
                        insideHtmlTag = false;
                    }

                    foreach (var token in tokenList)
                    {
                        // Token start
                        if (i == token.Start)
                        {
                            var entity = entityList.FirstOrDefault(e =>
                                                                   e.Id.ToString().Equals(token.Value, StringComparison.Ordinal));
                            if (entity != null)
                            {
                                var url = _contextFacade.GetRouteUrl(new RouteValueDictionary()
                                {
                                    ["area"]       = entity.ModuleId,
                                    ["controller"] = "Home",
                                    ["action"]     = "Display",
                                    ["opts.id"]    = entity.Id,
                                    ["opts.alias"] = entity.Alias
                                });
                                var popperUrl = _contextFacade.GetRouteUrl(new RouteValueDictionary()
                                {
                                    ["area"]       = "Plato.Entities",
                                    ["controller"] = "Home",
                                    ["action"]     = "GetEntity",
                                    ["opts.id"]    = entity.Id,
                                    ["opts.alias"] = entity.Alias
                                });
                                if (!insideHtmlTag)
                                {
                                    sb.Append("<a href=\"")
                                    .Append(url)
                                    .Append("\" ")
                                    .Append("data-provide=\"popper\" ")
                                    .Append("data-popper-url=\"")
                                    .Append(popperUrl)
                                    .Append("\" class=\"reference-link\">");
                                    if (!string.IsNullOrEmpty(token.Text))
                                    {
                                        sb.Append(token.Text);
                                        hasLinkText = true;
                                    }
                                }
                            }
                        }
                    }

                    if (!hasLinkText)
                    {
                        sb.Append(input[i]);
                    }

                    foreach (var token in tokenList)
                    {
                        if (i == token.End)
                        {
                            var entity = entityList.FirstOrDefault(e =>
                                                                   e.Id.ToString().Equals(token.Value, StringComparison.Ordinal));
                            if (entity != null)
                            {
                                if (!insideHtmlTag)
                                {
                                    sb.Append("</a>");
                                }
                            }
                            hasLinkText = false;
                        }
                    }
                }

                return(sb.ToString());
            }

            return(input);
        }
コード例 #7
0
        public async Task <IActionResult> Rollback(int id)
        {
            // Validate
            if (id <= 0)
            {
                throw new ArgumentOutOfRangeException(nameof(id));
            }

            // Get history point
            var history = await _entityHistoryStore.GetByIdAsync(id);

            // Ensure we found the history point
            if (history == null)
            {
                return(NotFound());
            }

            // Get entity for history point
            var entity = await _entityStore.GetByIdAsync(history.EntityId);

            // Ensure we found the entity
            if (entity == null)
            {
                return(NotFound());
            }

            // Get reply
            IdeaComment reply = null;

            if (history.EntityReplyId > 0)
            {
                reply = await _entityReplyStore.GetByIdAsync(history.EntityReplyId);

                // Ensure we found a reply if supplied
                if (reply == null)
                {
                    return(NotFound());
                }
            }

            // Get current user
            var user = await _contextFacade.GetAuthenticatedUserAsync();

            // We always need to be logged in to edit entities
            if (user == null)
            {
                return(Unauthorized());
            }

            // Ensure we have permission
            if (!await _authorizationService.AuthorizeAsync(HttpContext.User,
                                                            entity.CategoryId, reply != null
                    ? Permissions.RevertReplyHistory
                    : Permissions.RevertEntityHistory))
            {
                return(Unauthorized());
            }

            ICommandResultBase result;

            if (reply != null)
            {
                // Only update edited information if the message changes
                if (history.Message != reply.Message)
                {
                    reply.Message      = history.Message;
                    reply.EditedUserId = user?.Id ?? 0;
                    reply.EditedDate   = DateTimeOffset.UtcNow;
                }

                // Update reply to history point
                result = await _entityReplyManager.UpdateAsync(reply);
            }
            else
            {
                // Only update edited information if the message changes
                if (history.Message != entity.Message)
                {
                    entity.Message      = history.Message;
                    entity.EditedUserId = user?.Id ?? 0;
                    entity.EditedDate   = DateTimeOffset.UtcNow;
                }

                // Update entity to history point
                result = await _entityManager.UpdateAsync(entity);
            }

            // Add result
            if (result.Succeeded)
            {
                _alerter.Success(T["Version Rolled Back Successfully!"]);
            }
            else
            {
                foreach (var error in result.Errors)
                {
                    _alerter.Danger(T[error.Description]);
                }
            }

            // Redirect
            return(Redirect(_contextFacade.GetRouteUrl(new RouteValueDictionary()
            {
                ["area"] = "Plato.Ideas",
                ["controller"] = "Home",
                ["action"] = "Reply",
                ["opts.id"] = entity.Id,
                ["opts.alias"] = entity.Alias,
                ["opts.replyId"] = reply?.Id ?? 0
            })));
        }
コード例 #8
0
ファイル: HomeController.cs プロジェクト: radtek/Plato
        public async Task <IActionResult> Index(LabelIndexOptions opts, PagerOptions pager)
        {
            if (opts == null)
            {
                opts = new LabelIndexOptions();
            }

            if (pager == null)
            {
                pager = new PagerOptions();
            }

            // Get default options
            var defaultViewOptions  = new LabelIndexOptions();
            var defaultPagerOptions = new PagerOptions();

            // Add non default route data for pagination purposes
            if (opts.Search != defaultViewOptions.Search && !this.RouteData.Values.ContainsKey("opts.search"))
            {
                this.RouteData.Values.Add("opts.search", opts.Search);
            }
            if (opts.Sort != defaultViewOptions.Sort && !this.RouteData.Values.ContainsKey("opts.sort"))
            {
                this.RouteData.Values.Add("opts.sort", opts.Sort);
            }
            if (opts.Order != defaultViewOptions.Order && !this.RouteData.Values.ContainsKey("opts.order"))
            {
                this.RouteData.Values.Add("opts.order", opts.Order);
            }
            if (pager.Page != defaultPagerOptions.Page && !this.RouteData.Values.ContainsKey("pager.page"))
            {
                this.RouteData.Values.Add("pager.page", pager.Page);
            }
            if (pager.Size != defaultPagerOptions.Size && !this.RouteData.Values.ContainsKey("pager.size"))
            {
                this.RouteData.Values.Add("pager.size", pager.Size);
            }

            // Build view model
            var viewModel = await GetIndexViewModelAsync(opts, pager);

            // Add view options to context
            HttpContext.Items[typeof(LabelIndexViewModel <Label>)] = viewModel;

            // If we have a pager.page querystring value return paged results
            if (int.TryParse(HttpContext.Request.Query["pager.page"], out var page))
            {
                if (page > 0)
                {
                    return(View("GetLabels", viewModel));
                }
            }

            // Return Url for authentication purposes
            ViewData["ReturnUrl"] = _contextFacade.GetRouteUrl(new RouteValueDictionary()
            {
                ["area"]       = "Plato.Issues.Labels",
                ["controller"] = "Home",
                ["action"]     = "Index"
            });

            // Breadcrumb
            _breadCrumbManager.Configure(builder =>
            {
                builder.Add(S["Home"], home => home
                            .Action("Index", "Home", "Plato.Core")
                            .LocalNav()
                            ).Add(S["Issues"], discuss => discuss
                                  .Action("Index", "Home", "Plato.Issues")
                                  .LocalNav()
                                  ).Add(S["Labels"]);
            });

            // Return view
            return(View((LayoutViewModel)await _labelViewProvider.ProvideIndexAsync(new Label(), this)));
        }
コード例 #9
0
        // --------------
        // Manage Users
        // --------------

        public async Task <IActionResult> Index(int offset, UserIndexOptions opts, PagerOptions pager)
        {
            // Ensure we have permission
            if (!await _authorizationService.AuthorizeAsync(HttpContext.User,
                                                            Permissions.ManageUsers))
            {
                return(Unauthorized());
            }

            // default options
            if (opts == null)
            {
                opts = new UserIndexOptions();
            }

            // default pager
            if (pager == null)
            {
                pager = new PagerOptions();
            }

            // Set pager call back Url
            pager.Url = _contextFacade.GetRouteUrl(pager.Route(RouteData));

            // Get default options
            var defaultViewOptions  = new UserIndexOptions();
            var defaultPagerOptions = new PagerOptions();

            // Add non default route data for pagination purposes
            if (opts.Search != defaultViewOptions.Search)
            {
                RouteData.Values.Add("opts.search", opts.Search);
            }
            if (opts.Sort != defaultViewOptions.Sort)
            {
                RouteData.Values.Add("opts.sort", opts.Sort);
            }
            if (opts.Order != defaultViewOptions.Order)
            {
                RouteData.Values.Add("opts.order", opts.Order);
            }
            if (pager.Page != defaultPagerOptions.Page)
            {
                RouteData.Values.Add("pager.page", pager.Page);
            }
            if (pager.Size != defaultPagerOptions.Size)
            {
                RouteData.Values.Add("pager.size", pager.Size);
            }

            // Enable edit options for admin view
            opts.EnableEdit = true;

            var viewModel = new UserIndexViewModel()
            {
                Options = opts,
                Pager   = pager
            };

            // Add view options to context for use within view adapters
            HttpContext.Items[typeof(UserIndexViewModel)] = viewModel;

            // If we have a pager.page querystring value return paged results
            if (int.TryParse(HttpContext.Request.Query["pager.page"], out var page))
            {
                if (page > 0)
                {
                    return(View("GetUsers", viewModel));
                }
            }

            // Build breadcrumb
            _breadCrumbManager.Configure(builder =>
            {
                builder.Add(S["Home"], home => home
                            .Action("Index", "Admin", "Plato.Admin")
                            .LocalNav()
                            ).Add(S["Users"]);
            });

            // Return view
            return(View((LayoutViewModel)await _viewProvider.ProvideIndexAsync(new User(), this)));
        }
コード例 #10
0
        public async Task <IActionResult> Get(
            int page          = 1,
            int size          = 10,
            int entityId      = 0,
            int entityReplyId = 0,
            string sort       = "CreatedDate",
            OrderBy order     = OrderBy.Desc)
        {
            // Get histories
            var histories = await GetEntityHistory(
                page,
                size,
                entityId,
                entityReplyId,
                sort,
                order);

            IPagedResults <EntityHistoryApiResult> results = null;

            if (histories != null)
            {
                results = new PagedResults <EntityHistoryApiResult>
                {
                    Total = histories.Total
                };

                var baseUrl = await _contextFacade.GetBaseUrlAsync();

                foreach (var history in histories.Data)
                {
                    var createdByUrl = baseUrl + _contextFacade.GetRouteUrl(new RouteValueDictionary()
                    {
                        ["area"]       = "Plato.Users",
                        ["controller"] = "Home",
                        ["action"]     = "Display",
                        ["opts.id"]    = history.CreatedBy.Id,
                        ["opts.alias"] = history.CreatedBy.Alias
                    });

                    var sb = new StringBuilder();
                    sb.Append(history.CreatedBy.DisplayName)
                    .Append(" ")
                    .Append(history.MajorVersion == 1 && history.MinorVersion == 0
                            ? T["created"].Value
                            : T["edited"].Value)
                    .Append(" ")
                    .Append(history.CreatedDate.ToPrettyDate());

                    results.Data.Add(new EntityHistoryApiResult()
                    {
                        Id        = history.Id,
                        Text      = sb.ToString(),
                        Version   = history.Version,
                        CreatedBy = new UserApiResult()
                        {
                            Id          = history.CreatedBy.Id,
                            DisplayName = history.CreatedBy.DisplayName,
                            UserName    = history.CreatedBy.UserName,
                            Avatar      = history.CreatedBy.Avatar,
                            Url         = createdByUrl
                        },
                        Date = new FriendlyDate()
                        {
                            Text  = history.CreatedDate.ToPrettyDate(),
                            Value = history.CreatedDate
                        }
                    });
                }
            }

            IPagedApiResults <EntityHistoryApiResult> output = null;

            if (results != null)
            {
                output = new PagedApiResults <EntityHistoryApiResult>()
                {
                    Page       = page,
                    Size       = size,
                    Total      = results.Total,
                    TotalPages = results.Total.ToSafeCeilingDivision(size),
                    Data       = results.Data
                };
            }

            return(output != null
                ? base.Result(output)
                : base.NoResults());
        }
コード例 #11
0
        public async Task <IActionResult> Pin(string id)
        {
            // Ensure we have a valid id
            var ok = int.TryParse(id, out var entityId);

            if (!ok)
            {
                return(NotFound());
            }

            var topic = await _entityStore.GetByIdAsync(entityId);

            // Ensure the topic exists
            if (topic == null)
            {
                return(NotFound());
            }

            // Ensure we have permission
            if (!await _authorizationService.AuthorizeAsync(User, topic.CategoryId, ModeratorPermissions.PinTopics))
            {
                return(Unauthorized());
            }

            var user = await _contextFacade.GetAuthenticatedUserAsync();

            // Update topic
            topic.ModifiedUserId = user?.Id ?? 0;
            topic.ModifiedDate   = DateTimeOffset.UtcNow;
            topic.IsPinned       = true;

            // Save changes and return results
            var result = await _topicManager.UpdateAsync(topic);

            if (result.Succeeded)
            {
                _alerter.Success(T["Topic Pinned Successfully"]);
            }
            else
            {
                _alerter.Danger(T["Could not remove topic from SPAM"]);
            }

            // Redirect back to topic
            return(Redirect(_contextFacade.GetRouteUrl(new RouteValueDictionary()
            {
                ["area"] = "Plato.Discuss",
                ["controller"] = "Home",
                ["action"] = "Display",
                ["opts.id"] = topic.Id,
                ["opts.alias"] = topic.Alias
            })));
        }
コード例 #12
0
ファイル: AdminController.cs プロジェクト: radtek/Plato
        public async Task <IActionResult> ShareFileAttachment(ShareFileViewModel model)
        {
            var email = model.AttachmentEmail?.Trim() ?? string.Empty;

            // Ensure we have an email to share with
            if (string.IsNullOrEmpty(email))
            {
                // Add alert
                _alerter.Danger(T["An email address is required!"]);

                // Redirect back to file
                return(Redirect(_contextFacade.GetRouteUrl(new RouteValueDictionary()
                {
                    ["area"] = "Plato.Files",
                    ["controller"] = "Admin",
                    ["action"] = "Edit",
                    ["id"] = model.FileId
                })));
            }

            // Get current user
            var user = await _contextFacade.GetAuthenticatedUserAsync();

            // We need to be authenticated to add the invite
            if (user == null)
            {
                return(Unauthorized());
            }

            // Create the invite
            var invite = await _fileInviteStore.CreateAsync(new FileInvite()
            {
                FileId        = model.FileId,
                Email         = email,
                CreatedUserId = user.Id,
                CreatedDate   = DateTimeOffset.Now
            });

            // Share the invite
            if (invite != null)
            {
                var result = await _shareInviteService.SendAttachmentInviteAsync(invite);

                if (result.Succeeded)
                {
                    _alerter.Success(T["File Shared Successfully!"]);
                }
                else
                {
                    foreach (var error in result.Errors)
                    {
                        if (!string.IsNullOrEmpty(error.Description))
                        {
                            _alerter.Danger(T[error.Description]);
                        }
                    }
                }
            }

            // Redirect back to file
            return(Redirect(_contextFacade.GetRouteUrl(new RouteValueDictionary()
            {
                ["area"] = "Plato.Files",
                ["controller"] = "Admin",
                ["action"] = "Edit",
                ["id"] = model.FileId
            })));
        }
コード例 #13
0
ファイル: SearchController.cs プロジェクト: azgas/plato
        public async Task <IActionResult> Index([FromBody] TagApiParams parameters)
        {
            // Get tags
            var tags = await GetTags(parameters);

            // Build results
            IPagedResults <TagApiResult> results = null;

            if (tags != null)
            {
                // Get feature for tags
                IShellFeature feature = null;
                if (parameters.FeatureId > 0)
                {
                    feature = await _shellFeatureStore.GetByIdAsync(parameters.FeatureId);
                }

                results = new PagedResults <TagApiResult>
                {
                    Total = tags.Total
                };

                var baseUrl = await _contextFacade.GetBaseUrlAsync();

                foreach (var tag in tags.Data)
                {
                    var url = _contextFacade.GetRouteUrl(new RouteValueDictionary()
                    {
                        ["area"]       = feature?.ModuleId ?? "Plato.Tags",
                        ["controller"] = "Home",
                        ["action"]     = "Tag",
                        ["opts.id"]    = tag.Id,
                        ["opts.alias"] = tag.Alias
                    });

                    results.Data.Add(new TagApiResult()
                    {
                        Id       = tag.Id,
                        Name     = tag.Name,
                        Entities = tag.TotalEntities.ToPrettyInt(),
                        Follows  = tag.TotalFollows.ToPrettyInt(),
                        Url      = url
                    });
                }
            }

            IPagedApiResults <TagApiResult> output = null;

            if (results != null)
            {
                output = new PagedApiResults <TagApiResult>()
                {
                    Page       = parameters.Page,
                    Size       = parameters.Size,
                    Total      = results.Total,
                    TotalPages = results.Total.ToSafeCeilingDivision(parameters.Size),
                    Data       = results.Data
                };
            }

            return(output != null
                ? base.Result(output)
                : base.NoResults());
        }
コード例 #14
0
ファイル: LabelsController.cs プロジェクト: radtek/Plato
        public async Task <IActionResult> Get(LabelIndexOptions opts, PagerOptions pager)
        {
            if (opts == null)
            {
                opts = new LabelIndexOptions();;
            }

            if (pager == null)
            {
                pager = new PagerOptions();
            }

            if (opts.Sort == LabelSortBy.Auto)
            {
                opts.Sort  = LabelSortBy.Entities;
                opts.Order = OrderBy.Desc;
            }

            var labels = await _labelService.GetResultsAsync(opts, pager);

            PagedResults <LabelApiResult> results = null;

            if (labels != null)
            {
                results = new PagedResults <LabelApiResult>
                {
                    Total = labels.Total
                };

                var baseUrl = await _contextFacade.GetBaseUrlAsync();

                foreach (var label in labels.Data)
                {
                    var url = baseUrl + _contextFacade.GetRouteUrl(new RouteValueDictionary()
                    {
                        ["opts.labelId"] = label.Id,
                        ["opts.alias"]   = label.Alias
                    });

                    results.Data.Add(new LabelApiResult()
                    {
                        Id            = label.Id,
                        Name          = label.Name,
                        Description   = label.Description,
                        ForeColor     = label.ForeColor,
                        BackColor     = label.BackColor,
                        Alias         = label.Alias,
                        TotalEntities = new FriendlyNumber()
                        {
                            Text  = label.TotalEntities.ToPrettyInt(),
                            Value = label.TotalEntities
                        },
                        Rank = 0
                    });
                }
            }

            LabelApiResults output = null;

            if (results != null)
            {
                output = new LabelApiResults()
                {
                    Page       = pager.Page,
                    Size       = pager.Size,
                    Total      = results.Total,
                    TotalPages = results.Total.ToSafeCeilingDivision(pager.Size),
                    Data       = results.Data
                };
            }

            return(output != null
                ? base.Result(output)
                : base.NoResults());
        }
コード例 #15
0
ファイル: HomeController.cs プロジェクト: azgas/plato
        // -----------------
        // User List
        // -----------------

        public async Task <IActionResult> Index(UserIndexOptions opts, PagerOptions pager)
        {
            // Ensure we have permission
            if (!await _authorizationService.AuthorizeAsync(User,
                                                            Permissions.ViewUsers))
            {
                return(Unauthorized());
            }

            // default options
            if (opts == null)
            {
                opts = new UserIndexOptions();
            }

            // default pager
            if (pager == null)
            {
                pager = new PagerOptions();
            }

            // Set pager call back Url
            pager.Url = _contextFacade.GetRouteUrl(pager.Route(RouteData));

            // Get default options
            var defaultViewOptions  = new UserIndexOptions();
            var defaultPagerOptions = new PagerOptions();

            // Add non default route data for pagination purposes
            if (opts.Search != defaultViewOptions.Search)
            {
                this.RouteData.Values.Add("opts.search", opts.Search);
            }
            if (opts.Sort != defaultViewOptions.Sort)
            {
                this.RouteData.Values.Add("opts.sort", opts.Sort);
            }
            if (opts.Order != defaultViewOptions.Order)
            {
                this.RouteData.Values.Add("opts.order", opts.Order);
            }
            if (pager.Page != defaultPagerOptions.Page)
            {
                this.RouteData.Values.Add("pager.page", pager.Page);
            }
            if (pager.Size != defaultPagerOptions.Size)
            {
                this.RouteData.Values.Add("pager.size", pager.Size);
            }

            // Build view model
            var viewModel = new UserIndexViewModel()
            {
                Options = opts,
                Pager   = pager
            };

            // Add view model to context
            HttpContext.Items[typeof(UserIndexViewModel)] = viewModel;

            // If we have a pager.page querystring value return paged results
            if (int.TryParse(HttpContext.Request.Query["pager.page"], out var page))
            {
                if (page > 0)
                {
                    return(View("GetUsers", viewModel));
                }
            }

            // Return Url for authentication & canonical url purposes
            ViewData["ReturnUrl"] = _contextFacade.GetRouteUrl(new RouteValueDictionary()
            {
                ["area"]       = "Plato.Users",
                ["controller"] = "Home",
                ["action"]     = "Index"
            });

            // Breadcrumb
            _breadCrumbManager.Configure(builder =>
            {
                builder.Add(S["Home"], home => home
                            .Action("Index", "Home", "Plato.Core")
                            .LocalNav()
                            ).Add(S["Users"]);
            });

            // Return view
            return(View((LayoutViewModel)await _viewProvider.ProvideIndexAsync(new ProfilePage(), this)));
        }
コード例 #16
0
        async Task <ICommandResultBase> InstallEntityInternalAsync(SampleDataDescriptor descriptor, IList <User> users, int sortOrder = 0)
        {
            // Validate

            if (descriptor == null)
            {
                throw new ArgumentNullException(nameof(descriptor));
            }

            if (string.IsNullOrEmpty(descriptor.ModuleId))
            {
                throw new ArgumentNullException(nameof(descriptor.ModuleId));
            }

            // Our result
            var result = new CommandResultBase();

            // Ensure the feature is enabled
            var feature = await _featureFacade.GetFeatureByIdAsync(descriptor.ModuleId);

            if (feature == null)
            {
                return(result.Failed($"The feature {descriptor.ModuleId} is not enabled!"));
            }

            // Get a random user for the post
            var randomUser = users[_random.Next(0, users.Count)];

            // Capitalize the first character of our entity type
            var entityTypeCapitalized = char.ToUpper(descriptor.EntityType[0]).ToString() + descriptor.EntityType.Substring(1);

            // Create the post
            var entity = new Entity()
            {
                Title         = $"Example {entityTypeCapitalized} {_random.Next(0, 2000).ToString()}",
                Message       = GetEntityText(descriptor),
                FeatureId     = feature?.Id ?? 0,
                SortOrder     = sortOrder + 1,
                CreatedUserId = randomUser?.Id ?? 0,
                CreatedDate   = DateTimeOffset.UtcNow
            };

            // Create entity
            var entityResult = await _entityManager.CreateAsync(entity);

            if (entityResult.Succeeded)
            {
                var lastReplyId       = string.Empty;
                var lastReplyUserName = string.Empty;
                var lastReplyMessage  = string.Empty;

                // Create entity replies
                for (var i = 0; i < descriptor.EntityRepliesToCreate; i++)
                {
                    randomUser = users[_random.Next(0, users.Count - 1)];

                    var message = GetReplyText(descriptor);

                    message = message.Replace("{replyUserName}", randomUser?.UserName ?? "");

                    message = message.Replace("{lastReplyId}", lastReplyId ?? "");
                    message = message.Replace("{lastReplyMessage}", lastReplyMessage ?? "");
                    message = message.Replace("{lastReplyQuotedMessage}", lastReplyMessage.Replace(System.Environment.NewLine, System.Environment.NewLine + "> ") ?? "");
                    message = message.Replace("{lastReplyUserName}", lastReplyUserName ?? "");

                    message = message.Replace("{entityId}", entityResult.Response.Id.ToString() ?? "");
                    message = message.Replace("{entityTitle}", entityResult.Response.Title ?? "");
                    message = message.Replace("{entityUserName}", entityResult.Response.CreatedBy.UserName);

                    message = message.Replace("{mentionSample}", BuildMentionSampleMarkUp());

                    message = message.Replace("{lastReplyUrl}", _contextFacade.GetRouteUrl(new RouteValueDictionary()
                    {
                        ["area"]         = descriptor.ModuleId,
                        ["controller"]   = "Home",
                        ["action"]       = "Reply",
                        ["opts.id"]      = entityResult.Response.Id.ToString() ?? "",
                        ["opts.alias"]   = entityResult.Response.Alias.ToString() ?? "",
                        ["opts.replyId"] = lastReplyId ?? ""
                    }));

                    // Create reply
                    var reply = new EntityReply()
                    {
                        EntityId      = entityResult.Response.Id,
                        Message       = message,
                        CreatedUserId = randomUser?.Id ?? 0,
                        CreatedDate   = DateTimeOffset.UtcNow
                    };

                    // Add reply
                    var replyResult = await _entityReplyManager.CreateAsync(reply);

                    if (!replyResult.Succeeded)
                    {
                        return(result.Failed());
                    }

                    lastReplyId       = replyResult.Response.Id.ToString();
                    lastReplyMessage  = replyResult.Response.Message;
                    lastReplyUserName = replyResult.Response.CreatedBy.UserName;
                }
            }
            else
            {
                return(result.Failed(result.Errors.ToArray()));
            }

            return(result.Success());
        }
コード例 #17
0
        public async Task <string> ParseAsync(string input)
        {
            // We need input to parse
            if (string.IsNullOrEmpty(input))
            {
                return(input);
            }

            // Get tokens
            var tokens = _tokenizer.Tokenize(input);

            // Ensure we found tokens
            if (tokens == null)
            {
                return(input);
            }

            // Prevent multiple enumeration
            var tokenList = tokens.ToList();

            // Get mentioned users
            var users = await GetUsersAsync(tokenList);

            if (users != null)
            {
                var userList = users.ToList();
                var sb       = new StringBuilder();

                // Parse
                for (var i = 0; i < input.Length; i++)
                {
                    foreach (var token in tokenList)
                    {
                        // Token start
                        if (i == token.Start)
                        {
                            var user = userList.FirstOrDefault(u => u.UserName.Equals(token.Value, StringComparison.OrdinalIgnoreCase));
                            if (user != null)
                            {
                                var url = _contextFacade.GetRouteUrl(new RouteValueDictionary()
                                {
                                    ["area"]       = "Plato.Users",
                                    ["controller"] = "Home",
                                    ["action"]     = "Display",
                                    ["opts.id"]    = user.Id,
                                    ["opts.alias"] = user.Alias
                                });
                                var popperUrl = _contextFacade.GetRouteUrl(new RouteValueDictionary()
                                {
                                    ["area"]       = "Plato.Users",
                                    ["controller"] = "Home",
                                    ["action"]     = "GetUser",
                                    ["opts.id"]    = user.Id,
                                    ["opts.alias"] = user.Alias
                                });
                                sb.Append("<a href=\"")
                                .Append(url)
                                .Append("\" ")
                                .Append("data-provide=\"popper\" ")
                                .Append("data-popper-url=\"")
                                .Append(popperUrl)
                                .Append("\" ")
                                .Append("class=\"mention-link\">");
                            }
                        }
                    }

                    sb.Append(input[i]);

                    foreach (var token in tokenList)
                    {
                        if (i == token.End)
                        {
                            var user = userList.FirstOrDefault(u => u.UserName.Equals(token.Value, StringComparison.OrdinalIgnoreCase));
                            if (user != null)
                            {
                                sb.Append("</a>");
                            }
                        }
                    }
                }

                return(sb.ToString());
            }

            return(input);
        }
コード例 #18
0
        public async Task <IActionResult> Get(
            int page        = 1,
            int size        = 10,
            string keywords = "",
            string sort     = "LastLoginDate",
            OrderBy order   = OrderBy.Desc)
        {
            var users = await GetUsers(
                page,
                size,
                keywords,
                sort,
                order);

            IPagedResults <UserApiResult> results = null;

            if (users != null)
            {
                results = new PagedResults <UserApiResult>
                {
                    Total = users.Total
                };

                var baseUrl = await _contextFacade.GetBaseUrlAsync();

                foreach (var user in users.Data)
                {
                    var profileUrl = baseUrl + _contextFacade.GetRouteUrl(new RouteValueDictionary()
                    {
                        ["area"]       = "Plato.Users",
                        ["controller"] = "Home",
                        ["action"]     = "Display",
                        ["opts.id"]    = user.Id,
                        ["opts.alias"] = user.Alias
                    });

                    results.Data.Add(new UserApiResult()
                    {
                        Id          = user.Id,
                        DisplayName = user.DisplayName,
                        UserName    = user.UserName,
                        Url         = profileUrl,
                        Avatar      = user.Avatar
                    });
                }
            }

            IPagedApiResults <UserApiResult> output = null;

            if (results != null)
            {
                output = new PagedApiResults <UserApiResult>()
                {
                    Page       = page,
                    Size       = size,
                    Total      = results.Total,
                    TotalPages = results.Total.ToSafeCeilingDivision(size),
                    Data       = results.Data
                };
            }

            return(output != null
                ? base.Result(output)
                : base.NoResults());
        }
コード例 #19
0
ファイル: HomeController.cs プロジェクト: mrs2020/Plato
        public async Task <IActionResult> ToAnswer(string id)
        {
            // Get authenticated user
            var user = await _contextFacade.GetAuthenticatedUserAsync();

            // We need to be authenticated
            if (user == null)
            {
                return(Unauthorized());
            }

            // Ensure we have a valid id
            var ok = int.TryParse(id, out var replyId);

            if (!ok)
            {
                return(NotFound());
            }

            var reply = await _entityReplyStore.GetByIdAsync(replyId);

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

            var entity = await _entityStore.GetByIdAsync(reply.EntityId);

            // Ensure the entity exists
            if (entity == null)
            {
                return(NotFound());
            }

            // Get permission
            var permission = entity.CreatedUserId == user.Id
                ? Permissions.MarkOwnRepliesAnswer
                : Permissions.MarkAnyReplyAnswer;

            // Ensure we have permission
            if (!await _authorizationService.AuthorizeAsync(User, entity.CategoryId, permission))
            {
                return(Unauthorized());
            }

            // Update reply
            reply.ModifiedUserId = user?.Id ?? 0;
            reply.ModifiedDate   = DateTimeOffset.UtcNow;
            reply.IsAnswer       = true;

            // Save changes and return results
            var result = await _replyManager.UpdateAsync(reply);

            if (result.Succeeded)
            {
                await UpdateEntityAsync(entity);

                _alerter.Success(T["Marked As Answer Successfully"]);
            }
            else
            {
                _alerter.Danger(T["Could not mark the reply as an answer"]);
            }

            // Redirect back to reply
            return(Redirect(_contextFacade.GetRouteUrl(new RouteValueDictionary()
            {
                ["area"] = "Plato.Questions",
                ["controller"] = "Home",
                ["action"] = "Reply",
                ["opts.id"] = entity.Id,
                ["opts.alias"] = entity.Alias,
                ["opts.replyId"] = reply.Id
            })));
        }
コード例 #20
0
        public async Task <IActionResult> Get(
            int page        = 1,
            int size        = 10,
            string keywords = "",
            string sort     = "LastReplyDate",
            OrderBy order   = OrderBy.Desc)
        {
            var entities = await GetEntities(
                page,
                size,
                keywords,
                sort,
                order);

            IPagedResults <EntityApiResult> results = null;

            if (entities != null)
            {
                results = new PagedResults <EntityApiResult>
                {
                    Total = entities.Total
                };

                var baseUrl = await _contextFacade.GetBaseUrlAsync();

                foreach (var entity in entities.Data)
                {
                    var createdByUrl = baseUrl + _contextFacade.GetRouteUrl(new RouteValueDictionary()
                    {
                        ["area"]       = "Plato.Users",
                        ["controller"] = "Home",
                        ["action"]     = "Display",
                        ["opts.id"]    = entity.CreatedBy.Id,
                        ["opts.alias"] = entity.CreatedBy.Alias
                    });

                    var modifiedByUrl = baseUrl + _contextFacade.GetRouteUrl(new RouteValueDictionary()
                    {
                        ["area"]       = "Plato.Users",
                        ["controller"] = "Home",
                        ["action"]     = "Display",
                        ["opts.id"]    = entity.ModifiedBy.Id,
                        ["opts.alias"] = entity.ModifiedBy.Alias
                    });

                    var url = _contextFacade.GetRouteUrl(new RouteValueDictionary()
                    {
                        ["area"]       = entity.ModuleId,
                        ["controller"] = "Home",
                        ["action"]     = "Display",
                        ["opts.id"]    = entity.Id,
                        ["opts.alias"] = entity.Alias
                    });

                    results.Data.Add(new EntityApiResult()
                    {
                        Id        = entity.Id,
                        CreatedBy = new UserApiResult()
                        {
                            Id          = entity.CreatedBy.Id,
                            DisplayName = entity.CreatedBy.DisplayName,
                            UserName    = entity.CreatedBy.UserName,
                            Url         = createdByUrl
                        },
                        ModifiedBy = new UserApiResult()
                        {
                            Id          = entity.ModifiedBy.Id,
                            DisplayName = entity.ModifiedBy.DisplayName,
                            UserName    = entity.ModifiedBy.UserName,
                            Url         = modifiedByUrl
                        },
                        LastReplyBy = new UserApiResult()
                        {
                            Id          = entity.ModifiedBy.Id,
                            DisplayName = entity.ModifiedBy.DisplayName,
                            UserName    = entity.ModifiedBy.UserName,
                            Url         = modifiedByUrl
                        },
                        Title       = entity.Title,
                        Message     = entity.Message,
                        Url         = url,
                        CreatedDate = new FriendlyDate()
                        {
                            Text  = entity.CreatedDate.ToPrettyDate(),
                            Value = entity.CreatedDate
                        }
                    });
                }
            }

            IPagedApiResults <EntityApiResult> output = null;

            if (results != null)
            {
                output = new PagedApiResults <EntityApiResult>()
                {
                    Page       = page,
                    Size       = size,
                    Total      = results.Total,
                    TotalPages = results.Total.ToSafeCeilingDivision(size),
                    Data       = results.Data
                };
            }

            return(output != null
                ? base.Result(output)
                : base.NoResults());
        }
コード例 #21
0
ファイル: HomeController.cs プロジェクト: vdandrade/Plato
        // -----------------
        // AddSpammer
        // -----------------

        public async Task <IActionResult> AddSpammer(EntityOptions opts)
        {
            // Disable functionality within demo mode
            if (_platoOpts.DemoMode)
            {
                return(Unauthorized());
            }

            // Empty options
            if (opts == null)
            {
                opts = new EntityOptions();
            }

            // Validate
            if (opts.Id <= 0)
            {
                throw new ArgumentOutOfRangeException(nameof(opts.Id));
            }

            // Get entity
            var entity = await _entityStore.GetByIdAsync(opts.Id);

            // Ensure the topic exists
            if (entity == null)
            {
                return(NotFound());
            }

            // Ensure we have permission
            if (!await _authorizationService.AuthorizeAsync(User,
                                                            entity.CategoryId, Permissions.AddToStopForumSpam))
            {
                return(Unauthorized());
            }

            // Get reply
            IEntityReply reply = null;

            if (opts.ReplyId > 0)
            {
                reply = await _entityReplyStore.GetByIdAsync(opts.ReplyId);
            }

            // Get user for reply or entity
            var user = reply != null
                ? await GetUserToValidateAsync(reply)
                : await GetUserToValidateAsync(entity);

            // Ensure we found the user
            if (user == null)
            {
                return(NotFound());
            }

            // Add spammer for reply or entity
            var result = await AddSpammerAsync(user);

            // Confirmation
            if (result.Success)
            {
                _alerter.Success(T["Spammer Added Successfully"]);
            }
            else
            {
                _alerter.Danger(!string.IsNullOrEmpty(result.Error)
                    ? T[result.Error]
                    : T["An unknown error occurred adding the user to the StopForumSpam database."]);
            }

            // Redirect back to reply
            if (reply != null)
            {
                return(Redirect(_contextFacade.GetRouteUrl(new RouteValueDictionary()
                {
                    ["area"] = "Plato.Docs",
                    ["controller"] = "Home",
                    ["action"] = "Reply",
                    ["opts.id"] = entity.Id,
                    ["opts.alias"] = entity.Alias,
                    ["opts.replyId"] = reply.Id
                })));
            }

            // Redirect back to entity
            return(Redirect(_contextFacade.GetRouteUrl(new RouteValueDictionary()
            {
                ["area"] = "Plato.Docs",
                ["controller"] = "Home",
                ["action"] = "Display",
                ["opts.id"] = entity.Id,
                ["opts.alias"] = entity.Alias
            })));
        }
コード例 #22
0
        public async Task <IActionResult> Get(
            int page        = 1,
            int size        = 10,
            string keywords = "",
            string sort     = "TotalEntities",
            OrderBy order   = OrderBy.Desc)
        {
            var tags = await GetTags(
                page,
                size,
                keywords,
                sort,
                order);

            IPagedResults <TagApiResult> results = null;

            if (tags != null)
            {
                results = new PagedResults <TagApiResult>
                {
                    Total = tags.Total
                };

                var baseUrl = await _contextFacade.GetBaseUrlAsync();

                foreach (var tag in tags.Data)
                {
                    var url = _contextFacade.GetRouteUrl(new RouteValueDictionary()
                    {
                        ["area"]       = "Plato.Tags",
                        ["controller"] = "Home",
                        ["action"]     = "Tag",
                        ["opts.id"]    = tag.Id,
                        ["opts.alias"] = tag.Alias
                    });

                    results.Data.Add(new TagApiResult()
                    {
                        Id   = tag.Id,
                        Name = tag.Name,
                        Url  = url
                    });
                }
            }

            IPagedApiResults <TagApiResult> output = null;

            if (results != null)
            {
                output = new PagedApiResults <TagApiResult>()
                {
                    Page       = page,
                    Size       = size,
                    Total      = results.Total,
                    TotalPages = results.Total.ToSafeCeilingDivision(size),
                    Data       = results.Data
                };
            }

            return(output != null
                ? base.Result(output)
                : base.NoResults());
        }