public SearchSecurityTrimmer(SearchSecurityTrimmerContext searchContext)
 {
     _securityChecker = searchContext.SecurityChecker;
     _searcher = searchContext.Searcher;
     _luceneQuery = searchContext.LuceneQuery;
     _searchQuery = searchContext.SearchQuery;
     _hitDocs = new List<ScoreDoc>(16);
 }
예제 #2
0
 public SearchResults ModuleSearch(SearchQuery searchQuery)
 {
     searchQuery.SearchTypeIds = new List<int> { _moduleSearchTypeId };
     var results = GetResults(searchQuery);
     return new SearchResults { TotalHits = results.Item1, Results = results.Item2 };
 }
예제 #3
0
 public SearchResults SiteSearch(SearchQuery searchQuery)
 {
     var results = GetResults(searchQuery);
     return new SearchResults{TotalHits = results.Item1, Results = results.Item2};
 }
예제 #4
0
        private Tuple<int, IList<SearchResult>> GetSecurityTrimmedResults(SearchQuery searchQuery, LuceneQuery luceneQuery)
        {
            var results = new List<SearchResult>();
            var totalHits = 0;

            //****************************************************************************
            // First Fetch and determine starting item of current page
            //****************************************************************************
            if (searchQuery.PageSize > 0)
            {
                var luceneResults = LuceneController.Instance.Search(luceneQuery, out totalHits, HasPermissionToViewDoc);
                results = luceneResults.Select(GetSearchResultFromLuceneResult).ToList();

                //****************************************************************************
                //Adding URL Links to final trimmed results
                //****************************************************************************
                foreach (var result in results)
                {
                    if (string.IsNullOrEmpty(result.Url))
                    {
                        var resultController = GetSearchResultControllers().Single(sc => sc.Key == result.SearchTypeId).Value;
                        result.Url = resultController.GetDocUrl(result);
                    }
                }
            }

            return new Tuple<int, IList<SearchResult>>(totalHits, results);
        }
예제 #5
0
        private void ApplySearchTypeIdFilter(BooleanQuery query, SearchQuery searchQuery)
        {
            //Special handling for Module Search
            if (searchQuery.SearchTypeIds.Count() == 1 && searchQuery.SearchTypeIds.Contains(_moduleSearchTypeId))
            {
                //When moduleid is specified, we ignore other searchtypeid or moduledefinitionid. Major security check
                if (searchQuery.ModuleId > 0)
                {
                    //this is the main hook for module based search. Occur.MUST is a requirement for this condition or else results from other modules will be found
                    query.Add(NumericRangeQuery.NewIntRange(Constants.ModuleIdTag, searchQuery.ModuleId, searchQuery.ModuleId, true, true), Occur.MUST);
                }
                else
                {
                    var modDefQuery = new BooleanQuery();
                    foreach (var moduleDefId in searchQuery.ModuleDefIds)
                    {
                        modDefQuery.Add(NumericRangeQuery.NewIntRange(Constants.ModuleDefIdTag, moduleDefId, moduleDefId, true, true), Occur.SHOULD);
                    }
                    if (searchQuery.ModuleDefIds.Any())
                        query.Add(modDefQuery, Occur.MUST); //Note the MUST
                }

                query.Add(NumericRangeQuery.NewIntRange(Constants.SearchTypeTag, _moduleSearchTypeId, _moduleSearchTypeId, true, true), Occur.MUST);
            }
            else
            {
                var searchTypeIdQuery = new BooleanQuery();
                foreach (var searchTypeId in searchQuery.SearchTypeIds)
                {
                    if (searchTypeId == _moduleSearchTypeId)
                    {
			foreach (var moduleDefId in searchQuery.ModuleDefIds.OrderBy(id => id))
                        {
                            searchTypeIdQuery.Add(NumericRangeQuery.NewIntRange(Constants.ModuleDefIdTag, moduleDefId, moduleDefId, true, true), Occur.SHOULD);
                        }
                        if (!searchQuery.ModuleDefIds.Any())
                            searchTypeIdQuery.Add(NumericRangeQuery.NewIntRange(Constants.SearchTypeTag, searchTypeId, searchTypeId, true, true), Occur.SHOULD);  
                    }
                    else
                    {
                        searchTypeIdQuery.Add(NumericRangeQuery.NewIntRange(Constants.SearchTypeTag, searchTypeId, searchTypeId, true, true), Occur.SHOULD);       
                    }
                }
                query.Add(searchTypeIdQuery, Occur.MUST);
            }
        }
  private IEnumerable<GroupedBasicView> GetGroupBasicViewResults(SearchQuery query)
 {
     var userSearchContentSource = new SearchContentSource
                                       {
                                           SearchTypeId = UrlSearchTypeId,
                                           SearchTypeName = UrlSearchTypeName,
                                           SearchResultClass = FakeResultControllerClass,
                                           LocalizedName = UserSearchTypeName,
                                           ModuleDefinitionId = 0
                                       };
     var results = _searchServiceController.GetGroupedBasicViews(query, userSearchContentSource, PortalId0);
     return results;
 }
        public HttpResponseMessage Search(string search, string culture, int pageIndex, int pageSize, int sortOption)
        {
            string cleanedKeywords;
            search = (search ?? string.Empty).Trim();
            var tags = SearchQueryStringParser.Instance.GetTags(search, out cleanedKeywords);
            var beginModifiedTimeUtc = SearchQueryStringParser.Instance.GetLastModifiedDate(cleanedKeywords, out cleanedKeywords);
            var searchTypes = SearchQueryStringParser.Instance.GetSearchTypeList(cleanedKeywords, out cleanedKeywords);

            var contentSources = GetSearchContentSources(searchTypes);
            var settings = GetSearchModuleSettings();
            var searchTypeIds = GetSearchTypeIds(settings, contentSources);
            var moduleDefids = GetSearchModuleDefIds(settings, contentSources);
            var portalIds = GetSearchPortalIds(settings, -1);

            var more = false;
            var totalHits = 0;
            var results = new List<GroupedDetailView>();
            if (portalIds.Any() && searchTypeIds.Any() && 
                (!string.IsNullOrEmpty(cleanedKeywords) || tags.Any()))
            {
                var query = new SearchQuery
                    {
                        KeyWords = cleanedKeywords,
                        Tags = tags,
                        PortalIds = portalIds,
                        SearchTypeIds = searchTypeIds,
                        ModuleDefIds = moduleDefids,
                        BeginModifiedTimeUtc = beginModifiedTimeUtc,
                        EndModifiedTimeUtc = beginModifiedTimeUtc > DateTime.MinValue ? DateTime.MaxValue : DateTime.MinValue,
                        PageIndex = pageIndex,
                        PageSize = pageSize,
                        SortField = (SortFields) sortOption,
                        TitleSnippetLength = 120,
                        BodySnippetLength = 300,
                        CultureCode = culture,
                        WildCardSearch = IsWildCardEnabledForModule()
                    };

                try
                {
                    results = GetGroupedDetailViews(query, out totalHits, out more).ToList();
                }
                catch (Exception ex)
                {
                    Services.Exceptions.Exceptions.LogException(ex);
                }
            }

            return Request.CreateResponse(HttpStatusCode.OK, new { results, totalHits, more });
        }
        private IEnumerable<BasicView> GetBasicViews(SearchQuery searchQuery, out int totalHits)
        {
            var sResult = SearchController.Instance.SiteSearch(searchQuery);
            totalHits = sResult.TotalHits;

            return sResult.Results.Select(result => 
                new BasicView
                    {
                        Title = GetTitle(result),
                        DocumentTypeName = InternalSearchController.Instance.GetSearchDocumentTypeDisplayName(result),
                        DocumentUrl = result.Url,
                        Snippet = result.Snippet,
                    });
        }
예제 #9
0
        private static SearchResult GetPartialSearchResult(Document doc, SearchQuery searchQuery)
        {
            var result = new SearchResult {SearchContext = searchQuery.SearchContext};
            var localeField = doc.GetField(Constants.LocaleTag);

            if (localeField != null)
            {
                int id;
                result.CultureCode = int.TryParse(localeField.StringValue, out id) && id >= 0
                    ? LocaleController.Instance.GetLocale(id).Code : Null.NullString;
            }

            FillTagsValues(doc, result);
            return result;
        }
예제 #10
0
 private bool HasPermissionToViewDoc(Document document, SearchQuery searchQuery)
 {
     // others LuceneResult fields are not impotrant at this moment
     var result = GetPartialSearchResult(document, searchQuery);
     var resultController = GetSearchResultControllers().SingleOrDefault(sc => sc.Key == result.SearchTypeId).Value;
     return resultController != null && resultController.HasViewPermission(result);
 }
        public HttpResponseMessage Preview(string keywords, string culture, int forceWild = 1, int portal = -1)
        {
            string cleanedKeywords;
            keywords = (keywords ?? string.Empty).Trim();
            var tags = SearchQueryStringParser.Instance.GetTags(keywords, out cleanedKeywords);
            var beginModifiedTimeUtc = SearchQueryStringParser.Instance.GetLastModifiedDate(cleanedKeywords, out cleanedKeywords);
            var searchTypes = SearchQueryStringParser.Instance.GetSearchTypeList(keywords, out cleanedKeywords);
            
            var contentSources = GetSearchContentSources(searchTypes);
            var settings = GetSearchModuleSettings();
            var searchTypeIds = GetSearchTypeIds(settings, contentSources);
            var moduleDefids = GetSearchModuleDefIds(settings, contentSources);
            var portalIds = GetSearchPortalIds(settings, portal);

            var userSearchTypeId = SearchHelper.Instance.GetSearchTypeByName("user").SearchTypeId;
            var userSearchSource = contentSources.FirstOrDefault(s => s.SearchTypeId == userSearchTypeId);

            var results = new List<GroupedBasicView>();
            if (portalIds.Any() && searchTypeIds.Any() &&
                (!string.IsNullOrEmpty(cleanedKeywords) || tags.Any()))
            {
                var query = new SearchQuery
                {
                    KeyWords = cleanedKeywords,
                    Tags = tags,
                    PortalIds = portalIds,
                    SearchTypeIds = searchTypeIds,
                    ModuleDefIds = moduleDefids,
                    BeginModifiedTimeUtc = beginModifiedTimeUtc,
                    PageIndex = 1,
                    PageSize = 5,
                    TitleSnippetLength = 40,
                    BodySnippetLength = 100,
                    CultureCode = culture,
                    WildCardSearch = forceWild > 0 
                };

                try
                {
                    results = GetGroupedBasicViews(query, userSearchSource, PortalSettings.PortalId);
                }
                catch (Exception ex)
                {
                    Services.Exceptions.Exceptions.LogException(ex);
                }
            }

            return Request.CreateResponse(HttpStatusCode.OK, results);
        }
        internal List<GroupedBasicView> GetGroupedBasicViews(SearchQuery query, SearchContentSource userSearchSource, int portalId)
        {
            int totalHists;
            var results = new List<GroupedBasicView>();
            var previews = GetBasicViews(query, out totalHists);

            foreach (var preview in previews)
            {
                //if the document type is user, then try to add user pic into preview's custom attributes.
                if (userSearchSource != null && preview.DocumentTypeName == userSearchSource.LocalizedName)
                {
                    var match = Regex.Match(preview.DocumentUrl, "userid(/|\\|=)(\\d+)", RegexOptions.IgnoreCase);
                    if (match.Success)
                    {
                        var userid = Convert.ToInt32(match.Groups[2].Value);
                        var user = UserController.Instance.GetUserById(portalId, userid); 
                        if (user != null)
                        {
                            preview.Attributes.Add("Avatar", user.Profile.PhotoURL);
                        }
                    }
                }

                var groupedResult = results.SingleOrDefault(g => g.DocumentTypeName == preview.DocumentTypeName);
                if (groupedResult != null)
                {
                    if (!groupedResult.Results.Any(r => string.Equals(r.DocumentUrl, preview.DocumentUrl)))
                        groupedResult.Results.Add(new BasicView
                        {
                            Title = preview.Title,
                            Snippet = preview.Snippet,
                            DocumentUrl = preview.DocumentUrl,
                            Attributes = preview.Attributes
                        });
                }
                else
                {
                    results.Add(new GroupedBasicView(preview));
                }
            }

            return results;
        }
        public void GetSearchResultsBasic()
        {
            const string keyword = "awesome";
            const string userUrl = "mysite/userid/1";
            const string tabUrl1 = "mysite/Home";
            const string tabUrl2 = "mysite/AboutUs";

            var doc1 = new SearchDocument { UniqueKey = "key01", TabId = TabId1, Url = tabUrl1, Title = keyword, SearchTypeId = TabSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow, RoleId = RoleId731 };
            var doc2 = new SearchDocument { UniqueKey = "key02", TabId = TabId2, Url = tabUrl2, Title = keyword, SearchTypeId = TabSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow, RoleId = RoleId0 };
            var userdoc = new SearchDocument { UniqueKey = "key03", Url = userUrl, Title = keyword, SearchTypeId = UserSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow, RoleId = RoleId0 };
            _internalSearchController.AddSearchDocument(doc1);
            _internalSearchController.AddSearchDocument(doc2);
            _internalSearchController.AddSearchDocument(userdoc);

            var query = new SearchQuery
            {
                KeyWords = keyword,
                PortalIds = new List<int> { PortalId0 },
                SearchTypeIds = new[] { ModuleSearchTypeId, TabSearchTypeId, UserSearchTypeId },
                ModuleDefIds = new List<int> { HtmlModDefId },
                BeginModifiedTimeUtc = DateTime.Now.AddHours(-1.00),
                EndModifiedTimeUtc = DateTime.Now > DateTime.MinValue ? DateTime.MaxValue : DateTime.MinValue,
                PageIndex = 1,
                PageSize = 15,
                SortField = 0,
                TitleSnippetLength = 120,
                BodySnippetLength = 300,
                CultureCode = CultureEnUs,
                WildCardSearch = true
            };

            //Run 
            var search = GetGroupBasicViewResults(query);
            //Assert
            //Overal 2 groups - tabs and users
            var groupedBasicViews = search as List<GroupedBasicView> ?? search.ToList();
            Assert.AreEqual(2, groupedBasicViews.Count());

            //1 User results 
            Assert.AreEqual(1, groupedBasicViews.Single(x=>x.DocumentTypeName=="user").Results.Count());

            //User result should have 1 attribute(avatar)
            Assert.AreEqual(1, groupedBasicViews.Single(x => x.DocumentTypeName == "user").Results.ElementAt(0).Attributes.Count());

            //2 Tabs results
            Assert.AreEqual(2, groupedBasicViews.Single(x => x.DocumentTypeName == "tab").Results.Count());
        }
        public void GetSearchResultsDetailed()
        {
            const string keyword = "super";
            const string moduleBody = "super content is here";
            const string userUrl = "mysite/userid/1";
            const string tabUrl1 = "mysite/Home";
            const string tabUrl2 = "mysite/AboutUs";

            //first tab with 2 modules
            var doc1 = new SearchDocument { UniqueKey = "key01", TabId = TabId1, Url = tabUrl1, Title = keyword, SearchTypeId = TabSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow };
            var doc2 = new SearchDocument { UniqueKey = "key02", TabId = TabId1, Title = keyword, Url = tabUrl1, SearchTypeId = ModuleSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow, ModuleDefId = HtmlModuleDefId, ModuleId = HtmlModuleId2, Body = moduleBody, RoleId = 731};
            var doc3 = new SearchDocument { UniqueKey = "key03", TabId = TabId1, Title = keyword, Url = tabUrl1, SearchTypeId = ModuleSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow, ModuleDefId = HtmlModuleDefId, ModuleId = HtmlModuleId1, Body = moduleBody, RoleId = 731 };
           
            //second tab with 1 module
            var doc4 = new SearchDocument { UniqueKey = "key04", TabId = TabId2, Url = tabUrl2, Title = keyword, SearchTypeId = TabSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow, RoleId = RoleId0 };
            var doc5 = new SearchDocument { UniqueKey = "key05", TabId = TabId2, Title = keyword, Url = tabUrl2, SearchTypeId = ModuleSearchTypeId, ModuleDefId = HtmlModuleId, ModuleId = HtmlModuleId3, ModifiedTimeUtc = DateTime.UtcNow, Body = moduleBody, RoleId = 731 };
            
            //user doc
            var userdoc = new SearchDocument { UniqueKey = "key06", Url = userUrl, Title = keyword, SearchTypeId = UserSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow, RoleId = RoleId731 };
            _internalSearchController.AddSearchDocument(doc1);
            _internalSearchController.AddSearchDocument(doc2);
            _internalSearchController.AddSearchDocument(doc3);
            _internalSearchController.AddSearchDocument(doc4);
            _internalSearchController.AddSearchDocument(doc5);
            _internalSearchController.AddSearchDocument(userdoc);

            var query = new SearchQuery
            {
                KeyWords = keyword,
                SearchTypeIds = new[] { ModuleSearchTypeId, TabSearchTypeId, UserSearchTypeId },
                RoleId = 731
            };

            //Run 
            var search = GetGroupedDetailViewResults(query);
            
            //Assert
            var groupedDetailViews = search as List<GroupedDetailView> ?? search.ToList();
            
            //Overall 3 groups - tab1, tab2 and user
            Assert.AreEqual(3, groupedDetailViews.Count());
            
            //Tab 1 has 2 DetailViews 
            Assert.AreEqual(2, groupedDetailViews.Single(x=>x.DocumentUrl==tabUrl1).Results.Count());

            //Tab 2 has 1 DetailViews 
            Assert.AreEqual(1, groupedDetailViews.Single(x => x.DocumentUrl == tabUrl2).Results.Count());

            //UserUrl has 1 DetailViews 
            Assert.AreEqual(1, groupedDetailViews.Single(x => x.DocumentUrl == userUrl).Results.Count());
        }
 private IEnumerable<GroupedDetailView> GetGroupedDetailViewResults(SearchQuery searchQuery)
 {
     bool more = false;
     int totalHits = 0;
     var results = _searchServiceController.GetGroupedDetailViews(searchQuery, UserSearchTypeId, out totalHits, out more);
     return results;
 }
예제 #16
0
        private Tuple<int, IList<SearchResult>> GetResults(SearchQuery searchQuery)
        {
            Requires.NotNull("Query", searchQuery);
            Requires.PropertyNotEqualTo("searchQuery", "SearchTypeIds", searchQuery.SearchTypeIds.Count(), 0);

            if((searchQuery.ModuleId > 0) && (searchQuery.SearchTypeIds.Count() > 1 || !searchQuery.SearchTypeIds.Contains(_moduleSearchTypeId)))
                throw new ArgumentException("ModuleId based search must have SearchTypeId for a module only");

            if(searchQuery.SortField == SortFields.CustomStringField || searchQuery.SortField == SortFields.CustomNumericField
                || searchQuery.SortField == SortFields.NumericKey || searchQuery.SortField == SortFields.Keyword)
                Requires.NotNullOrEmpty("CustomSortField", searchQuery.CustomSortField);

            //TODO - Explore Slop factor for Phrase query

            var query = new BooleanQuery();
            if (!string.IsNullOrEmpty(searchQuery.KeyWords))
            {
                try
                {
                    var keywords = SearchHelper.Instance.RephraseSearchText(searchQuery.KeyWords, searchQuery.WildCardSearch);
                    // don't use stemming analyzer for exact matches or non-analyzed fields (e.g. Tags)
                    var analyzer = new SearchQueryAnalyzer(true);
                    var nonStemmerAnalyzer = new SearchQueryAnalyzer(false);
                    var keywordQuery = new BooleanQuery();
                    foreach (var fieldToSearch in Constants.KeyWordSearchFields)
                    {
                        var parserContent = new QueryParser(Constants.LuceneVersion, fieldToSearch,
                            fieldToSearch == Constants.Tag ? nonStemmerAnalyzer : analyzer);
                        var parsedQueryContent = parserContent.Parse(keywords);
                        keywordQuery.Add(parsedQueryContent, Occur.SHOULD);
                    }
                    query.Add(keywordQuery, Occur.MUST);
                }
                catch (Exception)
                {
                    foreach (var word in searchQuery.KeyWords.Split(' '))
                    {
                        query.Add(new TermQuery(new Term(Constants.ContentTag, word.ToLower())), Occur.SHOULD);
                    }
                }
            }

            var portalIdQuery = new BooleanQuery();
            foreach (var portalId in searchQuery.PortalIds)
            {
                portalIdQuery.Add(NumericRangeQuery.NewIntRange(Constants.PortalIdTag, portalId, portalId, true, true), Occur.SHOULD);                
            }
            if (searchQuery.PortalIds.Any()) query.Add(portalIdQuery, Occur.MUST);

            ApplySearchTypeIdFilter(query, searchQuery);

            if (searchQuery.BeginModifiedTimeUtc > DateTime.MinValue && searchQuery.EndModifiedTimeUtc >= searchQuery.BeginModifiedTimeUtc)
            {
                query.Add(NumericRangeQuery.NewLongRange(Constants.ModifiedTimeTag, long.Parse(searchQuery.BeginModifiedTimeUtc.ToString(Constants.DateTimeFormat)), long.Parse(searchQuery.EndModifiedTimeUtc.ToString(Constants.DateTimeFormat)), true, true), Occur.MUST);
            }

            if(searchQuery.RoleId > 0)
                query.Add(NumericRangeQuery.NewIntRange(Constants.RoleIdTag, searchQuery.RoleId, searchQuery.RoleId, true, true), Occur.MUST);  

            foreach (var tag in searchQuery.Tags)
            {
                query.Add(new TermQuery(new Term(Constants.Tag, tag.ToLower())), Occur.MUST);
            }

            if (!string.IsNullOrEmpty(searchQuery.CultureCode))
            {
                var localeQuery = new BooleanQuery();

                var languageId = Localization.Localization.GetCultureLanguageID(searchQuery.CultureCode);
                localeQuery.Add(NumericRangeQuery.NewIntRange(Constants.LocaleTag, languageId, languageId, true, true), Occur.SHOULD);
                localeQuery.Add(NumericRangeQuery.NewIntRange(Constants.LocaleTag, Null.NullInteger, Null.NullInteger, true, true), Occur.SHOULD);
                query.Add(localeQuery, Occur.MUST);
            }



            var luceneQuery = new LuceneQuery
            {
                Query = query,
                Sort = GetSort(searchQuery),
                PageIndex = searchQuery.PageIndex,
                PageSize = searchQuery.PageSize,
                TitleSnippetLength = searchQuery.TitleSnippetLength,
                BodySnippetLength = searchQuery.BodySnippetLength
            };

            return GetSecurityTrimmedResults(searchQuery, luceneQuery);
        }
        private IEnumerable<GroupedDetailView> GetGroupedDetailViews(SearchQuery searchQuery, out int totalHits, out bool more)
        {
            var searchResults = SearchController.Instance.SiteSearch(searchQuery);
            totalHits = searchResults.TotalHits;
            more = searchResults.Results.Count == searchQuery.PageSize;

            var groups = new List<GroupedDetailView>();
            var tabGroups = new Dictionary<string, IList<SearchResult>>();
            var userSearchTypeId = SearchHelper.Instance.GetSearchTypeByName("user").SearchTypeId;
           
            foreach (var result in searchResults.Results)
            {
                //var key = result.TabId + result.Url;
                var key = result.Url;
                if (!tabGroups.ContainsKey(key))
                {
                    tabGroups.Add(key, new List<SearchResult> { result });
                }
                else
                {
                    //when the result is a user search type, we should only show one result
                    // and if duplicate, we should also reduce the totalHit number.
                    if (result.SearchTypeId != userSearchTypeId ||
                        tabGroups[key].All(r => r.Url != result.Url))
                    {
                        tabGroups[key].Add(result);
                    }
                    else
                    {
                        totalHits--;
                    }
                }
            }

            foreach (var results in tabGroups.Values)
            {
                var group = new GroupedDetailView();

                //first entry
                var first = results[0];
                group.Title = first.Title;
                group.DocumentUrl = first.Url;

                //Find a different title for multiple entries with same url
                if (results.Count > 1)
                {
                    if (first.TabId > 0)
                    {
                        var tab = _tabController.GetTab(first.TabId, first.PortalId, false);
                        if (tab != null)
                            group.Title = tab.TabName;
                    }
                    else if (first.ModuleId > 0)
                    {
                        var tabTitle = GetTabTitleFromModuleId(first.ModuleId);
                        if (!string.IsNullOrEmpty(tabTitle))
                        {
                            group.Title = tabTitle;
                        }
                    }
                }
                else if (first.ModuleDefId > 0 && first.ModuleDefId == HtmlModuleDefitionId) //special handling for Html module
                {
                    var tabTitle = GetTabTitleFromModuleId(first.ModuleId);
                    if (!string.IsNullOrEmpty(tabTitle))
                    {
                        group.Title = tabTitle + " > " + first.Title;
                        first.Title = group.Title;
                    }
                }

                foreach (var result in results)
                {
                    var detail = new DetailedView
                    {
                        Title = result.Title,
                        DocumentTypeName = InternalSearchController.Instance.GetSearchDocumentTypeDisplayName(result),
                        DocumentUrl = result.Url,
                        Snippet = result.Snippet,
                        DisplayModifiedTime = result.DisplayModifiedTime,
                        Tags = result.Tags.ToList(),
                        AuthorProfileUrl = result.AuthorUserId > 0 ? Globals.UserProfileURL(result.AuthorUserId) : string.Empty,
                        AuthorName = result.AuthorName
                    };
                    group.Results.Add(detail);
                }

                groups.Add(group);
            }

            return groups;
        }
예제 #18
0
        /// <summary>
        /// This method
        /// </summary>
        /// <param name="channelName"></param>
        /// <param name="userName"></param>
        /// <remarks></remarks>
        protected override void PopulateChannel(string channelName, string userName)
        {
            var objModules = new ModuleController();
            ModuleInfo objModule;
            if (Request == null || Settings == null || Settings.ActiveTab == null || ModuleId == Null.NullInteger)
            {
                return;
            }
            Channel["title"] = Settings.PortalName;
            Channel["link"] = Globals.AddHTTP(Globals.GetDomainName(Request));
            if (!String.IsNullOrEmpty(Settings.Description))
            {
                Channel["description"] = Settings.Description;
            }
            else
            {
                Channel["description"] = Settings.PortalName;
            }
            Channel["language"] = Settings.DefaultLanguage;
            Channel["copyright"] = !string.IsNullOrEmpty(Settings.FooterText) ? Settings.FooterText.Replace("[year]", DateTime.Now.Year.ToString()) : string.Empty;
            Channel["webMaster"] = Settings.Email;
            
            IList<SearchResult> searchResults = null;
            var query = new SearchQuery();
            query.PortalIds = new[] { Settings.PortalId };
            query.TabId = TabId;
            query.ModuleId = ModuleId;
            query.SearchTypeIds = new[] { SearchHelper.Instance.GetSearchTypeByName("module").SearchTypeId };

            try
            {
                searchResults = SearchController.Instance.ModuleSearch(query).Results;
            }
            catch (Exception ex)
            {
                Exceptions.Exceptions.LogException(ex);
            }
            if (searchResults != null)
            {
                foreach (var result in searchResults)
                {
                    if (!result.UniqueKey.StartsWith(Constants.ModuleMetaDataPrefixTag) && TabPermissionController.CanViewPage())
                    {
                        if (Settings.ActiveTab.StartDate < DateTime.Now && Settings.ActiveTab.EndDate > DateTime.Now)
                        {
                            objModule = objModules.GetModule(result.ModuleId, query.TabId);
                            if (objModule != null && objModule.DisplaySyndicate && objModule.IsDeleted == false)
                            {
                                if (ModulePermissionController.CanViewModule(objModule))
                                {
                                    if (Convert.ToDateTime(objModule.StartDate == Null.NullDate ? DateTime.MinValue : objModule.StartDate) < DateTime.Now &&
                                        Convert.ToDateTime(objModule.EndDate == Null.NullDate ? DateTime.MaxValue : objModule.EndDate) > DateTime.Now)
                                    {
                                        Channel.Items.Add(GetRssItem(result));
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        public HttpResponseMessage Preview(string keywords, string culture, int forceWild = 1, int portal = -1)
        {
            string cleanedKeywords;
            keywords = (keywords ?? string.Empty).Trim();
            var tags = SearchQueryStringParser.Instance.GetTags(keywords, out cleanedKeywords);
            var beginModifiedTimeUtc = SearchQueryStringParser.Instance.GetLastModifiedDate(cleanedKeywords, out cleanedKeywords);
            var searchTypes = SearchQueryStringParser.Instance.GetSearchTypeList(keywords, out cleanedKeywords);

            var contentSources = GetSearchContentSources(searchTypes);
            var settings = GetSearchModuleSettings();
            var searchTypeIds = GetSearchTypeIds(settings, contentSources);
            var moduleDefids = GetSearchModuleDefIds(settings, contentSources);
            var portalIds = GetSearchPortalIds(settings, portal);

            var results = new List<GroupedBasicView>();
            if (portalIds.Any() && searchTypeIds.Any() &&
                (!string.IsNullOrEmpty(cleanedKeywords) || tags.Any()))
            {
                var query = new SearchQuery
                {
                    KeyWords = cleanedKeywords,
                    Tags = tags,
                    PortalIds = portalIds,
                    SearchTypeIds = searchTypeIds,
                    ModuleDefIds = moduleDefids,
                    BeginModifiedTimeUtc = beginModifiedTimeUtc,
                    PageIndex = 1,
                    PageSize = 5,
                    TitleSnippetLength = 40,
                    BodySnippetLength = 100,
                    CultureCode = culture,
                    WildCardSearch = forceWild > 0 
                };

                try
                {
                    int totalHists;
                    var previews = GetBasicViews(query, out totalHists);
                    var userSearchTypeId = SearchHelper.Instance.GetSearchTypeByName("user").SearchTypeId;
                    var userSearchSource = contentSources.FirstOrDefault(s => s.SearchTypeId == userSearchTypeId);
                    foreach (var preview in previews)
                    {
                        //if the document type is user, then try to add user pic into preview's custom attributes.
                        if (userSearchSource != null && preview.DocumentTypeName == userSearchSource.LocalizedName)
                        {
                            var match = Regex.Match(preview.DocumentUrl, "userid(/|\\|=)(\\d+)", RegexOptions.IgnoreCase);
                            if (match.Success)
                            {
                                var userid = Convert.ToInt32(match.Groups[2].Value);
                                var user = UserController.GetUserById(PortalSettings.PortalId, userid);
                                if (user != null)
                                {
                                    preview.Attributes.Add("Avatar", user.Profile.PhotoURL);
                                }
                            }
                        }

                        var groupedResult = results.SingleOrDefault(g => g.DocumentTypeName == preview.DocumentTypeName);
                        if (groupedResult != null)
                        {
                            if(!groupedResult.Results.Any(r => string.Equals(r.DocumentUrl, preview.DocumentUrl)))
                            groupedResult.Results.Add(new BasicView
                            {
                                Title = preview.Title,
                                Snippet = preview.Snippet,
                                DocumentUrl = preview.DocumentUrl,
                                Attributes = preview.Attributes
                            });
                        }
                        else
                        {
                            results.Add(new GroupedBasicView(preview));
                        }
                    }
                }
                catch (Exception ex)
                {
                    Services.Exceptions.Exceptions.LogException(ex);
                }
            }

            return Request.CreateResponse(HttpStatusCode.OK, results);
        }
예제 #20
0
        public HttpResponseMessage Preview(string keywords, string culture, int forceWild = 1, int portal = -1)
        {
            string cleanedKeywords;
            keywords = (keywords ?? string.Empty).Trim();
            var tags = GetTags(keywords, out cleanedKeywords);
            var beginModifiedTimeUtc = GetLastModifiedDate(cleanedKeywords, out cleanedKeywords);
            var searchTypes = GetSearchTypeList(keywords, out cleanedKeywords);

            var contentSources = GetSearchContentSources(searchTypes);
            var settings = GetSearchModuleSettings();
            var searchTypeIds = GetSearchTypeIds(settings, contentSources);
            var moduleDefids = GetSearchModuleDefIds(settings, contentSources);
            var portalIds = GetSearchPortalIds(settings, portal);

            var results = new List<GroupedBasicView>();
            if (portalIds.Any() && searchTypeIds.Any() &&
                (!string.IsNullOrEmpty(cleanedKeywords) || tags.Any()))
            {
                var query = new SearchQuery
                {
                    KeyWords = cleanedKeywords,
                    Tags = tags,
                    PortalIds = portalIds,
                    SearchTypeIds = searchTypeIds,
                    ModuleDefIds = moduleDefids,
                    BeginModifiedTimeUtc = beginModifiedTimeUtc,
                    PageIndex = 1,
                    PageSize = 5,
                    TitleSnippetLength = 40,
                    BodySnippetLength = 100,
                    CultureCode = culture,
                    WildCardSearch = forceWild > 0 
                };

                try
                {
                    int totalHists;
                    var previews = GetBasicViews(query, out totalHists);

                    foreach (var preview in previews)
                    {
                        var groupedResult = results.SingleOrDefault(g => g.DocumentTypeName == preview.DocumentTypeName);
                        if (groupedResult != null)
                        {
                            if(!groupedResult.Results.Any(r => string.Equals(r.DocumentUrl, preview.DocumentUrl)))
                            groupedResult.Results.Add(new BasicView
                            {
                                Title = preview.Title,
                                Snippet = preview.Snippet,
                                DocumentUrl = preview.DocumentUrl
                            });
                        }
                        else
                        {
                            results.Add(new GroupedBasicView(preview));
                        }
                    }
                }
                catch (Exception ex)
                {
                    Services.Exceptions.Exceptions.LogException(ex);
                }
            }

            return Request.CreateResponse(HttpStatusCode.OK, results);
        }
예제 #21
0
        private Sort GetSort(SearchQuery query)
        {
            var sort = Sort.RELEVANCE; //default sorting - relevance is always descending.
            if (query.SortField != SortFields.Relevance)
            {
                var reverse = query.SortDirection != SortDirections.Ascending;

                switch (query.SortField)
                {
                    case SortFields.LastModified:
                        sort = new Sort(new SortField(Constants.ModifiedTimeTag, SortField.LONG, reverse));
                        break;
                    case SortFields.Title:
                        sort = new Sort(new SortField(Constants.TitleTag, SortField.STRING, reverse));
                        break;
                    case SortFields.Tag:
                        sort = new Sort(new SortField(Constants.Tag, SortField.STRING, reverse));
                        break;
                    case SortFields.NumericKey:
                        sort = new Sort(new SortField(Constants.NumericKeyPrefixTag + query.CustomSortField, SortField.INT, reverse));
                        break;
                    case SortFields.Keyword:
                        sort = new Sort(new SortField(Constants.KeywordsPrefixTag + query.CustomSortField, SortField.STRING, reverse));
                        break;
                    case SortFields.CustomStringField:
                        sort = new Sort(new SortField(query.CustomSortField, SortField.STRING, reverse));
                        break;
                    case SortFields.CustomNumericField:
                        sort = new Sort(new SortField(query.CustomSortField, SortField.INT, reverse));
                        break;
                    default:
                        sort = Sort.RELEVANCE;
                        break;
                }
            }

            return sort;
        }
        public void ModifyingDocumentsDoesNotCreateDuplicates()
        {
            //Arrange
            const string tabUrl = "mysite/ContentUrl";
            const string title = "content title";
            const string contentBody = "content body";
            const string titleModified = title + " modified";
            var uniqueKey = Guid.NewGuid().ToString();
            var now = DateTime.UtcNow;

            var originalDocument = new SearchDocument
            {
                UniqueKey = uniqueKey,
                TabId = TabId1,
                Url = tabUrl,
                Title = title,
                Body = contentBody,
                SearchTypeId = TabSearchTypeId,
                ModifiedTimeUtc = now,
                PortalId = PortalId0,
                RoleId = RoleId731,
                Keywords = { { "description", "mycontent" } },
                NumericKeys = { {"points", 5} }
            };

            _internalSearchController.AddSearchDocument(originalDocument);
            _internalSearchController.Commit();

            var modifiedDocument = new SearchDocument
            {
                UniqueKey = uniqueKey,
                TabId = TabId1,
                Url = tabUrl,
                Title = titleModified,
                Body = contentBody + " modified",
                SearchTypeId = TabSearchTypeId,
                ModifiedTimeUtc = now,
                PortalId = PortalId0,
                RoleId = RoleId731,
                Keywords = { { "description", "mycontent_modified" }, { "description2", "mycontent_modified" } },
                NumericKeys = { { "points", 8 }, {"point2", 7 } }
            };

            _internalSearchController.AddSearchDocument(modifiedDocument);
            _internalSearchController.Commit();

            var query = new SearchQuery
            {
                KeyWords = title,
                PortalIds = new List<int> { PortalId0 },
                SearchTypeIds = new[] { ModuleSearchTypeId, TabSearchTypeId, UserSearchTypeId },
                BeginModifiedTimeUtc = now.AddMinutes(-1),
                EndModifiedTimeUtc = now.AddMinutes(+1),
                PageIndex = 1,
                PageSize = 15,
                SortField = 0,
                TitleSnippetLength = 120,
                BodySnippetLength = 300,
                WildCardSearch = true
            };

            //Run 
            var searchResults = GetGroupedDetailViewResults(query).ToList();

            //Assert
            Assert.AreEqual(1, searchResults.Count());
            Assert.AreEqual(1, searchResults.First().Results.Count);
            Assert.AreEqual(tabUrl, searchResults.First().Results.First().DocumentUrl);
            Assert.AreEqual(titleModified, searchResults.First().Results.First().Title);
        }