示例#1
0
        public ActionResult Sitemap()
        {
            if (!_commonSettings.Value.SitemapEnabled)
            {
                return(HttpNotFound());
            }

            var    roleIds  = _services.WorkContext.CurrentUser.UserRoles.Where(x => x.Active).Select(x => x.Id).ToList();
            string cacheKey = ModelCacheEventConsumer.SITEMAP_PAGE_MODEL_KEY.FormatInvariant(_services.WorkContext.WorkingLanguage.Id, string.Join(",", roleIds), _services.SiteContext.CurrentSite.Id);

            var result = _services.Cache.Get(cacheKey, () =>
            {
                var model = new SitemapModel();
                if (_commonSettings.Value.SitemapIncludeCategories)
                {
                    var categories          = _articleCategoryService.Value.GetAllCategories();
                    model.ArticleCategories = categories.Select(x => x.ToModel()).ToList();
                }
                if (_commonSettings.Value.SitemapIncludeProducts)
                {
                    //limit articel to 200 until paging is supported on this page
                    var articleSearchContext = new ArticleSearchContext();

                    articleSearchContext.OrderBy  = ArticleSortingEnum.Position;
                    articleSearchContext.PageSize = 200;
                    articleSearchContext.SiteId   = _services.SiteContext.CurrentSiteIdIfMultiSiteMode;
                    articleSearchContext.VisibleIndividuallyOnly = true;

                    var articels = _articleService.Value.SearchArticles(articleSearchContext);

                    model.Articles = articels.Select(articel => new ArticlePostModel()
                    {
                        Id           = articel.Id,
                        Title        = articel.GetLocalized(x => x.Title).EmptyNull(),
                        ShortContent = articel.GetLocalized(x => x.ShortContent),
                        FullContent  = articel.GetLocalized(x => x.FullContent),
                        SeName       = articel.GetSeName(),
                    }).ToList();
                }
                if (_commonSettings.Value.SitemapIncludeTopics)
                {
                    var topics = _topicService.Value.GetAllTopics(_services.SiteContext.CurrentSite.Id)
                                 .ToList()
                                 .FindAll(t => t.IncludeInSitemap);

                    model.Topics = topics.Select(topic => new TopicModel()
                    {
                        Id                  = topic.Id,
                        SystemName          = topic.SystemName,
                        IncludeInSitemap    = topic.IncludeInSitemap,
                        IsPasswordProtected = topic.IsPasswordProtected,
                        Title               = topic.GetLocalized(x => x.Title),
                    })
                                   .ToList();
                }
                return(model);
            });

            return(View(result));
        }
        public ActionResult ArticlesByTag(int articleTagId, ArticleCatalogPagingFilteringModel command)
        {
            var articlesTag = _articlesTagService.GetArticleTagById(articleTagId);

            if (articlesTag == null)
            {
                return(HttpNotFound());
            }

            if (command.PageNumber <= 0)
            {
                command.PageNumber = 1;
            }

            var model = new ArticleByTagModel()
            {
                Id      = articlesTag.Id,
                TagName = articlesTag.GetLocalized(y => y.Name)
            };

            _helper.PreparePagingFilteringModel(model.PagingFilteringContext, command, new PageSizeContext
            {
                AllowUsersToSelectPageSize = _catalogSettings.ArticlesByTagAllowUsersToSelectPageSize,
                PageSize        = _catalogSettings.ArticlesByTagPageSize,
                PageSizeOptions = _catalogSettings.ArticlesByTagPageSizeOptions.IsEmpty()
                    ? _catalogSettings.DefaultPageSizeOptions
                    : _catalogSettings.ArticlesByTagPageSizeOptions
            });

            //articless

            var ctx = new ArticleSearchContext();

            ctx.ArticleTagId            = articlesTag.Id;
            ctx.LanguageId              = _services.WorkContext.WorkingLanguage.Id;
            ctx.OrderBy                 = (ArticleSortingEnum)command.OrderBy;
            ctx.PageIndex               = command.PageNumber - 1;
            ctx.PageSize                = command.PageSize;
            ctx.SiteId                  = _services.SiteContext.CurrentSiteIdIfMultiSiteMode;
            ctx.VisibleIndividuallyOnly = true;

            var articless = _articleService.SearchArticles(ctx);

            model.Articles = _helper.PrepareArticlePostModels(
                articless).ToList();

            model.PagingFilteringContext.LoadPagedList(articless);
            //model.PagingFilteringContext.ViewMode = viewMode;
            return(View(model));
        }
示例#3
0
        public ActionResult ListRss()
        {
            var feed = new SyndicationFeed(
                string.Format("{0}: {1}", _services.SiteContext.CurrentSite.Name, T("RSS.RecentlyAddedArticles")),
                T("RSS.InformationAboutArticles"),
                new Uri(_services.WebHelper.GetSiteLocation(false)),
                "RecentlyAddedArticlesRSS",
                DateTime.UtcNow);

            if (!_catalogSettings.RecentlyAddedArticlesEnabled)
            {
                return new RssActionResult()
                       {
                           Feed = feed
                       }
            }
            ;

            var items = new List <SyndicationItem>();

            var ctx = new ArticleSearchContext();

            ctx.LanguageId = _services.WorkContext.WorkingLanguage.Id;
            ctx.OrderBy    = ArticleSortingEnum.CreatedOn;
            ctx.PageSize   = _catalogSettings.RecentlyAddedArticlesNumber;
            ctx.SiteId     = _services.SiteContext.CurrentSiteIdIfMultiSiteMode;
            ctx.VisibleIndividuallyOnly = true;

            var articles = _articleService.SearchArticles(ctx);

            foreach (var article in articles)
            {
                string articleUrl = Url.RouteUrl("Article", new { SeName = article.GetSeName() }, "http");

                if (!String.IsNullOrEmpty(articleUrl))
                {
                    items.Add(new SyndicationItem(article.GetLocalized(x => x.Title), article.GetLocalized(x => x.ShortContent), new Uri(articleUrl), String.Format("RecentlyAddedArticle:{0}", article.Id), article.CreatedOnUtc));
                }
            }
            feed.Items = items;
            return(new RssActionResult()
            {
                Feed = feed
            });
        }
        /// <summary>
        /// 搜索下拉提醒
        /// </summary>
        /// <param name="term"></param>
        /// <returns></returns>
        public ActionResult SearchTermAutoComplete(string term)
        {
            if (String.IsNullOrWhiteSpace(term) || term.Length < _catalogSettings.ArticleSearchTermMinimumLength)
            {
                return(Content(""));
            }

            // articles
            var pageSize = _catalogSettings.ArticleSearchAutoCompleteNumberOfArticles > 0 ? _catalogSettings.ArticleSearchAutoCompleteNumberOfArticles : 10;

            var ctx = new ArticleSearchContext();

            ctx.LanguageId = _services.WorkContext.WorkingLanguage.Id;
            ctx.Keywords   = term;
            ctx.OrderBy    = ArticleSortingEnum.Position;
            ctx.PageSize   = pageSize;
            ctx.SiteId     = _services.SiteContext.CurrentSiteIdIfMultiSiteMode;
            ctx.VisibleIndividuallyOnly = true;

            var articles = _articleService.SearchArticles(ctx);

            var models = _helper.PrepareArticlePostModels(
                articles,
                false,
                _catalogSettings.ShowArticleImagesInSearchAutoComplete,
                _mediaSettings.ThumbPictureSizeOnDetailsPage).ToList();

            var result = (from p in models
                          select new
            {
                label = p.Title,
                secondary = p.ShortContent.Truncate(70, "...") ?? "",
                articleurl = Url.RouteUrl("Article", new { SeName = p.SeName }),
                articlepictureurl = p.DefaultPictureModel.ImageUrl
            })
                         .ToList();

            return(Json(result, JsonRequestBehavior.AllowGet));
        }
        public ActionResult Search(SearchModel model, SearchPagingFilteringModel command)
        {
            if (model == null)
            {
                model = new SearchModel();
            }

            // 'Continue shopping' URL
            _genericAttributeService.SaveAttribute(_services.WorkContext.CurrentUser,
                                                   SystemUserAttributeNames.LastContinueShoppingPage,
                                                   _services.WebHelper.GetThisPageUrl(false),
                                                   _services.SiteContext.CurrentSite.Id);

            if (command.PageSize <= 0)
            {
                command.PageSize = _catalogSettings.SearchPageArticlesPerPage;
            }
            if (command.PageNumber <= 0)
            {
                command.PageNumber = 1;
            }

            _helper.PreparePagingFilteringModel(model.PagingFilteringContext, command, new PageSizeContext
            {
                AllowUsersToSelectPageSize = _catalogSettings.ArticleSearchAllowUsersToSelectPageSize,
                PageSize        = _catalogSettings.SearchPageArticlesPerPage,
                PageSizeOptions = _catalogSettings.ArticleSearchPageSizeOptions
            });

            if (model.Q == null)
            {
                model.Q = "";
            }
            model.Q = model.Q.Trim();

            // Build AvailableCategories
            // first empty entry
            model.AvailableArticleCategories.Add(new SelectListItem
            {
                Value = "0",
                Text  = T("Common.All")
            });

            var navModel = _helper.PrepareCategoryNavigationModel(0, 0);

            navModel.Root.TraverseTree((node) =>
            {
                if (node.IsRoot)
                {
                    return;
                }

                int id         = node.Value.EntityId;
                var breadcrumb = node.GetBreadcrumb().Select(x => x.Text).ToArray();

                model.AvailableArticleCategories.Add(new SelectListItem
                {
                    Value    = id.ToString(),
                    Text     = String.Join(" > ", breadcrumb),
                    Selected = model.Cid == id
                });
            });



            IPagedList <Article> articles = new PagedList <Article>(new List <Article>(), 0, 1);

            // only search if query string search keyword is set (used to avoid searching or displaying search term min length error message on /search page load)
            if (Request.Params["Q"] != null)
            {
                if (model.Q.Length < _catalogSettings.ArticleSearchTermMinimumLength)
                {
                    model.Warning = string.Format(T("Search.SearchTermMinimumLengthIsNCharacters"), _catalogSettings.ArticleSearchTermMinimumLength);
                }
                else
                {
                    var  categoryIds          = new List <int>();
                    bool searchInDescriptions = false;
                    if (model.As)
                    {
                        // advanced search
                        var categoryId = model.Cid;
                        if (categoryId > 0)
                        {
                            categoryIds.Add(categoryId);
                            if (model.Isc)
                            {
                                // include subcategories
                                categoryIds.AddRange(_helper.GetChildCategoryIds(categoryId));
                            }
                        }

                        searchInDescriptions = model.Sid;
                    }

                    //var searchInArticleTags = false;
                    var searchInArticleTags = searchInDescriptions;

                    //articles
                    #region Text Search


                    var ctx = new ArticleSearchContext();
                    ctx.CategoryIds             = categoryIds;
                    ctx.Keywords                = model.Q;
                    ctx.SearchDescriptions      = searchInDescriptions;
                    ctx.SearchArticleTags       = searchInArticleTags;
                    ctx.LanguageId              = _services.WorkContext.WorkingLanguage.Id;
                    ctx.OrderBy                 = (ArticleSortingEnum)command.OrderBy; // ArticleSortingEnum.Position;
                    ctx.PageIndex               = command.PageNumber - 1;
                    ctx.PageSize                = command.PageSize;
                    ctx.SiteId                  = _services.SiteContext.CurrentSiteIdIfMultiSiteMode;
                    ctx.VisibleIndividuallyOnly = true;

                    articles = _articleService.SearchArticles(ctx);
                    #endregion
                    #region Lucene

                    //var searchQuery = new SearchQuery(model.Q)
                    // {
                    //     NumberOfHitsToReturn = command.PageSize,
                    //     ReturnFromPosition = command.PageSize * (command.PageNumber - 1)
                    // };

                    //// Perform the searh
                    //var result = this._searchProvider.Value.Search(searchQuery);
                    #endregion

                    model.Articles = _helper.PrepareArticlePostModels(
                        articles).ToList();

                    model.NoResults = !model.Articles.Any();
                }
            }

            model.PagingFilteringContext.LoadPagedList(articles);
            return(View(model));
        }
        public ActionResult Category(int categoryId, ArticleCatalogPagingFilteringModel command, string filter)
        {
            var category = _articlecategoryService.GetArticleCategoryById(categoryId);

            if (category == null || category.Deleted)
            {
                return(HttpNotFound());
            }

            //判断内容访问权限,实际项目中需求及去掉注释启用
            //It allows him to preview a category before publishing
            //if (!category.Published )
            //    return HttpNotFound();

            ////ACL (access control list)
            //if (!_aclService.Authorize(category))
            //    return HttpNotFound();

            //site mapping
            if (!_siteMappingService.Authorize(category))
            {
                return(HttpNotFound());
            }

            //'Continue shopping' URL
            _genericAttributeService.SaveAttribute(_services.WorkContext.CurrentUser,
                                                   SystemUserAttributeNames.LastContinueShoppingPage,
                                                   _services.WebHelper.GetThisPageUrl(false),
                                                   _services.SiteContext.CurrentSite.Id);

            if (command.PageNumber <= 0)
            {
                command.PageNumber = 1;
            }



            var model = category.ToModel();

            _helper.PreparePagingFilteringModel(model.PagingFilteringContext, command, new PageSizeContext
            {
                AllowUsersToSelectPageSize = category.AllowUsersToSelectPageSize,
                PageSize        = category.PageSize,
                PageSizeOptions = category.PageSizeOptions
            });

            //category breadcrumb
            model.DisplayCategoryBreadcrumb = _catalogSettings.CategoryBreadcrumbEnabled;
            if (model.DisplayCategoryBreadcrumb)
            {
                model.CategoryBreadcrumb = _helper.GetCategoryBreadCrumb(category.Id, 0);
            }

            model.DisplayFilter = _catalogSettings.FilterEnabled;
            model.ShowSubcategoriesAboveArticleLists = _catalogSettings.ShowSubcategoriesAboveArticleLists;

            var customerRolesIds = _services.WorkContext.CurrentUser.UserRoles.Where(x => x.Active).Select(x => x.Id).ToList();

            //subcategories子分类
            //model.SubCategories = _articlecategoryService
            //    .GetAllArticleCategoriesByParentCategoryId(categoryId)
            //    .Select(x =>
            //    {
            //        var subCatName = x.GetLocalized(y => y.Name);
            //        var subCatModel = new ArticleCategoryModel.SubCategoryModel()
            //        {
            //            Id = x.Id,
            //            Name = subCatName,
            //            SeName = x.GetSeName(),
            //        };

            //        //prepare picture model
            //        int pictureSize = _mediaSettings.CategoryThumbPictureSize;
            //        var categoryPictureCacheKey = string.Format(ModelCacheEventConsumer.CATEGORY_PICTURE_MODEL_KEY, x.Id, pictureSize, true, _services.WorkContext.WorkingLanguage.Id, _services.WebHelper.IsCurrentConnectionSecured(), _services.SiteContext.CurrentSite.Id);
            //        subCatModel.PictureModel = _services.Cache.Get(categoryPictureCacheKey, () =>
            //        {
            //            var picture = _pictureService.GetPictureById(x.PictureId.GetValueOrDefault());
            //            var pictureModel = new PictureModel()
            //            {
            //                PictureId = x.PictureId.GetValueOrDefault(),
            //                FullSizeImageUrl = _pictureService.GetPictureUrl(picture),
            //                ImageUrl = _pictureService.GetPictureUrl(picture, targetSize: pictureSize),
            //                Title = string.Format(T("Media.Category.ImageLinkTitleFormat"), subCatName),
            //                AlternateText = string.Format(T("Media.Category.ImageAlternateTextFormat"), subCatName)
            //            };
            //            return pictureModel;
            //        });

            //        return subCatModel;
            //    })
            //    .ToList();

            // Articles
            if (filter.HasValue())
            {
                //var context = new FilterArticleContext
                //{
                //    ParentCategoryID = category.Id,
                //    CategoryIds = new List<int> { category.Id },
                //    Criteria = _filterService.Deserialize(filter),
                //    OrderBy = command.OrderBy
                //};

                //if (_catalogSettings.ShowArticlesFromSubcategories)
                //    context.CategoryIds.AddRange(_helper.GetChildCategoryIds(category.Id));

                //var filterQuery = _filterService.ArticleFilter(context);
                //var articles = new PagedList<Article>(filterQuery, command.PageIndex, command.PageSize);

                //model.Articles = _helper.PrepareArticleOverviewModels(
                //    articles,
                //    prepareColorAttributes: true,
                //    prepareClients: command.ViewMode.IsCaseInsensitiveEqual("list")).ToList();
                //model.PagingFilteringContext.LoadPagedList(articles);
            }
            else
            {
                var ctx2 = new ArticleSearchContext();

                if (category.Id > 0)
                {
                    ctx2.CategoryIds.Add(category.Id);
                    if (_catalogSettings.ShowArticlesFromSubcategories)
                    {
                        // include subcategories
                        ctx2.CategoryIds.AddRange(_helper.GetChildCategoryIds(category.Id));
                    }
                }
                ctx2.LanguageId = _services.WorkContext.WorkingLanguage.Id;

                ctx2.OrderBy   = (ArticleSortingEnum)command.OrderBy; // ArticleSortingEnum.Position;
                ctx2.PageIndex = command.PageNumber - 1;
                ctx2.PageSize  = command.PageSize;
                ctx2.SiteId    = _services.SiteContext.CurrentSiteIdIfMultiSiteMode;
                ctx2.Origin    = categoryId.ToString();

                var articles = _articleService.SearchArticles(ctx2);

                model.Articles = _helper.PrepareArticlePostModels(
                    articles,
                    preparePictureModel: true).ToList();

                model.PagingFilteringContext.LoadPagedList(articles);
            }



            // template
            var templateCacheKey = string.Format(ModelCacheEventConsumer.ARTICLECATEGORY_TEMPLATE_MODEL_KEY, category.ModelTemplateId);
            var templateViewPath = _services.Cache.Get(templateCacheKey, () =>
            {
                var template = _modelTemplateService.GetModelTemplateById(category.ModelTemplateId);
                if (template == null)
                {
                    template = _modelTemplateService.GetAllModelTemplates().FirstOrDefault();
                }
                return(template.ViewPath);
            });

            // activity log
            _services.UserActivity.InsertActivity("PublicSite.ViewCategory", T("ActivityLog.PublicSite.ViewCategory"), category.Name);

            if (IsAjaxRequest())
            {
                return(Json(model));
            }
            else
            {
                return(View(templateViewPath, model));
            }
        }
        private ArticleCategoryModel CategoryFilter(int categoryId, int?articleThumbPictureSize, ArticleCatalogPagingFilteringModel command, string partialView = null)
        {
            var cacheKey = string.Format(ModelCacheEventConsumer.HOMEPAGE_TOPARTICLESMODEL_KEY, _services.WorkContext.WorkingLanguage.Id, _services.SiteContext.CurrentSite.Id, categoryId);

            if (partialView.IsEmpty())
            {
                cacheKey = string.Format(ModelCacheEventConsumer.HOMEPAGE_TOPARTICLESMODEL_PARTVIEW_KEY, _services.WorkContext.WorkingLanguage.Id, _services.SiteContext.CurrentSite.Id, categoryId, partialView);
            }
            var cachedModel = _services.Cache.Get(cacheKey, () =>
            {
                var category = _articlecategoryService.GetArticleCategoryById(categoryId);
                if (category == null || category.Deleted)
                {
                    return(null);
                }

                //Check whether the current user has a "Manage catalog" permission
                //It allows him to preview a category before publishing
                //if (!category.Published )
                //    return null;

                ////ACL (access control list)
                //if (!_aclService.Authorize(category))
                //    return null;

                //Site mapping
                if (!_siteMappingService.Authorize(category))
                {
                    return(null);
                }


                //'Continue shopping' URL
                _genericAttributeService.SaveAttribute(_services.WorkContext.CurrentUser,
                                                       SystemUserAttributeNames.LastContinueShoppingPage,
                                                       _services.WebHelper.GetThisPageUrl(false),
                                                       _services.SiteContext.CurrentSite.Id);

                if (command.PageNumber <= 0)
                {
                    command.PageNumber = 1;
                }



                var model = category.ToModel();
                _helper.PreparePagingFilteringModel(model.PagingFilteringContext, command, new PageSizeContext
                {
                    AllowUsersToSelectPageSize = category.AllowUsersToSelectPageSize,
                    PageSize        = category.PageSize,
                    PageSizeOptions = category.PageSizeOptions
                });
                //category breadcrumb
                model.DisplayCategoryBreadcrumb = _catalogSettings.CategoryBreadcrumbEnabled;
                if (model.DisplayCategoryBreadcrumb)
                {
                    model.CategoryBreadcrumb = _helper.GetCategoryBreadCrumb(category.Id, 0);
                }

                // Articles

                var ctx2 = new ArticleSearchContext();
                if (category.Id > 0)
                {
                    ctx2.CategoryIds.Add(category.Id);
                    if (_catalogSettings.ShowArticlesFromSubcategories)
                    {
                        // include subcategories
                        ctx2.CategoryIds.AddRange(_helper.GetChildCategoryIds(category.Id));
                    }
                }

                ctx2.LanguageId = _services.WorkContext.WorkingLanguage.Id;

                ctx2.OrderBy   = (ArticleSortingEnum)command.OrderBy; // ArticleSortingEnum.Position;
                ctx2.PageIndex = command.PageNumber - 1;
                ctx2.PageSize  = command.PageSize;
                ctx2.SiteId    = _services.SiteContext.CurrentSiteIdIfMultiSiteMode;
                ctx2.Origin    = categoryId.ToString();
                ctx2.IsTop     = command.IsTop;
                ctx2.IsHot     = command.IsHot;
                ctx2.IsRed     = command.IsRed;
                ctx2.IsSlide   = command.IsSlide;
                var articles   = _articleService.SearchArticles(ctx2);

                model.PagingFilteringContext.LoadPagedList(articles);

                model.Articles = _helper.PrepareArticlePostModels(
                    articles,
                    preparePictureModel: true, articleThumbPictureSize: articleThumbPictureSize).ToList();


                // activity log
                _services.UserActivity.InsertActivity("PublicSite.ViewCategory", T("ActivityLog.PublicSite.ViewCategory"), category.Name);
                return(model);
            });

            return(cachedModel);
        }