protected void btnSearch_Click(object sender, EventArgs e)
        {
            txtPageName.Text = txtPageName.Text.Trim();

            if (txtPageName.Text.Length == 0)
            {
                lstAvailablePage.Items.Clear();
                btnAdd.Enabled = false;
                return;
            }

            List <SearchResult> similarPages = SearchClass.Search(new SearchField[] { SearchField.PageFullName }, txtPageName.Text, SearchOptions.AtLeastOneWord);

            lstAvailablePage.Items.Clear();

            foreach (SearchResult page in similarPages)
            {
                if (page.DocumentType == DocumentType.Page)
                {
                    PageDocument pageDocument = page.Document as PageDocument;
                    PageInfo     pageInfo     = Pages.FindPage(pageDocument.PageFullName);
                    lstAvailablePage.Items.Add(new ListItem(FormattingPipeline.PrepareTitle(pageDocument.Title, false, FormattingContext.Other, pageInfo), pageDocument.PageFullName));
                }
            }

            btnAdd.Enabled = lstAvailablePage.Items.Count > 0;
        }
Beispiel #2
0
        /// <summary>
        /// Prints the results of the automatic search.
        /// </summary>
        public void PrintSearchResults()
        {
            StringBuilder sb = new StringBuilder(1000);

            List <SearchResult> similarPages = SearchClass.Search(new SearchField[] { SearchField.PageFullName }, Request["Page"], SearchOptions.AtLeastOneWord);

            List <PageInfo> results = new List <PageInfo>();

            foreach (SearchResult page in similarPages)
            {
                if (page.DocumentType == DocumentType.Page)
                {
                    PageDocument pageDocument = page.Document as PageDocument;
                    PageInfo     pageInfo     = Pages.FindPage(pageDocument.PageFullName);
                    results.Add(pageInfo);
                }
            }
            if (results.Count > 0)
            {
                sb.Append("<p>");
                sb.Append(Properties.Messages.WereYouLookingFor);
                sb.Append("</p>");
                sb.Append("<ul>");
                PageContent c;
                for (int i = 0; i < results.Count; i++)
                {
                    c = Content.GetPageContent(results[i], true);
                    sb.Append(@"<li><a href=""");
                    UrlTools.BuildUrl(sb, Tools.UrlEncode(results[i].FullName), Settings.PageExtension);
                    sb.Append(@""">");
                    sb.Append(FormattingPipeline.PrepareTitle(c.Title, false, FormattingContext.PageContent, c.PageInfo));
                    sb.Append("</a></li>");
                }
                sb.Append("</ul>");
            }
            else
            {
                sb.Append("<p>");
                sb.Append(Properties.Messages.NoSimilarPages);
                sb.Append("</p>");
            }
            sb.Append(@"<br /><p>");
            sb.Append(Properties.Messages.YouCanAlso);
            sb.Append(@" <a href=""");
            UrlTools.BuildUrl(sb, "Search.aspx?Query=", Tools.UrlEncode(Request["Page"]));
            sb.Append(@""">");
            sb.Append(Properties.Messages.PerformASearch);
            sb.Append("</a> ");
            sb.Append(Properties.Messages.Or);
            sb.Append(@" <a href=""");
            UrlTools.BuildUrl(sb, "Edit.aspx?Page=", Tools.UrlEncode(Request["Page"]));
            sb.Append(@"""><b>");
            sb.Append(Properties.Messages.CreateThePage);
            sb.Append("</b></a> (");
            sb.Append(Properties.Messages.CouldRequireLogin);
            sb.Append(").</p>");

            lblSearchResults.Text = sb.ToString();
        }
Beispiel #3
0
        /// <summary>
        /// Creates a new instance of the <see cref="T:SearchResultRow" /> class.
        /// </summary>
        /// <param name="result">The result to use.</param>
        /// <returns>The instance.</returns>
        public static SearchResultRow CreateInstance(SearchResult result)
        {
            //string queryStringKeywords = "HL=" + GetKeywordsForQueryString(result.Matches);
            string queryStringKeywords = "HL=" + HttpContext.Current.Request.QueryString["Query"].Replace(" ", ",");

            if (result.DocumentType == DocumentType.Page)
            {
                PageDocument doc      = result.Document as PageDocument;
                PageInfo     pageInfo = Pages.FindPage(doc.PageFullName);
                return(new SearchResultRow(doc.PageFullName + Settings.PageExtension + "?" + queryStringKeywords, Page,
                                           FormattingPipeline.PrepareTitle(doc.Title, false, FormattingContext.PageContent, pageInfo), result.Relevance,
                                           string.IsNullOrEmpty(doc.HighlightedContent) ? doc.Content : doc.HighlightedContent));
            }
            else if (result.DocumentType == DocumentType.Message)
            {
                MessageDocument doc      = result.Document as MessageDocument;
                PageInfo        pageInfo = Pages.FindPage(doc.PageFullName);
                PageContent     content  = Cache.GetPageContent(pageInfo);
                if (content == null)
                {
                    content = Content.GetPageContent(pageInfo, false);
                }

                return(new SearchResultRow(content.FullName + Settings.PageExtension + "?" + queryStringKeywords + "&amp;Discuss=1#" + Tools.GetMessageIdForAnchor(doc.DateTime), Message,
                                           FormattingPipeline.PrepareTitle(doc.Subject, false, FormattingContext.MessageBody, pageInfo) + " (" +
                                           FormattingPipeline.PrepareTitle(content.Title, false, FormattingContext.MessageBody, content.PageInfo) +
                                           ")", result.Relevance, doc.HighlightedBody));
            }
            else if (result.DocumentType == DocumentType.File)
            {
                FileDocument fileDoc = result.Document as FileDocument;

                string[] fileParts = fileDoc.FileName.Split(new char[] { '|' });

                return(new SearchResultRow("GetFile.aspx?File=" + Tools.UrlEncode(fileDoc.FileName.Substring(fileParts[0].Length + 1)) +
                                           "&amp;Provider=" + Tools.UrlEncode(fileParts[0]),
                                           File, fileParts[1], result.Relevance, fileDoc.HighlightedFileContent));
            }
            else if (result.DocumentType == DocumentType.Attachment)
            {
                PageAttachmentDocument attnDoc = result.Document as PageAttachmentDocument;
                PageInfo    pageInfo           = Pages.FindPage(attnDoc.PageFullName);
                PageContent content            = Cache.GetPageContent(pageInfo);
                if (content == null)
                {
                    content = Content.GetPageContent(pageInfo, false);
                }

                return(new SearchResultRow(content.FullName + Settings.PageExtension, Attachment,
                                           attnDoc.FileName + " (" +
                                           FormattingPipeline.PrepareTitle(content.Title, false, FormattingContext.PageContent, content.PageInfo) +
                                           ")", result.Relevance, attnDoc.HighlightedFileContent));
            }
            else
            {
                throw new NotSupportedException();
            }
        }
        protected void btnSearch_Click(object sender, EventArgs e)
        {
            lstAvailablePage.Items.Clear();
            btnAddPage.Enabled = false;

            txtPageName.Text = txtPageName.Text.Trim();

            if (txtPageName.Text.Length == 0)
            {
                return;
            }

            List <SearchResult> similarPages = SearchClass.Search(new SearchField[] { SearchField.PageFullName }, txtPageName.Text, SearchOptions.AtLeastOneWord);

            List <PageInfo> pages = new List <PageInfo>();

            foreach (SearchResult page in similarPages)
            {
                if (page.DocumentType == DocumentType.Page)
                {
                    PageDocument pageDocument = page.Document as PageDocument;
                    PageInfo     pageInfo     = Pages.FindPage(pageDocument.PageFullName);
                    pages.Add(pageInfo);
                }
            }

            string cp = CurrentProvider;

            foreach (PageInfo page in
                     from p in pages
                     where p.Provider.GetType().FullName == cp
                     select p)
            {
                // Filter pages already in the list
                bool found = false;
                foreach (ListItem item in lstPages.Items)
                {
                    if (item.Value == page.FullName)
                    {
                        found = true;
                        break;
                    }
                }

                if (!found)
                {
                    PageContent content = Content.GetPageContent(page, false);
                    lstAvailablePage.Items.Add(new ListItem(FormattingPipeline.PrepareTitle(content.Title, false, FormattingContext.Other, page), page.FullName));
                }
            }

            btnAddPage.Enabled = lstAvailablePage.Items.Count > 0;
        }
Beispiel #5
0
        /// <summary>
        /// Searches for pages with name or title similar to a specified value.
        /// </summary>
        /// <param name="name">The name to look for (<c>null</c> for the root).</param>
        /// <param name="nspace">The namespace to search into.</param>
        /// <returns>The similar pages, if any.</returns>
        public static PageInfo[] SearchSimilarPages(string name, string nspace)
        {
            if (string.IsNullOrEmpty(nspace))
            {
                nspace = null;
            }

            SearchResultCollection searchResults = Search(name, false, false, SearchOptions.AtLeastOneWord);

            List <PageInfo> result = new List <PageInfo>(20);

            foreach (SearchResult res in searchResults)
            {
                PageDocument pageDoc = res.Document as PageDocument;
                if (pageDoc != null)
                {
                    string pageNamespace = NameTools.GetNamespace(pageDoc.PageInfo.FullName);
                    if (string.IsNullOrEmpty(pageNamespace))
                    {
                        pageNamespace = null;
                    }

                    if (pageNamespace == nspace)
                    {
                        result.Add(pageDoc.PageInfo);
                    }
                }
            }

            // Search page names for matches
            List <PageInfo>  allPages    = Pages.GetPages(Pages.FindNamespace(nspace));
            PageNameComparer comp        = new PageNameComparer( );
            string           currentName = name.ToLowerInvariant( );

            foreach (PageInfo page in allPages)
            {
                if (NameTools.GetLocalName(page.FullName).ToLowerInvariant( ).Contains(currentName))
                {
                    if (result.Find(delegate(PageInfo p) { return(comp.Compare(p, page) == 0); }) == null)
                    {
                        result.Add(page);
                    }
                }
            }

            return(result.ToArray( ));
        }
Beispiel #6
0
        /// <summary>
        /// Creates a new instance of the <see cref="T:SearchResultRow" /> class.
        /// </summary>
        /// <param name="result">The result to use.</param>
        /// <returns>The instance.</returns>
        public static SearchResultRow CreateInstance(SearchResult result)
        {
            string queryStringKeywords = "HL=" + GetKeywordsForQueryString(result.Matches);

            if (result.Document.TypeTag == PageDocument.StandardTypeTag)
            {
                PageDocument pageDoc = result.Document as PageDocument;

                return(new SearchResultRow(pageDoc.PageInfo.FullName + Settings.PageExtension + "?" + queryStringKeywords, Page,
                                           FormattingPipeline.PrepareTitle(pageDoc.Title, false, FormattingContext.PageContent, pageDoc.PageInfo),
                                           result.Relevance.Value, GetExcerpt(pageDoc.PageInfo, result.Matches)));
            }
            else if (result.Document.TypeTag == MessageDocument.StandardTypeTag)
            {
                MessageDocument msgDoc = result.Document as MessageDocument;

                PageContent content = Content.GetPageContent(msgDoc.PageInfo, true);

                return(new SearchResultRow(msgDoc.PageInfo.FullName + Settings.PageExtension + "?" + queryStringKeywords + "&amp;Discuss=1#" + Tools.GetMessageIdForAnchor(msgDoc.DateTime), Message,
                                           FormattingPipeline.PrepareTitle(msgDoc.Title, false, FormattingContext.MessageBody, content.PageInfo) + " (" +
                                           FormattingPipeline.PrepareTitle(content.Title, false, FormattingContext.MessageBody, content.PageInfo) +
                                           ")", result.Relevance.Value, GetExcerpt(msgDoc.PageInfo, msgDoc.MessageID, result.Matches)));
            }
            else if (result.Document.TypeTag == FileDocument.StandardTypeTag)
            {
                FileDocument fileDoc = result.Document as FileDocument;

                return(new SearchResultRow("GetFile.aspx?File=" + Tools.UrlEncode(fileDoc.Name.Substring(fileDoc.Provider.Length + 1)) +
                                           "&amp;Provider=" + Tools.UrlEncode(fileDoc.Provider),
                                           File, fileDoc.Title, result.Relevance.Value, ""));
            }
            else if (result.Document.TypeTag == PageAttachmentDocument.StandardTypeTag)
            {
                PageAttachmentDocument attnDoc = result.Document as PageAttachmentDocument;
                PageContent            content = Content.GetPageContent(attnDoc.Page, false);

                return(new SearchResultRow(attnDoc.Page.FullName + Settings.PageExtension, Attachment,
                                           attnDoc.Title + " (" +
                                           FormattingPipeline.PrepareTitle(content.Title, false, FormattingContext.PageContent, content.PageInfo) +
                                           ")", result.Relevance.Value, ""));
            }
            else
            {
                throw new NotSupportedException();
            }
        }
Beispiel #7
0
        /// <summary>
        /// Searches the specified phrase in the specified search fields.
        /// </summary>
        /// <param name="searchFields">The search fields.</param>
        /// <param name="phrase">The phrase to search.</param>
        /// <param name="searchOption">The search options.</param>
        /// <returns>A list of <see cref="SearchResult"/> items.</returns>
        public static List <SearchResult> Search(SearchField[] searchFields, string phrase, SearchOptions searchOption)
        {
            IIndexDirectoryProviderV30 indexDirectoryProvider = Collectors.IndexDirectoryProvider;
            Analyzer analyzer = new SimpleAnalyzer();

            using (IndexSearcher searcher = new IndexSearcher(indexDirectoryProvider.GetDirectory(), false))
            {
                string[] searchFieldsAsString     = (from f in searchFields select f.AsString()).ToArray();
                MultiFieldQueryParser queryParser = new MultiFieldQueryParser(Lucene.Net.Util.Version.LUCENE_29, searchFieldsAsString, analyzer);

                if (searchOption == SearchOptions.AllWords)
                {
                    queryParser.DefaultOperator = QueryParser.Operator.AND;
                }

                if (searchOption == SearchOptions.AtLeastOneWord)
                {
                    queryParser.DefaultOperator = QueryParser.Operator.OR;
                }

                try
                {
                    Query   query   = queryParser.Parse(phrase);
                    TopDocs topDocs = searcher.Search(query, 100);

                    Highlighter highlighter = new Highlighter(new SimpleHTMLFormatter("<b class=\"searchkeyword\">", "</b>"), new QueryScorer(query));

                    List <SearchResult> searchResults = new List <SearchResult>(topDocs.TotalHits);
                    for (int i = 0; i < Math.Min(100, topDocs.TotalHits); i++)
                    {
                        Document doc = searcher.Doc(topDocs.ScoreDocs[i].Doc);

                        SearchResult result = new SearchResult();
                        result.DocumentType = DocumentTypeFromString(doc.GetField(SearchField.DocumentType.AsString()).StringValue);
                        result.Relevance    = topDocs.ScoreDocs[i].Score * 100;
                        switch (result.DocumentType)
                        {
                        case DocumentType.Page:
                            PageDocument page = new PageDocument();
                            page.PageFullName = doc.GetField(SearchField.PageFullName.AsString()).StringValue;
                            page.Title        = doc.GetField(SearchField.Title.AsString()).StringValue;

                            TokenStream tokenStream1 = analyzer.TokenStream(SearchField.Title.AsString(), new StringReader(page.Title));
                            page.HighlightedTitle = highlighter.GetBestFragments(tokenStream1, page.Title, 3, " [...] ");

                            page.Content = doc.GetField(SearchField.Content.AsString()).StringValue;

                            tokenStream1            = analyzer.TokenStream(SearchField.Content.AsString(), new StringReader(page.Content));
                            page.HighlightedContent = highlighter.GetBestFragments(tokenStream1, page.Content, 3, " [...] ");

                            result.Document = page;
                            break;

                        case DocumentType.Message:
                            MessageDocument message = new MessageDocument();
                            message.PageFullName = doc.GetField(SearchField.PageFullName.AsString()).StringValue;
                            message.DateTime     = DateTime.Parse(doc.GetField(SearchField.MessageDateTime.AsString()).StringValue);
                            message.Subject      = doc.GetField(SearchField.Title.AsString()).StringValue;
                            message.Body         = doc.GetField(SearchField.Content.AsString()).StringValue;

                            TokenStream tokenStream2 = analyzer.TokenStream(SearchField.Content.AsString(), new StringReader(message.Body));
                            message.HighlightedBody = highlighter.GetBestFragments(tokenStream2, message.Body, 3, " [...] ");

                            result.Document = message;
                            break;

                        case DocumentType.Attachment:
                            PageAttachmentDocument attachment = new PageAttachmentDocument();
                            attachment.PageFullName = doc.GetField(SearchField.PageFullName.AsString()).StringValue;
                            attachment.FileName     = doc.GetField(SearchField.FileName.AsString()).StringValue;
                            attachment.FileContent  = doc.GetField(SearchField.FileContent.AsString()).StringValue;

                            TokenStream tokenStream3 = analyzer.TokenStream(SearchField.Content.AsString(), new StringReader(attachment.FileContent));
                            attachment.HighlightedFileContent = highlighter.GetBestFragments(tokenStream3, attachment.FileContent, 3, " [...] ");

                            result.Document = attachment;
                            break;

                        case DocumentType.File:
                            FileDocument file = new FileDocument();
                            file.FileName    = doc.GetField(SearchField.FileName.AsString()).StringValue;
                            file.FileContent = doc.GetField(SearchField.FileContent.AsString()).StringValue;

                            TokenStream tokenStream4 = analyzer.TokenStream(SearchField.Content.AsString(), new StringReader(file.FileContent));
                            file.HighlightedFileContent = highlighter.GetBestFragments(tokenStream4, file.FileContent, 3, " [...]");

                            result.Document = file;
                            break;

                        case DocumentType.SourceControlFile:
                            FileDocument scfile = new FileDocument();
                            scfile.FileName    = doc.GetField(SearchField.FileName.AsString()).StringValue;
                            scfile.FileContent = doc.GetField(SearchField.FileContent.AsString()).StringValue;

                            TokenStream tokenStream5 = analyzer.TokenStream(SearchField.Content.AsString(), new StringReader(scfile.FileContent));
                            scfile.HighlightedFileContent = highlighter.GetBestFragments(tokenStream5, scfile.FileContent, 3, " [...]");

                            result.Document = scfile;
                            break;
                        }

                        searchResults.Add(result);
                    }
                    return(searchResults);
                }
                catch (ParseException)
                {
                    return(new List <SearchResult>(0));
                }
            }
        }
Beispiel #8
0
        /// <summary>
        /// Performs a search.
        /// </summary>
        /// <param name="query">The search query.</param>
        /// <param name="mode">The search mode.</param>
        /// <param name="selectedCategories">The selected categories.</param>
        /// <param name="searchUncategorized">A value indicating whether to search uncategorized pages.</param>
        /// <param name="searchInAllNamespacesAndCategories">A value indicating whether to search in all namespaces and categories.</param>
        /// <param name="searchFilesAndAttachments">A value indicating whether to search files and attachments.</param>
        private void PerformSearch(string query, SearchOptions mode, List <string> selectedCategories, bool searchUncategorized, bool searchInAllNamespacesAndCategories, bool searchFilesAndAttachments)
        {
            List <SearchResult> results = null;
            DateTime            begin   = DateTime.Now;

            try {
                List <SearchField> searchFields = new List <SearchField>(2)
                {
                    SearchField.Title, SearchField.Content
                };
                if (searchFilesAndAttachments)
                {
                    searchFields.AddRange(new SearchField[] { SearchField.FileName, SearchField.FileContent });
                }
                results = SearchClass.Search(currentWiki, searchFields.ToArray(), query, mode);
            }
            catch (ArgumentException ex) {
                Log.LogEntry("Search threw an exception\n" + ex.ToString(), EntryType.Warning, SessionFacade.CurrentUsername, currentWiki);
                results = new List <SearchResult>();
            }
            DateTime end = DateTime.Now;

            // Build a list of SearchResultRow for display in the repeater
            List <SearchResultRow> rows = new List <SearchResultRow>(Math.Min(results.Count, MaxResults));

            string currentUser = SessionFacade.GetCurrentUsername();

            string[] currentGroups = SessionFacade.GetCurrentGroupNames(currentWiki);

            AuthChecker authChecker = new AuthChecker(Collectors.CollectorsBox.GetSettingsProvider(currentWiki));

            CategoryInfo[] pageCategories;
            int            count = 0;

            foreach (SearchResult res in results)
            {
                // Filter by category
                PageContent currentPage = null;
                pageCategories = new CategoryInfo[0];

                if (res.DocumentType == DocumentType.Page)
                {
                    PageDocument doc = res.Document as PageDocument;
                    currentPage    = Pages.FindPage(doc.Wiki, doc.PageFullName);
                    pageCategories = Pages.GetCategoriesForPage(currentPage);

                    // Verify permissions
                    bool canReadPage = authChecker.CheckActionForPage(currentPage.FullName,
                                                                      Actions.ForPages.ReadPage, currentUser, currentGroups);
                    if (!canReadPage)
                    {
                        continue;                                  // Skip
                    }
                }
                else if (res.DocumentType == DocumentType.Message)
                {
                    MessageDocument doc = res.Document as MessageDocument;
                    currentPage    = Pages.FindPage(doc.Wiki, doc.PageFullName);
                    pageCategories = Pages.GetCategoriesForPage(currentPage);

                    // Verify permissions
                    bool canReadDiscussion = authChecker.CheckActionForPage(currentPage.FullName,
                                                                            Actions.ForPages.ReadDiscussion, currentUser, currentGroups);
                    if (!canReadDiscussion)
                    {
                        continue;                                        // Skip
                    }
                }
                else if (res.DocumentType == DocumentType.Attachment)
                {
                    PageAttachmentDocument doc = res.Document as PageAttachmentDocument;
                    currentPage    = Pages.FindPage(doc.Wiki, doc.PageFullName);
                    pageCategories = Pages.GetCategoriesForPage(currentPage);

                    // Verify permissions
                    bool canDownloadAttn = authChecker.CheckActionForPage(currentPage.FullName,
                                                                          Actions.ForPages.DownloadAttachments, currentUser, currentGroups);
                    if (!canDownloadAttn)
                    {
                        continue;                                      // Skip
                    }
                }
                else if (res.DocumentType == DocumentType.File)
                {
                    FileDocument             doc      = res.Document as FileDocument;
                    string[]                 fields   = doc.FileName.Split('|');
                    IFilesStorageProviderV40 provider = Collectors.CollectorsBox.FilesProviderCollector.GetProvider(fields[0], currentWiki);
                    string directory = Tools.GetDirectoryName(fields[1]);

                    // Verify permissions
                    bool canDownloadFiles = authChecker.CheckActionForDirectory(provider, directory,
                                                                                Actions.ForDirectories.DownloadFiles, currentUser, currentGroups);
                    if (!canDownloadFiles)
                    {
                        continue;                                       // Skip
                    }
                }

                string currentNamespace = DetectNamespace();
                if (string.IsNullOrEmpty(currentNamespace))
                {
                    currentNamespace = null;
                }

                if (currentPage != null)
                {
                    // Check categories match, if page is set

                    if (searchInAllNamespacesAndCategories ||
                        Array.Find(pageCategories,
                                   delegate(CategoryInfo c) {
                        return(selectedCategories.Contains(c.FullName));
                    }) != null || pageCategories.Length == 0 && searchUncategorized)
                    {
                        // ... then namespace
                        if (searchInAllNamespacesAndCategories ||
                            NameTools.GetNamespace(currentPage.FullName) == currentNamespace)
                        {
                            rows.Add(SearchResultRow.CreateInstance(res));
                            count++;
                        }
                    }
                }
                else
                {
                    // No associated page (-> file), add result
                    rows.Add(SearchResultRow.CreateInstance(res));
                    count++;
                }

                if (count >= MaxResults)
                {
                    break;
                }
            }

            rptResults.DataSource = rows;
            rptResults.DataBind();
        }