/// <summary> /// Deletes and de-indexes a file. /// </summary> /// <param name="provider">The provider.</param> /// <param name="fullName">The full name of the file to delete.</param> /// <returns><c>true</c> if the file was deleted, <c>false</c> otherwise.</returns> public static bool DeleteFile(IFilesStorageProviderV40 provider, string fullName) { if (provider == null) { throw new ArgumentNullException("provider"); } if (fullName == null) { throw new ArgumentNullException("fullName"); } if (fullName.Length == 0) { throw new ArgumentException("Full Name cannot be empty", "fullName"); } fullName = NormalizeFullName(fullName); bool done = provider.DeleteFile(fullName); if (!done) { return(false); } SearchClass.UnindexFile(provider.GetType().FullName + "|" + fullName, provider.CurrentWiki); Host.Instance.OnFileActivity(provider.GetType().FullName, fullName, null, FileActivity.FileDeleted); return(true); }
/// <summary> /// Recursively re-indexes all the contents of the old (renamed) directory to the new one. /// </summary> /// <param name="provider">The provider.</param> /// <param name="oldDirectory">The old directory.</param> /// <param name="newDirectory">The new directory.</param> private static void ReindexDirectory(IFilesStorageProviderV30 provider, string oldDirectory, string newDirectory) { oldDirectory = NormalizeFullPath(oldDirectory); newDirectory = NormalizeFullPath(newDirectory); // At this point the directory has been already renamed, // thus we must list on the new directory and construct the old name // Example: /directory/one/ renamed to /directory/two-two/ // List on /directory/two-two/ // dir1 // dir2 // oldSub = /directory/one/dir1/ foreach (string sub in provider.ListDirectories(newDirectory)) { string oldSub = oldDirectory + sub.Substring(newDirectory.Length); ReindexDirectory(provider, oldSub, sub); } foreach (string file in provider.ListFiles(newDirectory)) { string oldFile = oldDirectory + file.Substring(newDirectory.Length); SearchClass.RenameFile(provider.GetType().FullName + "|" + oldFile, provider.GetType().FullName + "|" + file); } }
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; }
/// <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(); }
/// <summary> /// Stores and indexes a file. /// </summary> /// <param name="provider">The destination provider.</param> /// <param name="fullName">The full name.</param> /// <param name="source">The source stream.</param> /// <param name="overwrite"><c>true</c> to overwrite the existing file, <c>false</c> otherwise.</param> /// <returns><c>true</c> if the file was stored, <c>false</c> otherwise.</returns> public static bool StoreFile(IFilesStorageProviderV30 provider, string fullName, Stream source, bool overwrite) { if (provider == null) { throw new ArgumentNullException("provider"); } if (fullName == null) { throw new ArgumentNullException("fullName"); } if (fullName.Length == 0) { throw new ArgumentException("Full Name cannot be empty", "fullName"); } if (source == null) { throw new ArgumentNullException("source"); } fullName = NormalizeFullName(fullName); bool done = provider.StoreFile(fullName, source, overwrite); if (!done) { return(false); } if (overwrite) { SearchClass.UnindexFile(provider.GetType().FullName + "|" + fullName); } // Index the attached file string tempDir = Path.Combine(Environment.GetEnvironmentVariable("TEMP"), Guid.NewGuid().ToString()); if (!Directory.Exists(tempDir)) { Directory.CreateDirectory(tempDir); } string tempFile = Path.Combine(tempDir, Path.GetFileName(fullName)); source.Seek(0, SeekOrigin.Begin); using (FileStream temp = File.Create(tempFile)) { source.CopyTo(temp); } SearchClass.IndexFile(provider.GetType().FullName + "|" + fullName, tempFile); Directory.Delete(tempDir, true); Host.Instance.OnFileActivity(provider.GetType().FullName, fullName, null, FileActivity.FileUploaded); return(true); }
/// <summary> /// Renames and re-indexes a page attachment. /// </summary> /// <param name="provider">The provider.</param> /// <param name="pageFullName">The page full name.</param> /// <param name="name">The attachment name.</param> /// <param name="newName">The new attachment name.</param> /// <returns><c>true</c> if the attachment was rename, <c>false</c> otherwise.</returns> public static bool RenamePageAttachment(IFilesStorageProviderV40 provider, string pageFullName, string name, string newName) { if (provider == null) { throw new ArgumentNullException("provider"); } if (pageFullName == null) { throw new ArgumentNullException("pageFullName"); } if (pageFullName.Length == 0) { throw new ArgumentException("Page Full Name cannot be empty", "pageFullName"); } if (name == null) { throw new ArgumentNullException("name"); } if (name.Length == 0) { throw new ArgumentException("Name cannot be empty", "name"); } if (newName == null) { throw new ArgumentNullException("newName"); } if (newName.Length == 0) { throw new ArgumentException("New Name cannot be empty", "newName"); } if (name.ToLowerInvariant() == newName.ToLowerInvariant()) { return(false); } PageContent page = Pages.FindPage(provider.CurrentWiki, pageFullName); if (page == null) { return(false); } bool done = provider.RenamePageAttachment(pageFullName, name, newName); if (!done) { return(false); } SearchClass.RenamePageAttachment(page, name, newName); Host.Instance.OnAttachmentActivity(provider.GetType().FullName, newName, pageFullName, name, FileActivity.AttachmentRenamed); return(true); }
/// <summary> /// Deletes and de-indexes a page attachment. /// </summary> /// <param name="provider">The provider.</param> /// <param name="pageFullName">The page full name.</param> /// <param name="name">The attachment name.</param> /// <returns><c>true</c> if the attachment was deleted, <c>false</c> otherwise.</returns> public static bool DeletePageAttachment(IFilesStorageProviderV30 provider, string pageFullName, string name) { if (provider == null) { throw new ArgumentNullException("provider"); } if (pageFullName == null) { throw new ArgumentNullException("pageFullName"); } if (pageFullName.Length == 0) { throw new ArgumentException("Page Full Name cannot be empty", "pageFullName"); } if (name == null) { throw new ArgumentNullException("name"); } if (name.Length == 0) { throw new ArgumentException("Name cannot be empty", "name"); } PageInfo pageInfo = Pages.FindPage(pageFullName); if (pageInfo == null) { return(false); } PageContent page = Content.GetPageContent(pageInfo, false); if (page == null) { return(false); } bool done = provider.DeletePageAttachment(pageInfo, name); if (!done) { return(false); } SearchClass.UnindexPageAttachment(name, page); Host.Instance.OnAttachmentActivity(provider.GetType().FullName, name, pageFullName, null, FileActivity.AttachmentDeleted); return(true); }
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; }
/// <summary> /// De-indexes all contents of a directory. /// </summary> /// <param name="provider">The provider.</param> /// <param name="directory">The directory.</param> private static void DeindexDirectory(IFilesStorageProviderV30 provider, string directory) { directory = NormalizeFullPath(directory); foreach (string sub in provider.ListDirectories(directory)) { DeindexDirectory(provider, sub); } foreach (string file in provider.ListFiles(directory)) { SearchClass.UnindexFile(provider.GetType().FullName + "|" + file); } }
/// <summary> /// Renames and re-indexes a file. /// </summary> /// <param name="provider">The provider.</param> /// <param name="fullName">The full name of the file to rename.</param> /// <param name="newName">The new name of the file (without namespace).</param> /// <returns><c>true</c> if the file was renamed, <c>false</c> otherwise.</returns> public static bool RenameFile(IFilesStorageProviderV30 provider, string fullName, string newName) { if (provider == null) { throw new ArgumentNullException("provider"); } if (fullName == null) { throw new ArgumentNullException("fullName"); } if (fullName.Length == 0) { throw new ArgumentException("Full Name cannot be empty", "fullName"); } if (newName == null) { throw new ArgumentNullException("newName"); } if (newName.Length == 0) { throw new ArgumentException("New Name cannot be empty", "newName"); } fullName = NormalizeFullName(fullName); string newFullName = GetDirectory(fullName) + newName; newFullName = NormalizeFullName(newFullName); if (newFullName.ToLowerInvariant() == fullName.ToLowerInvariant()) { return(false); } bool done = provider.RenameFile(fullName, newFullName); if (!done) { return(false); } SearchClass.RenameFile(provider.GetType().FullName + "|" + fullName, provider.GetType().FullName + "|" + newFullName); Host.Instance.OnFileActivity(provider.GetType().FullName, fullName, newFullName, FileActivity.FileRenamed); return(true); }
/// <summary> /// Performs all needed startup operations. /// </summary> public static void Startup() { // Load Host Host.Instance = new Host(); // Load config ISettingsStorageProviderV30 ssp = ProviderLoader.LoadSettingsStorageProvider(WebConfigurationManager.AppSettings["SettingsStorageProvider"]); ssp.Init(Host.Instance, GetSettingsStorageProviderConfiguration()); Collectors.SettingsProvider = ssp; if (!(ssp is SettingsStorageProvider)) { // Update DLLs from public\Plugins UpdateDllsIntoSettingsProvider(ssp, ProviderLoader.SettingsStorageProviderAssemblyName); } if (ssp.IsFirstApplicationStart()) { if (ssp.GetMetaDataItem(MetaDataItem.AccountActivationMessage, null) == "") { ssp.SetMetaDataItem(MetaDataItem.AccountActivationMessage, null, Defaults.AccountActivationMessageContent); } if (ssp.GetMetaDataItem(MetaDataItem.EditNotice, null) == "") { ssp.SetMetaDataItem(MetaDataItem.EditNotice, null, Defaults.EditNoticeContent); } if (ssp.GetMetaDataItem(MetaDataItem.Footer, null) == "") { ssp.SetMetaDataItem(MetaDataItem.Footer, null, Defaults.FooterContent); } if (ssp.GetMetaDataItem(MetaDataItem.Header, null) == "") { ssp.SetMetaDataItem(MetaDataItem.Header, null, Defaults.HeaderContent); } if (ssp.GetMetaDataItem(MetaDataItem.PasswordResetProcedureMessage, null) == "") { ssp.SetMetaDataItem(MetaDataItem.PasswordResetProcedureMessage, null, Defaults.PasswordResetProcedureMessageContent); } if (ssp.GetMetaDataItem(MetaDataItem.Sidebar, null) == "") { ssp.SetMetaDataItem(MetaDataItem.Sidebar, null, Defaults.SidebarContent); } if (ssp.GetMetaDataItem(MetaDataItem.PageChangeMessage, null) == "") { ssp.SetMetaDataItem(MetaDataItem.PageChangeMessage, null, Defaults.PageChangeMessage); } if (ssp.GetMetaDataItem(MetaDataItem.DiscussionChangeMessage, null) == "") { ssp.SetMetaDataItem(MetaDataItem.DiscussionChangeMessage, null, Defaults.DiscussionChangeMessage); } if (ssp.GetMetaDataItem(MetaDataItem.ApproveDraftMessage, null) == "") { ssp.SetMetaDataItem(MetaDataItem.ApproveDraftMessage, null, Defaults.ApproveDraftMessage); } } // Load config IIndexDirectoryProviderV30 idp = ProviderLoader.LoadIndexDirectoryProvider(WebConfigurationManager.AppSettings["IndexDirectoryProvider"]); idp.Init(Host.Instance, GetSettingsStorageProviderConfiguration()); Collectors.IndexDirectoryProvider = idp; MimeTypes.Init(); // Load Providers Collectors.FileNames = new System.Collections.Generic.Dictionary <string, string>(10); Collectors.UsersProviderCollector = new ProviderCollector <IUsersStorageProviderV30>(); Collectors.PagesProviderCollector = new ProviderCollector <IPagesStorageProviderV30>(); Collectors.FilesProviderCollector = new ProviderCollector <IFilesStorageProviderV30>(); Collectors.FormatterProviderCollector = new ProviderCollector <IFormatterProviderV30>(); Collectors.CacheProviderCollector = new ProviderCollector <ICacheProviderV30>(); Collectors.DisabledUsersProviderCollector = new ProviderCollector <IUsersStorageProviderV30>(); Collectors.DisabledPagesProviderCollector = new ProviderCollector <IPagesStorageProviderV30>(); Collectors.DisabledFilesProviderCollector = new ProviderCollector <IFilesStorageProviderV30>(); Collectors.DisabledFormatterProviderCollector = new ProviderCollector <IFormatterProviderV30>(); Collectors.DisabledCacheProviderCollector = new ProviderCollector <ICacheProviderV30>(); // Load built-in providers // Files storage providers have to be loaded BEFORE users storage providers in order to properly set permissions FilesStorageProvider f = new FilesStorageProvider(); if (!ProviderLoader.IsDisabled(f.GetType().FullName)) { f.Init(Host.Instance, ""); Collectors.FilesProviderCollector.AddProvider(f); Log.LogEntry("Provider " + f.Information.Name + " loaded (Enabled)", EntryType.General, Log.SystemUsername); } else { Collectors.DisabledFilesProviderCollector.AddProvider(f); Log.LogEntry("Provider " + f.Information.Name + " loaded (Disabled)", EntryType.General, Log.SystemUsername); } UsersStorageProvider u = new UsersStorageProvider(); if (!ProviderLoader.IsDisabled(u.GetType().FullName)) { u.Init(Host.Instance, ""); Collectors.UsersProviderCollector.AddProvider(u); Log.LogEntry("Provider " + u.Information.Name + " loaded (Enabled)", EntryType.General, Log.SystemUsername); } else { Collectors.DisabledUsersProviderCollector.AddProvider(u); Log.LogEntry("Provider " + u.Information.Name + " loaded (Disabled)", EntryType.General, Log.SystemUsername); } // Load Users (pages storage providers might need access to users/groups data for upgrading from 2.0 to 3.0) ProviderLoader.FullLoad(true, false, false, false, false); //Users.Instance = new Users(); bool groupsCreated = VerifyAndCreateDefaultGroups(); PagesStorageProvider p = new PagesStorageProvider(); if (!ProviderLoader.IsDisabled(p.GetType().FullName)) { p.Init(Host.Instance, ""); Collectors.PagesProviderCollector.AddProvider(p); Log.LogEntry("Provider " + p.Information.Name + " loaded (Enabled)", EntryType.General, Log.SystemUsername); } else { Collectors.DisabledPagesProviderCollector.AddProvider(p); Log.LogEntry("Provider " + p.Information.Name + " loaded (Disabled)", EntryType.General, Log.SystemUsername); } CacheProvider c = new CacheProvider(); if (!ProviderLoader.IsDisabled(c.GetType().FullName)) { c.Init(Host.Instance, ""); Collectors.CacheProviderCollector.AddProvider(c); Log.LogEntry("Provider " + c.Information.Name + " loaded (Enabled)", EntryType.General, Log.SystemUsername); } else { Collectors.DisabledCacheProviderCollector.AddProvider(c); Log.LogEntry("Provider " + c.Information.Name + " loaded (Disabled)", EntryType.General, Log.SystemUsername); } // Load all other providers ProviderLoader.FullLoad(false, true, true, true, true); if (groupsCreated) { // It is necessary to set default permissions for file management UserGroup administratorsGroup = Users.FindUserGroup(Settings.AdministratorsGroup); UserGroup anonymousGroup = Users.FindUserGroup(Settings.AnonymousGroup); UserGroup usersGroup = Users.FindUserGroup(Settings.UsersGroup); SetAdministratorsGroupDefaultPermissions(administratorsGroup); SetUsersGroupDefaultPermissions(usersGroup); SetAnonymousGroupDefaultPermissions(anonymousGroup); } // Init cache //Cache.Instance = new Cache(Collectors.CacheProviderCollector.GetProvider(Settings.DefaultCacheProvider)); if (Collectors.CacheProviderCollector.GetProvider(Settings.DefaultCacheProvider) == null) { Log.LogEntry("Default Cache Provider was not loaded, backing to integrated provider", EntryType.Error, Log.SystemUsername); Settings.DefaultCacheProvider = typeof(CacheProvider).FullName; Collectors.TryEnable(Settings.DefaultCacheProvider); } // Create the Main Page, if needed if (Pages.FindPage(Settings.DefaultPage) == null) { CreateMainPage(); } Log.LogEntry("ScrewTurn Wiki is ready", EntryType.General, Log.SystemUsername); System.Threading.ThreadPool.QueueUserWorkItem(ignored => { SearchClass.RebuildIndex(); }); }
/// <summary> /// Stores and indexes a page attachment. /// </summary> /// <param name="provider">The provider.</param> /// <param name="pageFullName">The page full name.</param> /// <param name="name">The attachment name.</param> /// <param name="source">The source stream.</param> /// <param name="overwrite"><c>true</c> to overwrite an existing attachment with the same name, <c>false</c> otherwise.</param> /// <returns><c>true</c> if the attachment was stored, <c>false</c> otherwise.</returns> public static bool StorePageAttachment(IFilesStorageProviderV30 provider, string pageFullName, string name, Stream source, bool overwrite) { if (provider == null) { throw new ArgumentNullException("provider"); } if (pageFullName == null) { throw new ArgumentNullException("pageFullName"); } if (pageFullName.Length == 0) { throw new ArgumentException("Page Full Name cannot be empty", "pageFullName"); } if (name == null) { throw new ArgumentNullException("name"); } if (name.Length == 0) { throw new ArgumentException("Name cannot be empty", "name"); } if (source == null) { throw new ArgumentNullException("source"); } PageInfo pageInfo = Pages.FindPage(pageFullName); if (pageInfo == null) { return(false); } PageContent page = Content.GetPageContent(pageInfo, false); if (page == null) { return(false); } bool done = provider.StorePageAttachment(pageInfo, name, source, overwrite); if (!done) { return(false); } if (overwrite) { SearchClass.UnindexPageAttachment(name, page); } // Index the attached file string tempDir = Path.Combine(Environment.GetEnvironmentVariable("TEMP"), Guid.NewGuid().ToString()); if (!Directory.Exists(tempDir)) { Directory.CreateDirectory(tempDir); } string tempFile = Path.Combine(tempDir, name); source.Seek(0, SeekOrigin.Begin); using (FileStream temp = File.Create(tempFile)) { source.CopyTo(temp); } SearchClass.IndexPageAttachment(name, tempFile, page); Directory.Delete(tempDir, true); Host.Instance.OnAttachmentActivity(provider.GetType().FullName, name, pageFullName, null, FileActivity.AttachmentUploaded); return(true); }
protected void rptIndex_ItemCommand(object sender, CommandEventArgs e) { Log.LogEntry("Index rebuild requested for " + e.CommandArgument as string, EntryType.General, SessionFacade.GetCurrentUsername(), currentWiki); if (e.CommandName == "PagesRebuild") { // Clear the pages search index for the current wiki SearchClass.ClearIndex(currentWiki); IPagesStorageProviderV40 pagesProvider = Collectors.CollectorsBox.PagesProviderCollector.GetProvider(e.CommandArgument as string, currentWiki); // Index all pages of the wiki List <NamespaceInfo> namespaces = new List <NamespaceInfo>(pagesProvider.GetNamespaces()); namespaces.Add(null); foreach (NamespaceInfo nspace in namespaces) { // Index pages of the namespace PageContent[] pages = pagesProvider.GetPages(nspace); foreach (PageContent page in pages) { // Index page SearchClass.IndexPage(page); // Index page messages Message[] messages = pagesProvider.GetMessages(page.FullName); foreach (Message message in messages) { SearchClass.IndexMessage(message, page); // Search for replies Message[] replies = message.Replies; foreach (Message reply in replies) { // Index reply SearchClass.IndexMessage(reply, page); } } } } } else if (e.CommandName == "FilesRebuild") { // Clear the files search index for the current wiki SearchClass.ClearFilesIndex(currentWiki); IFilesStorageProviderV40 filesProvider = Collectors.CollectorsBox.FilesProviderCollector.GetProvider(e.CommandArgument as string, currentWiki); // Index all files of the wiki // 1. List all directories (add the root directory: null) // 2. List all files in each directory // 3. Index each file List <string> directories = new List <string>(filesProvider.ListDirectories(null)); directories.Add(null); foreach (string directory in directories) { string[] files = filesProvider.ListFiles(directory); foreach (string file in files) { byte[] fileContent; using (MemoryStream stream = new MemoryStream()) { filesProvider.RetrieveFile(file, stream); fileContent = new byte[stream.Length]; stream.Seek(0, SeekOrigin.Begin); stream.Read(fileContent, 0, (int)stream.Length); } // Index the file string tempDir = Path.Combine(Environment.GetEnvironmentVariable("TEMP"), Guid.NewGuid().ToString()); if (!Directory.Exists(tempDir)) { Directory.CreateDirectory(tempDir); } string tempFile = Path.Combine(tempDir, file.Substring(file.LastIndexOf('/') + 1)); using (FileStream writer = File.Create(tempFile)) { writer.Write(fileContent, 0, fileContent.Length); } SearchClass.IndexFile(filesProvider.GetType().FullName + "|" + file, tempFile, currentWiki); Directory.Delete(tempDir, true); } } // Index all attachment of the wiki string[] pagesWithAttachments = filesProvider.GetPagesWithAttachments(); foreach (string page in pagesWithAttachments) { string[] attachments = filesProvider.ListPageAttachments(page); foreach (string attachment in attachments) { byte[] fileContent; using (MemoryStream stream = new MemoryStream()) { filesProvider.RetrievePageAttachment(page, attachment, stream); fileContent = new byte[stream.Length]; stream.Seek(0, SeekOrigin.Begin); stream.Read(fileContent, 0, (int)stream.Length); } // Index the attached file string tempDir = Path.Combine(Environment.GetEnvironmentVariable("TEMP"), Guid.NewGuid().ToString()); if (!Directory.Exists(tempDir)) { Directory.CreateDirectory(tempDir); } string tempFile = Path.Combine(tempDir, attachment); using (FileStream writer = File.Create(tempFile)) { writer.Write(fileContent, 0, fileContent.Length); } SearchClass.IndexPageAttachment(attachment, tempFile, Pages.FindPage(currentWiki, page)); Directory.Delete(tempDir, true); } } } Log.LogEntry("Index rebuild completed for " + e.CommandArgument as string, EntryType.General, SessionFacade.GetCurrentUsername(), currentWiki); }
/// <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(); }