/// <summary> /// Activates the page editor. /// </summary> private void ActivatePageEditor() { lblCurrentPage.Text = txtCurrentPage.Value; txtNewName.Text = NameTools.GetLocalName(txtCurrentPage.Value); // Enable/disable page sections PageContent page = Pages.FindPage(currentWiki, txtCurrentPage.Value); NamespaceInfo nspace = Pages.FindNamespace(currentWiki, NameTools.GetNamespace(page.FullName)); string currentUser = SessionFacade.GetCurrentUsername(); string[] currentGroups = SessionFacade.GetCurrentGroupNames(currentWiki); AuthChecker authChecker = new AuthChecker(Collectors.CollectorsBox.GetSettingsProvider(currentWiki)); bool canApproveReject = AdminMaster.CanApproveDraft(page.Provider.CurrentWiki, page.FullName, currentUser, currentGroups); bool canDeletePages = authChecker.CheckActionForNamespace(nspace, Actions.ForNamespaces.DeletePages, currentUser, currentGroups); bool canManageAllPages = authChecker.CheckActionForNamespace(nspace, Actions.ForNamespaces.ManagePages, currentUser, currentGroups); bool canManagePage = authChecker.CheckActionForPage(page.FullName, Actions.ForPages.ManagePage, currentUser, currentGroups); bool canManageDiscussion = authChecker.CheckActionForPage(page.FullName, Actions.ForPages.ManageDiscussion, currentUser, currentGroups); bool namespaceAvailable = PopulateTargetNamespaces(page); // Approve/reject // Rename // Migrate // Rollback // Delete Backups // Clear discussion // Delete pnlApproveRevision.Enabled = canApproveReject; pnlRename.Enabled = canDeletePages; pnlMigrate.Enabled = canManageAllPages && namespaceAvailable; pnlRollback.Enabled = canManagePage; pnlDeleteBackups.Enabled = canManagePage; pnlClearDiscussion.Enabled = canManageDiscussion; pnlDelete.Enabled = canDeletePages; // Disable rename, migrate, delete for default page NamespaceInfo currentNamespace = Pages.FindNamespace(currentWiki, lstNamespace.SelectedValue); string currentDefaultPage = currentNamespace != null ? currentNamespace.DefaultPageFullName : Settings.GetDefaultPage(currentWiki); if (txtCurrentPage.Value == currentDefaultPage) { btnRename.Enabled = false; btnMigrate.Enabled = false; btnDeletePage.Enabled = false; } LoadDraft(txtCurrentPage.Value); LoadBackups(txtCurrentPage.Value); btnRollback.Enabled = lstRevision.Items.Count > 0; btnDeleteBackups.Enabled = lstBackup.Items.Count > 0; pnlList.Visible = false; pnlEditPage.Visible = true; ClearResultLabels(); }
protected void btnDeletePage_Click(object sender, EventArgs e) { PageInfo page = Pages.FindPage(txtCurrentPage.Value); if (!AuthChecker.CheckActionForNamespace(Pages.FindNamespace(NameTools.GetNamespace(page.FullName)), Actions.ForNamespaces.DeletePages, SessionFacade.GetCurrentUsername(), SessionFacade.GetCurrentGroupNames())) { return; } Log.LogEntry("Page deletion requested for " + txtCurrentPage.Value, EntryType.General, Log.SystemUsername); bool done = Pages.DeletePage(page); if (done) { ResetPageList(); RefreshList(); lblDeleteResult.CssClass = "resultok"; lblDeleteResult.Text = Properties.Messages.PageDeleted; ReturnToList(); } else { lblDeleteResult.CssClass = "resulterror"; lblDeleteResult.Text = Properties.Messages.CouldNotDeletePage; } }
/// <summary> /// Populates the namespaces list for migration. /// </summary> /// <param name="page">The selected page.</param> /// <returns><c>true</c> if there is at least one valid target namespace, <c>false</c> otherwise.</returns> private bool PopulateTargetNamespaces(PageInfo page) { string currentUser = SessionFacade.GetCurrentUsername(); string[] currentGroups = SessionFacade.GetCurrentGroupNames(); lstTargetNamespace.Items.Clear(); NamespaceInfo pageNamespace = Pages.FindNamespace(NameTools.GetNamespace(page.FullName)); if (pageNamespace != null) { // Try adding Root as target namespace bool canManagePages = AuthChecker.CheckActionForNamespace(null, Actions.ForNamespaces.ManagePages, currentUser, currentGroups); if (canManagePages) { lstTargetNamespace.Items.Add(new ListItem("<root>", "")); } } // Try adding all other namespaces foreach (NamespaceInfo nspace in Pages.GetNamespaces().FindAll(n => n.Provider == page.Provider)) { if (pageNamespace == null || (pageNamespace != null && nspace.Name != pageNamespace.Name)) { bool canManagePages = AuthChecker.CheckActionForNamespace(nspace, Actions.ForNamespaces.ManagePages, currentUser, currentGroups); if (canManagePages) { lstTargetNamespace.Items.Add(new ListItem(nspace.Name, nspace.Name)); } } } return(lstTargetNamespace.Items.Count > 0); }
/// <summary> /// Appends a breadbrumb trail element. /// </summary> /// <param name="sb">The destination <see cref="T:StringBuilder" />.</param> /// <param name="page">The page to append.</param> /// <param name="dpPrefix">The drop-down menu ID prefix.</param> private void AppendBreadcrumb(StringBuilder sb, PageInfo page, string dpPrefix) { PageNameComparer comp = new PageNameComparer(); PageContent pc = Content.GetPageContent(page, true); string id = AppendBreadcrumbDropDown(sb, page, dpPrefix); string nspace = NameTools.GetNamespace(page.FullName); sb.Append("» "); if (comp.Compare(page, currentPage) == 0) { sb.Append("<b>"); } sb.AppendFormat(@"<a href=""{0}"" title=""{1}""{2}{3}{4}>{1}</a>", Tools.UrlEncode(page.FullName) + Settings.PageExtension, FormattingPipeline.PrepareTitle(pc.Title, false, FormattingContext.PageContent, currentPage) + (string.IsNullOrEmpty(nspace) ? "" : (" (" + NameTools.GetNamespace(page.FullName) + ")")), (id != null ? @" onmouseover=""javascript:return __ShowDropDown(event, '" + id + @"', this);""" : ""), (id != null ? @" id=""lnk" + id + @"""" : ""), (id != null ? @" onmouseout=""javascript:return __HideDropDown('" + id + @"');""" : "")); if (comp.Compare(page, currentPage) == 0) { sb.Append("</b>"); } sb.Append(" "); }
/// <summary> /// Searches for pages with name or title similar to a specified value. /// </summary> /// <param name="wiki">The wiki.</param> /// <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 PageContent[] SearchSimilarPages(string wiki, string name, string nspace) { if (string.IsNullOrEmpty(nspace)) { nspace = null; } var searchFields = new [] { SearchField.PageFullName }; List <SearchResult> searchResults = Search(wiki, searchFields, name, SearchOptions.AtLeastOneWord); var result = new List <PageContent>(20); foreach (SearchResult res in searchResults) { var pageDoc = res.Document as PageDocument; if (pageDoc != null) { string pageNamespace = NameTools.GetNamespace(pageDoc.PageFullName); if (string.IsNullOrEmpty(pageNamespace)) { pageNamespace = null; } if (pageNamespace == nspace) { var page = new PageContent(pageDoc.PageFullName, null, new DateTime(), pageDoc.Title, null, new DateTime(), null, pageDoc.Content, null, null); result.Add(page); } } } // Search page names for matches List <PageContent> allPages = Pages.GetPages(wiki, Pages.FindNamespace(wiki, nspace)); var comp = new PageNameComparer(); string currentName = name.ToLowerInvariant(); foreach (PageContent page in allPages) { if (NameTools.GetLocalName(page.FullName).ToLowerInvariant().Contains(currentName)) { if (result.Find(p => comp.Compare(p, page) == 0) == null) { result.Add(page); } } } return(result.ToArray()); }
/// <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); var result = new List <PageInfo>(20); foreach (SearchResult res in searchResults) { var pageDoc = res.Document as PageDocument; if (pageDoc != null) { var 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)); var comp = new PageNameComparer(); var 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()); }
/// <summary> /// Finds all the Navigation Paths that include a Page. /// </summary> /// <param name="wiki">The wiki.</param> /// <param name="pageFullName">The full name of the page.</param> /// <returns>The list of Navigation Paths.</returns> public static string[] PathsPerPage(string wiki, string pageFullName) { NamespaceInfo pageNamespace = Pages.FindNamespace(wiki, NameTools.GetNamespace(pageFullName)); List <string> result = new List <string>(10); List <NavigationPath> allPaths = GetNavigationPaths(wiki, pageNamespace); for (int i = 0; i < allPaths.Count; i++) { List <string> pages = new List <string>(allPaths[i].Pages); if (pages.Contains(pageFullName)) { result.Add(allPaths[i].FullName); } } return(result.ToArray()); }
/// <summary> /// Finds all the Navigation Paths that include a Page. /// </summary> /// <param name="page">The Page.</param> /// <returns>The list of Navigation Paths.</returns> public static string[] PathsPerPage(PageInfo page) { NamespaceInfo pageNamespace = Pages.FindNamespace(NameTools.GetNamespace(page.FullName)); var result = new List <string>(10); List <NavigationPath> allPaths = GetNavigationPaths(pageNamespace); for (var i = 0; i < allPaths.Count; i++) { var pages = new List <string>(allPaths[i].Pages); if (pages.Contains(page.FullName)) { result.Add(allPaths[i].FullName); } } return(result.ToArray()); }
protected List <TreeElement> ctPages_Populate(object sender, PopulateEventArgs e) { string currentNamespace = DetectNamespace(); if (string.IsNullOrEmpty(currentNamespace)) { currentNamespace = null; } List <TreeElement> result = new List <TreeElement>(100); foreach (PageInfo pi in Pages.GetPages(Pages.FindNamespace(lstNamespace.SelectedValue))) { string pageNamespace = NameTools.GetNamespace(pi.FullName); if (string.IsNullOrEmpty(pageNamespace)) { pageNamespace = null; } PageContent cont = Content.GetPageContent(pi, true); string formattedTitle = FormattingPipeline.PrepareTitle(cont.Title, false, FormattingContext.Other, pi); string onClickJavascript = "javascript:"; // Populate the page title box if the title is different to the page name if (pi.FullName != cont.Title) { // Supply the page title to the Javascript that sets the page title on the page // We can safely escape the \ and ' characters, but the " character is interpreted by the browser even if it is escaped to Javascript, so we can't allow it. // Instead we replace it with an escaped single quote. // Similarly, < on it's own is fine, but causes problems when combined with text and > to form a tag. Safest to remove < characters to prevent // breaking the drop-down. onClickJavascript += "SetValue('txtPageTitle', '" + cont.Title.Replace("\\", "\\\\").Replace("'", "\\'").Replace("\"", "\\'").Replace("<", "") + "');"; } else { onClickJavascript += "SetValue('txtPageTitle', '');"; } // Populate the page name onClickJavascript += "return SetValue('txtPageName', '" + ((pageNamespace == currentNamespace ? NameTools.GetLocalName(pi.FullName) : ("++" + pi.FullName))).Replace("++++", "++") + "');"; TreeElement item = new TreeElement(pi.FullName, formattedTitle, onClickJavascript); result.Add(item); } return(result); }
private static Authorization LocalCheckActionForPage(PageInfo page, string action, string currentUser, string[] groups, bool localEscalator = false) { AclEntry[] entries = SettingsProvider.AclManager.RetrieveEntriesForResource(Actions.ForPages.ResourceMasterPrefix + page.FullName); Authorization auth = AclEvaluator.AuthorizeAction(Actions.ForPages.ResourceMasterPrefix + page.FullName, action, AuthTools.PrepareUsername(currentUser), AuthTools.PrepareGroups(groups), entries); if (localEscalator || auth != Authorization.Unknown) { return(auth); } // Try local escalators string[] localEscalators = null; if (Actions.ForPages.LocalEscalators.TryGetValue(action, out localEscalators)) { foreach (string localAction in localEscalators) { Authorization authorization = LocalCheckActionForPage(page, localAction, currentUser, groups, true); if (authorization != Authorization.Unknown) { return(authorization); } } } // Try namespace escalators string[] namespaceEscalators = null; string nsName = NameTools.GetNamespace(page.FullName); NamespaceInfo ns = string.IsNullOrEmpty(nsName) ? null : new NamespaceInfo(nsName, null, null); if (Actions.ForPages.NamespaceEscalators.TryGetValue(action, out namespaceEscalators)) { foreach (string namespaceAction in namespaceEscalators) { Authorization authorization = LocalCheckActionForNamespace(ns, namespaceAction, currentUser, groups, true); if (authorization != Authorization.Unknown) { return(authorization); } // Try root escalation if (ns != null) { authorization = LocalCheckActionForNamespace(null, namespaceAction, currentUser, groups, true); if (authorization != Authorization.Unknown) { return(authorization); } } } } // Try global escalators string[] globalEscalators = null; if (Actions.ForPages.GlobalEscalators.TryGetValue(action, out globalEscalators)) { foreach (string globalAction in globalEscalators) { Authorization authorization = LocalCheckActionForGlobals(globalAction, currentUser, groups); if (authorization != Authorization.Unknown) { return(authorization); } } } return(Authorization.Unknown); }
public void MigratePagesStorageProviderData() { var mocks = new MockRepository(); var source = mocks.StrictMock <IPagesStorageProviderV30>(); var destination = mocks.StrictMock <IPagesStorageProviderV30>(); // Setup SOURCE ------------------------- // Setup snippets var s1 = new Snippet("S1", "Blah1", source); var s2 = new Snippet("S2", "Blah2", source); Expect.Call(source.GetSnippets()).Return(new[] { s1, s2 }); // Setup content templates var ct1 = new ContentTemplate("CT1", "Template 1", source); var ct2 = new ContentTemplate("CT2", "Template 2", source); Expect.Call(source.GetContentTemplates()).Return(new[] { ct1, ct2 }); // Setup namespaces var ns1 = new NamespaceInfo("NS1", source, null); var ns2 = new NamespaceInfo("NS2", source, null); Expect.Call(source.GetNamespaces()).Return(new[] { ns1, ns2 }); // Setup pages var p1 = new PageInfo("Page", source, DateTime.Now); var p2 = new PageInfo(NameTools.GetFullName(ns1.Name, "Page"), source, DateTime.Now); var p3 = new PageInfo(NameTools.GetFullName(ns1.Name, "Page1"), source, DateTime.Now); Expect.Call(source.GetPages(null)).Return(new[] { p1 }); Expect.Call(source.GetPages(ns1)).Return(new[] { p2, p3 }); Expect.Call(source.GetPages(ns2)).Return(new PageInfo[0]); // Set default page for NS1 ns1.DefaultPage = p2; // Setup categories/bindings var c1 = new CategoryInfo("Cat", source); c1.Pages = new[] { p1.FullName }; var c2 = new CategoryInfo(NameTools.GetFullName(ns1.Name, "Cat"), source); c2.Pages = new[] { p2.FullName }; var c3 = new CategoryInfo(NameTools.GetFullName(ns1.Name, "Cat1"), source); c3.Pages = new string[0]; Expect.Call(source.GetCategories(null)).Return(new[] { c1 }); Expect.Call(source.GetCategories(ns1)).Return(new[] { c2, c3 }); Expect.Call(source.GetCategories(ns2)).Return(new CategoryInfo[0]); // Setup drafts var d1 = new PageContent(p1, "Draft", "NUnit", DateTime.Now, "Comm", "Cont", new[] { "k1", "k2" }, "Descr"); Expect.Call(source.GetDraft(p1)).Return(d1); Expect.Call(source.GetDraft(p2)).Return(null); Expect.Call(source.GetDraft(p3)).Return(null); // Setup content var ctn1 = new PageContent(p1, "Title1", "User1", DateTime.Now, "Comm1", "Cont1", null, "Descr1"); var ctn2 = new PageContent(p2, "Title2", "User2", DateTime.Now, "Comm2", "Cont2", null, "Descr2"); var ctn3 = new PageContent(p3, "Title3", "User3", DateTime.Now, "Comm3", "Cont3", null, "Descr3"); Expect.Call(source.GetContent(p1)).Return(ctn1); Expect.Call(source.GetContent(p2)).Return(ctn2); Expect.Call(source.GetContent(p3)).Return(ctn3); // Setup backups Expect.Call(source.GetBackups(p1)).Return(new[] { 0, 1 }); Expect.Call(source.GetBackups(p2)).Return(new[] { 0 }); Expect.Call(source.GetBackups(p3)).Return(new int[0]); var bak1_0 = new PageContent(p1, "K1_0", "U1_0", DateTime.Now, "", "Cont", null, null); var bak1_1 = new PageContent(p1, "K1_1", "U1_1", DateTime.Now, "", "Cont", null, null); var bak2_0 = new PageContent(p2, "K2_0", "U2_0", DateTime.Now, "", "Cont", null, null); Expect.Call(source.GetBackupContent(p1, 0)).Return(bak1_0); Expect.Call(source.GetBackupContent(p1, 1)).Return(bak1_1); Expect.Call(source.GetBackupContent(p2, 0)).Return(bak2_0); // Messages var m1 = new Message(1, "User1", "Subject1", DateTime.Now, "Body1"); m1.Replies = new[] { new Message(2, "User2", "Subject2", DateTime.Now, "Body2") }; Message[] p1m = { m1 }; var p2m = new Message[0]; var p3m = new Message[0]; Expect.Call(source.GetMessages(p1)).Return(p1m); Expect.Call(source.GetMessages(p2)).Return(p2m); Expect.Call(source.GetMessages(p3)).Return(p3m); // Setup navigation paths var n1 = new NavigationPath("N1", source); n1.Pages = new[] { p1.FullName }; var n2 = new NavigationPath(NameTools.GetFullName(ns1.Name, "N1"), source); n2.Pages = new[] { p2.FullName, p3.FullName }; Expect.Call(source.GetNavigationPaths(null)).Return(new[] { n1 }); Expect.Call(source.GetNavigationPaths(ns1)).Return(new[] { n2 }); Expect.Call(source.GetNavigationPaths(ns2)).Return(new NavigationPath[0]); // Setup DESTINATION -------------------------- // Snippets Expect.Call(destination.AddSnippet(s1.Name, s1.Content)) .Return(new Snippet(s1.Name, s1.Content, destination)); Expect.Call(source.RemoveSnippet(s1.Name)).Return(true); Expect.Call(destination.AddSnippet(s2.Name, s2.Content)) .Return(new Snippet(s2.Name, s2.Content, destination)); Expect.Call(source.RemoveSnippet(s2.Name)).Return(true); // Content templates Expect.Call(destination.AddContentTemplate(ct1.Name, ct1.Content)) .Return(new ContentTemplate(ct1.Name, ct1.Name, destination)); Expect.Call(source.RemoveContentTemplate(ct1.Name)).Return(true); Expect.Call(destination.AddContentTemplate(ct2.Name, ct2.Content)) .Return(new ContentTemplate(ct2.Name, ct2.Name, destination)); Expect.Call(source.RemoveContentTemplate(ct2.Name)).Return(true); // Namespaces var ns1Out = new NamespaceInfo(ns1.Name, destination, null); var ns2Out = new NamespaceInfo(ns2.Name, destination, null); Expect.Call(destination.AddNamespace(ns1.Name)).Return(ns1Out); Expect.Call(source.RemoveNamespace(ns1)).Return(true); Expect.Call(destination.AddNamespace(ns2.Name)).Return(ns2Out); Expect.Call(source.RemoveNamespace(ns2)).Return(true); // Pages/drafts/content/backups/messages var p1Out = new PageInfo(p1.FullName, destination, p1.CreationDateTime); Expect.Call(destination.AddPage(null, p1.FullName, p1.CreationDateTime)).Return(p1Out); Expect.Call(destination.ModifyPage(p1Out, ctn1.Title, ctn1.User, ctn1.LastModified, ctn1.Comment, ctn1.Content, ctn1.Keywords, ctn1.Description, SaveMode.Normal)).Return(true); Expect.Call(destination.ModifyPage(p1Out, d1.Title, d1.User, d1.LastModified, d1.Comment, d1.Content, d1.Keywords, d1.Description, SaveMode.Draft)).Return(true); Expect.Call(destination.SetBackupContent(bak1_0, 0)).Return(true); Expect.Call(destination.SetBackupContent(bak1_1, 1)).Return(true); Expect.Call(destination.BulkStoreMessages(p1Out, p1m)).Return(true); Expect.Call(source.RemovePage(p1)).Return(true); var p2Out = new PageInfo(p2.FullName, destination, p2.CreationDateTime); Expect.Call(destination.AddPage(p2.Namespace, p2.Name, p2.CreationDateTime)).Return(p2Out); Expect.Call(destination.ModifyPage(p2Out, ctn2.Title, ctn2.User, ctn2.LastModified, ctn2.Comment, ctn2.Content, ctn2.Keywords, ctn2.Description, SaveMode.Normal)).Return(true); Expect.Call(destination.SetBackupContent(bak2_0, 0)).Return(true); Expect.Call(destination.BulkStoreMessages(p2Out, p2m)).Return(true); Expect.Call(source.RemovePage(p2)).Return(true); var p3Out = new PageInfo(p3.FullName, destination, p3.CreationDateTime); Expect.Call(destination.AddPage(p3.Namespace, p3.Name, p3.CreationDateTime)).Return(p3Out); Expect.Call(destination.ModifyPage(p3Out, ctn3.Title, ctn3.User, ctn3.LastModified, ctn3.Comment, ctn3.Content, ctn3.Keywords, ctn3.Description, SaveMode.Normal)).Return(true); Expect.Call(destination.BulkStoreMessages(p3Out, p3m)).Return(true); Expect.Call(source.RemovePage(p3)).Return(true); // Categories/bindings var c1Out = new CategoryInfo(c1.FullName, destination); var c2Out = new CategoryInfo(c2.FullName, destination); var c3Out = new CategoryInfo(c3.FullName, destination); Expect.Call(destination.AddCategory(null, c1.FullName)).Return(c1Out); Expect.Call(destination.AddCategory(NameTools.GetNamespace(c2.FullName), NameTools.GetLocalName(c2.FullName))) .Return(c2Out); Expect.Call(destination.AddCategory(NameTools.GetNamespace(c3.FullName), NameTools.GetLocalName(c3.FullName))) .Return(c3Out); Expect.Call(destination.RebindPage(p1Out, new[] { c1.FullName })).Return(true); Expect.Call(destination.RebindPage(p2Out, new[] { c2.FullName })).Return(true); Expect.Call(destination.RebindPage(p3Out, new string[0])).Return(true); Expect.Call(source.RemoveCategory(c1)).Return(true); Expect.Call(source.RemoveCategory(c2)).Return(true); Expect.Call(source.RemoveCategory(c3)).Return(true); // Navigation paths var n1Out = new NavigationPath(n1.FullName, destination); n1Out.Pages = n1.Pages; var n2Out = new NavigationPath(n2.FullName, destination); n2Out.Pages = n2.Pages; Expect.Call(destination.AddNavigationPath(null, n1.FullName, new[] { p1 })).Return(n1Out).Constraints( RMC.Is.Null(), RMC.Is.Equal(n1.FullName), RMC.Is.Matching(delegate(PageInfo[] array) { return(array[0].FullName == p1.FullName); })); Expect.Call(destination.AddNavigationPath(NameTools.GetNamespace(n2.FullName), NameTools.GetLocalName(n2.FullName), new[] { p2, p3 })).Return(n2Out).Constraints( RMC.Is.Equal(NameTools.GetNamespace(n2.FullName)), RMC.Is.Equal(NameTools.GetLocalName(n2.FullName)), RMC.Is.Matching( delegate(PageInfo[] array) { return(array[0].FullName == p2.FullName && array[1].FullName == p3.FullName); })); Expect.Call(source.RemoveNavigationPath(n1)).Return(true); Expect.Call(source.RemoveNavigationPath(n2)).Return(true); Expect.Call(destination.SetNamespaceDefaultPage(ns1Out, p2Out)).Return(ns1Out); Expect.Call(destination.SetNamespaceDefaultPage(ns2Out, null)).Return(ns2Out); // Used for navigation paths Expect.Call(destination.GetPages(null)).Return(new[] { p1Out }); Expect.Call(destination.GetPages(ns1Out)).Return(new[] { p2Out, p3Out }); Expect.Call(destination.GetPages(ns2Out)).Return(new PageInfo[0]); mocks.Replay(source); mocks.Replay(destination); DataMigrator.MigratePagesStorageProviderData(source, destination); mocks.Verify(source); mocks.Verify(destination); }
/// <summary> /// Checks whether an action is allowed for a page. /// </summary> /// <param name="page">The current page.</param> /// <param name="action">The action the user is attempting to perform.</param> /// <param name="currentUser">The current user.</param> /// <param name="groups">The groups the user is member of.</param> /// <returns><c>true</c> if the action is allowed, <c>false</c> otherwise.</returns> public static bool CheckActionForPage(PageInfo page, string action, string currentUser, string[] groups) { if (page == null) { throw new ArgumentNullException("page"); } if (action == null) { throw new ArgumentNullException("action"); } if (action.Length == 0) { throw new ArgumentException("Action cannot be empty", "action"); } if (!AuthTools.IsValidAction(action, Actions.ForPages.All)) { throw new ArgumentException("Invalid action", "action"); } if (currentUser == null) { throw new ArgumentNullException("currentUser"); } if (currentUser.Length == 0) { throw new ArgumentException("Current User cannot be empty", "currentUser"); } if (groups == null) { throw new ArgumentNullException("groups"); } if (currentUser == "admin") { return(true); } AclEntry[] entries = SettingsProvider.AclManager.RetrieveEntriesForResource(Actions.ForPages.ResourceMasterPrefix + page.FullName); Authorization auth = AclEvaluator.AuthorizeAction(Actions.ForPages.ResourceMasterPrefix + page.FullName, action, AuthTools.PrepareUsername(currentUser), AuthTools.PrepareGroups(groups), entries); if (auth != Authorization.Unknown) { return(auth == Authorization.Granted); } // Try local escalators string[] localEscalators = null; if (Actions.ForPages.LocalEscalators.TryGetValue(action, out localEscalators)) { foreach (string localAction in localEscalators) { bool authorized = CheckActionForPage(page, localAction, currentUser, groups); if (authorized) { return(true); } } } // Try namespace escalators string[] namespaceEscalators = null; string nsName = NameTools.GetNamespace(page.FullName); NamespaceInfo ns = string.IsNullOrEmpty(nsName) ? null : new NamespaceInfo(nsName, null, null); if (Actions.ForPages.NamespaceEscalators.TryGetValue(action, out namespaceEscalators)) { foreach (string namespaceAction in namespaceEscalators) { bool authorized = CheckActionForNamespace(ns, namespaceAction, currentUser, groups); if (authorized) { return(true); } } } // Try global escalators string[] globalEscalators = null; if (Actions.ForPages.GlobalEscalators.TryGetValue(action, out globalEscalators)) { foreach (string globalAction in globalEscalators) { bool authorized = CheckActionForGlobals(globalAction, currentUser, groups); if (authorized) { return(true); } } } return(false); }
/// <summary> /// Migrates <b>all</b> the data from a Pages Provider to another one. /// </summary> /// <param name="source">The source Provider.</param> /// <param name="destination">The destination Provider.</param> public static void MigratePagesStorageProviderData(IPagesStorageProviderV30 source, IPagesStorageProviderV30 destination) { // Move Snippets Snippet[] snippets = source.GetSnippets(); for (int i = 0; i < snippets.Length; i++) { destination.AddSnippet(snippets[i].Name, snippets[i].Content); source.RemoveSnippet(snippets[i].Name); } // Move Content Templates ContentTemplate[] templates = source.GetContentTemplates(); for (int i = 0; i < templates.Length; i++) { destination.AddContentTemplate(templates[i].Name, templates[i].Content); source.RemoveContentTemplate(templates[i].Name); } // Create namespaces NamespaceInfo[] namespaces = source.GetNamespaces(); NamespaceInfo[] createdNamespaces = new NamespaceInfo[namespaces.Length]; for (int i = 0; i < namespaces.Length; i++) { createdNamespaces[i] = destination.AddNamespace(namespaces[i].Name); } List <NamespaceInfo> sourceNamespaces = new List <NamespaceInfo>(); sourceNamespaces.Add(null); sourceNamespaces.AddRange(namespaces); int currentNamespaceIndex = 0; foreach (NamespaceInfo currentNamespace in sourceNamespaces) { // Load all nav paths now to avoid problems with missing pages from source provider // after the pages have been moved already NavigationPath[] sourceNavPaths = source.GetNavigationPaths(currentNamespace); // Copy categories (removed from source later) CategoryInfo[] sourceCats = source.GetCategories(currentNamespace); for (int i = 0; i < sourceCats.Length; i++) { destination.AddCategory(NameTools.GetNamespace(sourceCats[i].FullName), NameTools.GetLocalName(sourceCats[i].FullName)); } // Move Pages PageInfo[] pages = source.GetPages(currentNamespace); for (int i = 0; i < pages.Length; i++) { // Create Page PageInfo newPage = destination.AddPage(NameTools.GetNamespace(pages[i].FullName), NameTools.GetLocalName(pages[i].FullName), pages[i].CreationDateTime); if (newPage == null) { Log.LogEntry("Unable to move Page " + pages[i].FullName + " - Skipping", EntryType.Error, Log.SystemUsername); continue; } // Get content and store it, without backup PageContent c = source.GetContent(pages[i]); destination.ModifyPage(newPage, c.Title, c.User, c.LastModified, c.Comment, c.Content, c.Keywords, c.Description, SaveMode.Normal); // Move all the backups int[] revs = source.GetBackups(pages[i]); for (int k = 0; k < revs.Length; k++) { c = source.GetBackupContent(pages[i], revs[k]); destination.SetBackupContent(c, revs[k]); } // Move all messages Message[] messages = source.GetMessages(pages[i]); destination.BulkStoreMessages(newPage, messages); // Bind current page (find all proper categories, and use them to bind the page) List <string> pageCats = new List <string>(); for (int k = 0; k < sourceCats.Length; k++) { for (int z = 0; z < sourceCats[k].Pages.Length; z++) { if (sourceCats[k].Pages[z].Equals(newPage.FullName)) { pageCats.Add(sourceCats[k].FullName); break; } } } destination.RebindPage(newPage, pageCats.ToArray()); // Copy draft PageContent draft = source.GetDraft(pages[i]); if (draft != null) { destination.ModifyPage(newPage, draft.Title, draft.User, draft.LastModified, draft.Comment, draft.Content, draft.Keywords, draft.Description, SaveMode.Draft); } // Remove Page from source source.RemovePage(pages[i]); // Also deletes the Messages } // Remove Categories from source for (int i = 0; i < sourceCats.Length; i++) { source.RemoveCategory(sourceCats[i]); } // Move navigation paths List <PageInfo> newPages = new List <PageInfo>(destination.GetPages(currentNamespace == null ? null : createdNamespaces[currentNamespaceIndex])); for (int i = 0; i < sourceNavPaths.Length; i++) { PageInfo[] tmp = new PageInfo[sourceNavPaths[i].Pages.Length]; for (int k = 0; k < tmp.Length; k++) { tmp[k] = newPages.Find(delegate(PageInfo p) { return(p.FullName == sourceNavPaths[i].Pages[k]); }); } destination.AddNavigationPath(NameTools.GetNamespace(sourceNavPaths[i].FullName), NameTools.GetLocalName(sourceNavPaths[i].FullName), tmp); source.RemoveNavigationPath(sourceNavPaths[i]); } if (currentNamespace != null) { // Set default page PageInfo defaultPage = currentNamespace.DefaultPage == null ? null : newPages.Find(delegate(PageInfo p) { return(p.FullName == currentNamespace.DefaultPage.FullName); }); destination.SetNamespaceDefaultPage(createdNamespaces[currentNamespaceIndex], defaultPage); // Remove namespace from source source.RemoveNamespace(currentNamespace); currentNamespaceIndex++; } } }
/// <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) { SearchResultCollection results = null; DateTime begin = DateTime.Now; try { results = SearchTools.Search(query, true, searchFilesAndAttachments, mode); } catch (ArgumentException ex) { Log.LogEntry("Search threw an exception\n" + ex, EntryType.Warning, SessionFacade.CurrentUsername); results = new SearchResultCollection(); } 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(); CategoryInfo[] pageCategories; int count = 0; foreach (SearchResult res in results) { // Filter by category PageInfo currentPage = null; pageCategories = new CategoryInfo[0]; if (res.Document.TypeTag == PageDocument.StandardTypeTag) { currentPage = (res.Document as PageDocument).PageInfo; pageCategories = Pages.GetCategoriesForPage(currentPage); // Verify permissions bool canReadPage = AuthChecker.CheckActionForPage(currentPage, Actions.ForPages.ReadPage, currentUser, currentGroups); if (!canReadPage) { continue; // Skip } } else if (res.Document.TypeTag == MessageDocument.StandardTypeTag) { currentPage = (res.Document as MessageDocument).PageInfo; pageCategories = Pages.GetCategoriesForPage(currentPage); // Verify permissions bool canReadDiscussion = AuthChecker.CheckActionForPage(currentPage, Actions.ForPages.ReadDiscussion, currentUser, currentGroups); if (!canReadDiscussion) { continue; // Skip } } else if (res.Document.TypeTag == PageAttachmentDocument.StandardTypeTag) { currentPage = (res.Document as PageAttachmentDocument).Page; pageCategories = Pages.GetCategoriesForPage(currentPage); // Verify permissions bool canDownloadAttn = AuthChecker.CheckActionForPage(currentPage, Actions.ForPages.DownloadAttachments, currentUser, currentGroups); if (!canDownloadAttn) { continue; // Skip } } else if (res.Document.TypeTag == FileDocument.StandardTypeTag) { string[] fields = ((FileDocument)res.Document).Name.Split('|'); IFilesStorageProviderV30 provider = Collectors.FilesProviderCollector.GetProvider(fields[0]); 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(); PrintStats(end - begin, rows.Count); }
protected void btnSave_Click(object sender, EventArgs e) { bool wasVisible = pnlPageName.Visible; pnlPageName.Visible = true; if (!wasVisible && Settings.GetAutoGeneratePageNames(currentWiki) && txtName.Enabled) { txtName.Text = GenerateAutoName(txtTitle.Text); } txtName.Text = txtName.Text.Trim(); Page.Validate("nametitle"); Page.Validate("captcha"); if (!Page.IsValid) { if (!rfvTitle.IsValid || !rfvName.IsValid || !cvName1.IsValid || !cvName2.IsValid) { pnlPageName.Visible = true; pnlManualName.Visible = false; } return; } pnlPageName.Visible = wasVisible; // Check permissions if (currentPage == null) { // Check permissions for creating new pages if (!canCreateNewPages) { UrlTools.Redirect("AccessDenied.aspx"); } } else { // Check permissions for editing current page if (!canEdit && !canEditWithApproval) { UrlTools.Redirect("AccessDenied.aspx"); } } chkMinorChange.Visible = true; chkSaveAsDraft.Visible = true; // Verify edit with approval if (!canEdit && canEditWithApproval) { chkSaveAsDraft.Checked = true; } // Check for scripts (Administrators can always add SCRIPT tags) if (!SessionFacade.GetCurrentGroupNames(currentWiki).Contains(Settings.GetAdministratorsGroup(currentWiki)) && !Settings.GetScriptTagsAllowed(currentWiki)) { Regex r = new Regex(@"\<script.*?\>", RegexOptions.Compiled | RegexOptions.IgnoreCase); if (r.Match(editor.GetContent()).Success) { lblResult.Text = @"<span style=""color: #FF0000;"">" + Properties.Messages.ScriptDetected + "</span>"; return; } } bool redirect = true; if (sender == btnSaveAndContinue) { redirect = false; } lblResult.Text = ""; lblResult.CssClass = ""; string username = ""; if (SessionFacade.LoginKey == null) { username = Request.UserHostAddress; } else { username = SessionFacade.CurrentUsername; } IPagesStorageProviderV40 provider = FindAppropriateProvider(); // Create list of selected categories List <CategoryInfo> categories = new List <CategoryInfo>(); for (int i = 0; i < lstCategories.Items.Count; i++) { if (lstCategories.Items[i].Selected) { CategoryInfo cat = Pages.FindCategory(currentWiki, lstCategories.Items[i].Value); // Sanity check if (cat.Provider == provider) { categories.Add(cat); } } } txtComment.Text = txtComment.Text.Trim(); txtDescription.Text = txtDescription.Text.Trim(); SaveMode saveMode = SaveMode.Backup; if (chkSaveAsDraft.Checked) { saveMode = SaveMode.Draft; } if (chkMinorChange.Checked) { saveMode = SaveMode.Normal; } if (txtName.Enabled) { // Find page, if inexistent create it Log.LogEntry("Page update requested for " + txtName.Text, EntryType.General, username, currentWiki); string nspace = DetectNamespaceInfo() != null?DetectNamespaceInfo().Name : null; PageContent pg = Pages.FindPage(NameTools.GetFullName(DetectNamespace(), txtName.Text), provider); if (pg == null) { saveMode = SaveMode.Normal; pg = Pages.SetPageContent(currentWiki, nspace, txtName.Text, provider, txtTitle.Text, username, DateTime.UtcNow, txtComment.Text, editor.GetContent(), GetKeywords(), txtDescription.Text, saveMode); attachmentManager.CurrentPage = pg; } else { Pages.SetPageContent(currentWiki, nspace, txtName.Text, provider, txtTitle.Text, username, DateTime.UtcNow, txtComment.Text, editor.GetContent(), GetKeywords(), txtDescription.Text, saveMode); } // Save categories binding Pages.Rebind(pg, categories.ToArray()); // If not a draft, remove page draft if (saveMode != SaveMode.Draft) { Pages.DeleteDraft(pg.FullName, pg.Provider); isDraft = false; } else { isDraft = true; } ManageDraft(); lblResult.CssClass = "resultok"; lblResult.Text = Properties.Messages.PageSaved; // This is a new page, so only who has page management permissions can execute this code // No notification must be sent for drafts awaiting approval if (redirect) { Collisions.CancelEditingSession(pg, username); string target = UrlTools.BuildUrl(currentWiki, Tools.UrlEncode(txtName.Text), GlobalSettings.PageExtension, "?NoRedirect=1"); UrlTools.Redirect(target); } else { // Disable PageName, because the name cannot be changed anymore txtName.Enabled = false; pnlManualName.Visible = false; } } else { // Used for redirecting to a specific section after editing it string anchor = ""; if (currentPage == null) { currentPage = Pages.FindPage(currentWiki, NameTools.GetFullName(DetectNamespace(), txtName.Text)); } // Save data Log.LogEntry("Page update requested for " + currentPage.FullName, EntryType.General, username, currentWiki); if (!isDraft && currentSection != -1) { StringBuilder sb = new StringBuilder(currentPage.Content.Length); int start, len; ExtractSection(currentPage.Content, currentSection, out start, out len, out anchor); if (start > 0) { sb.Append(currentPage.Content.Substring(0, start)); } sb.Append(editor.GetContent()); if (start + len < currentPage.Content.Length - 1) { sb.Append(currentPage.Content.Substring(start + len)); } Pages.SetPageContent(currentPage.Provider.CurrentWiki, NameTools.GetNamespace(currentPage.FullName), NameTools.GetLocalName(currentPage.FullName), txtTitle.Text, username, DateTime.UtcNow, txtComment.Text, sb.ToString(), GetKeywords(), txtDescription.Text, saveMode); } else { Pages.SetPageContent(currentPage.Provider.CurrentWiki, NameTools.GetNamespace(currentPage.FullName), NameTools.GetLocalName(currentPage.FullName), txtTitle.Text, username, DateTime.UtcNow, txtComment.Text, editor.GetContent(), GetKeywords(), txtDescription.Text, saveMode); } // Save Categories binding Pages.Rebind(currentPage, categories.ToArray()); // If not a draft, remove page draft if (saveMode != SaveMode.Draft) { Pages.DeleteDraft(currentPage.FullName, currentPage.Provider); isDraft = false; } else { isDraft = true; } ManageDraft(); lblResult.CssClass = "resultok"; lblResult.Text = Properties.Messages.PageSaved; // This code is executed every time the page is saved, even when "Save & Continue" is clicked // This causes a draft approval notification to be sent multiple times for the same page, // but this is the only solution because the user might navigate away from the page after // clicking "Save & Continue" but not "Save" or "Cancel" - in other words, it is necessary // to take every chance to send a notification because no more chances might be available if (!canEdit && canEditWithApproval) { Pages.SendEmailNotificationForDraft(currentPage.Provider.CurrentWiki, currentPage.FullName, txtTitle.Text, txtComment.Text, username); } if (redirect) { Collisions.CancelEditingSession(currentPage, username); string target = UrlTools.BuildUrl(currentWiki, Tools.UrlEncode(currentPage.FullName), GlobalSettings.PageExtension, "?NoRedirect=1", (!string.IsNullOrEmpty(anchor) ? ("#" + anchor + "_" + currentSection.ToString()) : "")); UrlTools.Redirect(target); } } }
/// <summary> /// Detects the permissions for the current user. /// </summary> /// <remarks><b>currentPage</b> should be set before calling this method.</remarks> private void DetectPermissions() { string currentUser = SessionFacade.GetCurrentUsername(); string[] currentGroups = SessionFacade.GetCurrentGroupNames(currentWiki); AuthChecker authChecker = new AuthChecker(Collectors.CollectorsBox.GetSettingsProvider(currentWiki)); if (currentPage != null) { Pages.CanEditPage(currentPage.Provider.CurrentWiki, currentPage.FullName, currentUser, currentGroups, out canEdit, out canEditWithApproval); canCreateNewPages = false; // Least privilege canCreateNewCategories = authChecker.CheckActionForNamespace(Pages.FindNamespace(currentWiki, NameTools.GetNamespace(currentPage.FullName)), Actions.ForNamespaces.ManageCategories, currentUser, currentGroups); canManagePageCategories = authChecker.CheckActionForPage(currentPage.FullName, Actions.ForPages.ManageCategories, currentUser, currentGroups); canDownloadAttachments = authChecker.CheckActionForPage(currentPage.FullName, Actions.ForPages.DownloadAttachments, currentUser, currentGroups); } else { NamespaceInfo ns = DetectNamespaceInfo(); canCreateNewPages = authChecker.CheckActionForNamespace(ns, Actions.ForNamespaces.CreatePages, currentUser, currentGroups); canCreateNewCategories = authChecker.CheckActionForNamespace(ns, Actions.ForNamespaces.ManageCategories, currentUser, currentGroups); canManagePageCategories = canCreateNewCategories; canDownloadAttachments = authChecker.CheckActionForNamespace(ns, Actions.ForNamespaces.DownloadAttachments, currentUser, currentGroups); } }
/// <summary> /// Detects the permissions for the current user. /// </summary> /// <remarks><b>currentPage</b> should be set before calling this method.</remarks> private void DetectPermissions() { // Sueetie Modified - Bug fix for session expiring and user not known if (!Page.User.Identity.IsAuthenticated) { Response.Redirect("accessdenied.aspx"); return; } MembershipUser _user = Membership.GetUser(); var currentUser = _user.UserName; UserInfo user = Users.FindUser(_user.UserName); if (user == null) { Response.Redirect("/members/message.aspx?msgid=2"); return; } var currentGroups = SessionFacade.GetCurrentGroupNames(); currentGroups = UserGroups(user); if (HttpContext.Current.Session == null) { if (user == null) { user = Users.FindUser(_user.UserName); } SessionFacade.LoginKey = ConfigurationManager.AppSettings["SUEETIE.WikiLoginKey"].ToString(); SessionFacade.CurrentUsername = user.Username; Session["Logout"] = null; Log.LogEntry("User " + user.Username + " auto-logged in through edit bug fix session restart", EntryType.General, "SUEETIE"); } // END - Bug fix for session expiring and user not known if (currentPage != null) { Pages.CanEditPage(currentPage, currentUser, currentGroups, out canEdit, out canEditWithApproval); canCreateNewPages = false; // Least privilege canCreateNewCategories = AuthChecker.CheckActionForNamespace(Pages.FindNamespace(NameTools.GetNamespace(currentPage.FullName)), Actions.ForNamespaces.ManageCategories, currentUser, currentGroups); canManagePageCategories = AuthChecker.CheckActionForPage(currentPage, Actions.ForPages.ManageCategories, currentUser, currentGroups); canDownloadAttachments = AuthChecker.CheckActionForPage(currentPage, Actions.ForPages.DownloadAttachments, currentUser, currentGroups); } else { NamespaceInfo ns = DetectNamespaceInfo(); canCreateNewPages = AuthChecker.CheckActionForNamespace(ns, Actions.ForNamespaces.CreatePages, currentUser, currentGroups); canCreateNewCategories = AuthChecker.CheckActionForNamespace(ns, Actions.ForNamespaces.ManageCategories, currentUser, currentGroups); canManagePageCategories = canCreateNewCategories; canDownloadAttachments = AuthChecker.CheckActionForNamespace(ns, Actions.ForNamespaces.DownloadAttachments, currentUser, currentGroups); } }
protected void btnMigrate_Click(object sender, EventArgs e) { lblMigrateResult.CssClass = ""; lblMigrateResult.Text = ""; string currentUser = SessionFacade.GetCurrentUsername(); string[] currentGroups = SessionFacade.GetCurrentGroupNames(); PageInfo page = Pages.FindPage(txtCurrentPage.Value); NamespaceInfo targetNamespace = Pages.FindNamespace(lstTargetNamespace.SelectedValue); bool canManageAllPages = AuthChecker.CheckActionForNamespace(Pages.FindNamespace(NameTools.GetNamespace(page.FullName)), Actions.ForNamespaces.ManagePages, currentUser, currentGroups); bool canManageAllPagesInTarget = AuthChecker.CheckActionForNamespace(targetNamespace, Actions.ForNamespaces.ManagePages, currentUser, currentGroups); if (canManageAllPages && canManageAllPagesInTarget) { bool done = Pages.MigratePage(page, targetNamespace, chkCopyCategories.Checked); if (done) { chkCopyCategories.Checked = false; ResetPageList(); RefreshList(); lblRenameResult.CssClass = "resultok"; lblRenameResult.Text = Properties.Messages.PageRenamed; ReturnToList(); } else { lblMigrateResult.CssClass = "resulterror"; lblMigrateResult.Text = Properties.Messages.CouldNotMigratePage; } } }
protected void Page_Load(object sender, EventArgs e) { page = Pages.FindPage(Request["Page"]); if (page == null) { UrlTools.RedirectHome(); } // Check permissions bool canView = false; if (Request["Discuss"] == null) { canView = AuthChecker.CheckActionForPage(page, Actions.ForPages.ReadPage, SessionFacade.GetCurrentUsername(), SessionFacade.GetCurrentGroupNames()); } else { canView = AuthChecker.CheckActionForPage(page, Actions.ForPages.ReadDiscussion, SessionFacade.GetCurrentUsername(), SessionFacade.GetCurrentGroupNames()); } if (!canView) { UrlTools.Redirect("AccessDenied.aspx"); } content = Content.GetPageContent(page, true); Literal canonical = new Literal(); canonical.Text = Tools.GetCanonicalUrlTag(Request.Url.ToString(), page, Pages.FindNamespace(NameTools.GetNamespace(page.FullName))); Page.Header.Controls.Add(canonical); Page.Title = FormattingPipeline.PrepareTitle(content.Title, false, FormattingContext.PageContent, page) + " - " + Settings.WikiTitle; PrintContent(); }
protected void Page_Load(object sender, EventArgs e) { discussMode = Request["Discuss"] != null; viewCodeMode = Request["Code"] != null && !discussMode; if (!Settings.EnableViewPageCodeFeature) { viewCodeMode = false; } currentPage = DetectPageInfo(true); VerifyAndPerformRedirects(); // The following actions are verified: // - View content (redirect to AccessDenied) // - Edit or Edit with Approval (for button display) // - Any Administrative activity (Rollback/Admin/Perms) (for button display) // - Download attachments (for button display - download permissions are also checked in GetFile) // - View discussion (for button display in content mode) // - Post discussion (for button display in discuss mode) string currentUsername = SessionFacade.GetCurrentUsername(); string[] currentGroups = SessionFacade.GetCurrentGroupNames(); bool canView = AuthChecker.CheckActionForPage(currentPage, Actions.ForPages.ReadPage, currentUsername, currentGroups); bool canEdit = false; bool canEditWithApproval = false; Pages.CanEditPage(currentPage, currentUsername, currentGroups, out canEdit, out canEditWithApproval); if (canEditWithApproval && canEdit) { canEditWithApproval = false; } bool canDownloadAttachments = AuthChecker.CheckActionForPage(currentPage, Actions.ForPages.DownloadAttachments, currentUsername, currentGroups); bool canSetPerms = AuthChecker.CheckActionForGlobals(Actions.ForGlobals.ManagePermissions, currentUsername, currentGroups); bool canAdmin = AuthChecker.CheckActionForPage(currentPage, Actions.ForPages.ManagePage, currentUsername, currentGroups); bool canViewDiscussion = AuthChecker.CheckActionForPage(currentPage, Actions.ForPages.ReadDiscussion, currentUsername, currentGroups); bool canPostDiscussion = AuthChecker.CheckActionForPage(currentPage, Actions.ForPages.PostDiscussion, currentUsername, currentGroups); bool canManageDiscussion = AuthChecker.CheckActionForPage(currentPage, Actions.ForPages.ManageDiscussion, currentUsername, currentGroups); if (!canView) { if (SessionFacade.LoginKey == null) { UrlTools.Redirect("Login.aspx?Redirect=" + Tools.UrlEncode(Tools.GetCurrentUrlFixed())); } else { UrlTools.Redirect(UrlTools.BuildUrl("AccessDenied.aspx")); } } attachmentViewer.Visible = canDownloadAttachments; attachmentViewer.PageInfo = currentPage; currentContent = Content.GetPageContent(currentPage, true); pnlPageInfo.Visible = Settings.EnablePageInfoDiv; SetupTitles(); SetupToolbarLinks(canEdit || canEditWithApproval, canViewDiscussion, canPostDiscussion, canDownloadAttachments, canAdmin, canAdmin, canSetPerms); SetupLabels(); SetupPrintAndRssLinks(); SetupMetaInformation(); VerifyAndPerformPageRedirection(); SetupRedirectionSource(); SetupNavigationPaths(); SetupAdjacentPages(); SessionFacade.Breadcrumbs.AddPage(currentPage); SetupBreadcrumbsTrail(); SetupDoubleClickHandler(); SetupEmailNotification(); SetupPageContent(canPostDiscussion, canManageDiscussion); if (currentPage != null) { Literal canonical = new Literal(); canonical.Text = Tools.GetCanonicalUrlTag(Request.Url.ToString(), currentPage, Pages.FindNamespace(NameTools.GetNamespace(currentPage.FullName))); Page.Header.Controls.Add(canonical); } }
protected void btnRename_Click(object sender, EventArgs e) { // Check name for change, validity and existence of another page with same name // Perform rename // Create shadow page, if needed PageInfo page = Pages.FindPage(txtCurrentPage.Value); if (!AuthChecker.CheckActionForNamespace(Pages.FindNamespace(NameTools.GetNamespace(page.FullName)), Actions.ForNamespaces.DeletePages, SessionFacade.GetCurrentUsername(), SessionFacade.GetCurrentGroupNames())) { return; } txtNewName.Text = txtNewName.Text.Trim(); string currentNamespace = NameTools.GetNamespace(txtCurrentPage.Value); string currentPage = NameTools.GetLocalName(txtCurrentPage.Value); if (!Page.IsValid) { return; } if (txtNewName.Text.ToLowerInvariant() == currentPage.ToLowerInvariant()) { return; } if (Pages.FindPage(NameTools.GetFullName(currentNamespace, txtNewName.Text)) != null) { lblRenameResult.CssClass = "resulterror"; lblRenameResult.Text = Properties.Messages.PageAlreadyExists; return; } Log.LogEntry("Page rename requested for " + txtCurrentPage.Value, EntryType.General, Log.SystemUsername); PageInfo oldPage = Pages.FindPage(txtCurrentPage.Value); PageContent oldContent = Content.GetPageContent(oldPage, false); bool done = Pages.RenamePage(oldPage, txtNewName.Text); if (done) { if (chkShadowPage.Checked) { done = Pages.CreatePage(currentNamespace, currentPage); if (done) { done = Pages.ModifyPage(Pages.FindPage(txtCurrentPage.Value), oldContent.Title, oldContent.User, oldContent.LastModified, oldContent.Comment, ">>> [" + txtNewName.Text + "]", new string[0], oldContent.Description, SaveMode.Normal); if (done) { ResetPageList(); RefreshList(); lblRenameResult.CssClass = "resultok"; lblRenameResult.Text = Properties.Messages.PageRenamed; ReturnToList(); } else { lblRenameResult.CssClass = "resulterror"; lblRenameResult.Text = Properties.Messages.PageRenamedCouldNotSetShadowPageContent; } } else { lblRenameResult.CssClass = "resulterror"; lblRenameResult.Text = Properties.Messages.PageRenamedCouldNotCreateShadowPage; } } else { RefreshList(); lblRenameResult.CssClass = "resultok"; lblRenameResult.Text = Properties.Messages.PageRenamed; ReturnToList(); } } else { lblRenameResult.CssClass = "resulterror"; lblRenameResult.Text = Properties.Messages.CouldNotRenamePage; } }
protected void btnApprove_Click(object sender, EventArgs e) { PageContent page = Pages.FindPage(currentWiki, txtCurrentPage.Value); if (!AdminMaster.CanApproveDraft(page.Provider.CurrentWiki, page.FullName, SessionFacade.GetCurrentUsername(), SessionFacade.GetCurrentGroupNames(currentWiki))) { return; } PageContent draft = Pages.GetDraft(page); Log.LogEntry("Page draft approval requested for " + draft.FullName, EntryType.General, SessionFacade.CurrentUsername, currentWiki); PageContent newPageContent = Pages.SetPageContent(draft.Provider.CurrentWiki, NameTools.GetNamespace(draft.FullName), NameTools.GetLocalName(draft.FullName), draft.Title, draft.User, draft.LastModified, draft.Comment, draft.Content, draft.Keywords, draft.Description, SaveMode.Backup); if (newPageContent != null) { Pages.DeleteDraft(draft.FullName, draft.Provider); lblApproveResult.CssClass = "resultok"; lblApproveResult.Text = Properties.Messages.DraftApproved; lblDraftPreview.Text = ""; ReturnToList(); } else { lblApproveResult.CssClass = "resulterror"; lblApproveResult.Text = Properties.Messages.CouldNotApproveDraft; } }
protected void Page_Load(object sender, EventArgs e) { rssFeedsMode = Settings.RssFeedsMode; if (rssFeedsMode == RssFeedsMode.Disabled) { Response.Clear(); Response.StatusCode = 404; Response.End(); return; } string currentUsername = SessionFacade.GetCurrentUsername(); string[] currentGroups = SessionFacade.GetCurrentGroupNames(); currentNamespace = DetectNamespace(); if (string.IsNullOrEmpty(currentNamespace)) { currentNamespace = null; } if (SessionFacade.LoginKey == null) { // Look for username/password in the query string if (Request["Username"] != null && Request["Password"] != null) { // Try to authenticate UserInfo u = Users.FindUser(Request["Username"]); if (u != null) { // Very "dirty" way - pages should not access Providers if (u.Provider.TestAccount(u, Request["Password"])) { // Valid account currentUsername = Request["Username"]; currentGroups = Users.FindUser(currentUsername).Groups; } } else { // Check for built-in admin account if (Request["Username"].Equals("admin") && Request["Password"].Equals(Settings.MasterPassword)) { currentUsername = "******"; currentGroups = new string[] { Settings.AdministratorsGroup }; } } } } Response.ClearContent(); Response.ContentType = "text/xml;charset=UTF-8"; Response.ContentEncoding = System.Text.UTF8Encoding.UTF8; if (Request["Page"] != null) { PageInfo page = Pages.FindPage(Request["Page"]); if (page == null) { return; } PageContent content = Content.GetPageContent(page, true); if (Request["Discuss"] == null) { // Check permission for the page bool canReadPage = AuthChecker.CheckActionForPage(page, Actions.ForPages.ReadPage, currentUsername, currentGroups); if (!canReadPage) { Response.StatusCode = 401; return; } // Start an XML writer for the output stream using (XmlWriter rss = XmlWriter.Create(Response.OutputStream)) { // Build an RSS header BuildRssHeader(rss); // Build the channel element BuildChannelHead(rss, Settings.WikiTitle + " - " + Formatter.StripHtml(FormattingPipeline.PrepareTitle(content.Title, false, FormattingContext.PageContent, page)), Settings.MainUrl + page.FullName + Settings.PageExtension, Settings.MainUrl + UrlTools.BuildUrl("RSS.aspx?Page=", page.FullName), Formatter.StripHtml(content.Title) + " - " + Properties.Messages.PageUpdates); // Write the item element rss.WriteStartElement("item"); rss.WriteStartElement("title"); rss.WriteCData(Formatter.StripHtml(FormattingPipeline.PrepareTitle(content.Title, false, FormattingContext.PageContent, page))); rss.WriteEndElement(); rss.WriteElementString("link", Settings.MainUrl + page.FullName + Settings.PageExtension); UserInfo user = Users.FindUser(content.User); string username = user != null?Users.GetDisplayName(user) : content.User; // Create the description tag rss.WriteStartElement("description"); if (rssFeedsMode == RssFeedsMode.Summary) { rss.WriteCData(Formatter.StripHtml(content.Title) + ": " + Properties.Messages.ThePageHasBeenUpdatedBy + " " + username + (content.Comment.Length > 0 ? ".<br />" + content.Comment : ".")); } else { rss.WriteCData(Content.GetFormattedPageContent(page, false)); } rss.WriteEndElement(); // Write the remaining elements rss.WriteElementString("author", username); rss.WriteElementString("pubDate", content.LastModified.ToUniversalTime().ToString("R")); rss.WriteStartElement("guid"); rss.WriteAttributeString("isPermaLink", "false"); rss.WriteString(GetGuid(page.FullName, content.LastModified)); rss.WriteEndElement(); // Complete the item element CompleteCurrentElement(rss); // Complete the channel element CompleteCurrentElement(rss); // Complete the rss element CompleteCurrentElement(rss); // Finish off rss.Flush(); rss.Close(); } } else { // Check permission for the discussion bool canReadDiscussion = AuthChecker.CheckActionForPage(page, Actions.ForPages.ReadDiscussion, currentUsername, currentGroups); if (!canReadDiscussion) { Response.StatusCode = 401; return; } List <Message> messages = new List <Message>(Pages.GetPageMessages(page)); // Un-tree Messages messages = UnTreeMessages(messages); // Sort from newer to older messages.Sort(new MessageDateTimeComparer(true)); // Start an XML writer for the output stream using (XmlWriter rss = XmlWriter.Create(Response.OutputStream)) { // Build an RSS header BuildRssHeader(rss); // Build the channel element BuildChannelHead(rss, Settings.WikiTitle + " - " + Formatter.StripHtml(FormattingPipeline.PrepareTitle(content.Title, false, FormattingContext.PageContent, page)) + " - Discussion Updates", Settings.MainUrl + page.FullName + Settings.PageExtension + "?Discuss=1", Settings.MainUrl + UrlTools.BuildUrl("RSS.aspx?Page=", page.FullName, "&Discuss=1"), Settings.WikiTitle + " - " + Formatter.StripHtml(FormattingPipeline.PrepareTitle(content.Title, false, FormattingContext.PageContent, page)) + " - Discussion Updates"); for (int i = 0; i < messages.Count; i++) { // Write the item element rss.WriteStartElement("item"); rss.WriteStartElement("title"); rss.WriteCData(Formatter.StripHtml(FormattingPipeline.PrepareTitle(messages[i].Subject, false, FormattingContext.MessageBody, page))); rss.WriteEndElement(); rss.WriteElementString("link", Settings.MainUrl + page.FullName + Settings.PageExtension + "?Discuss=1"); UserInfo user = Users.FindUser(messages[i].Username); string username = user != null?Users.GetDisplayName(user) : messages[i].Username; // Create the description tag rss.WriteStartElement("description"); if (rssFeedsMode == RssFeedsMode.Summary) { rss.WriteCData(Properties.Messages.AMessageHasBeenPostedBy.Replace("##SUBJECT##", messages[i].Subject) + " " + username + "."); } else { rss.WriteCData(FormattingPipeline.FormatWithPhase3(FormattingPipeline.FormatWithPhase1And2(messages[i].Body, false, FormattingContext.MessageBody, page), FormattingContext.MessageBody, page)); } rss.WriteEndElement(); // Write the remaining elements rss.WriteElementString("author", username); rss.WriteElementString("pubDate", messages[i].DateTime.ToUniversalTime().ToString("R")); rss.WriteStartElement("guid"); rss.WriteAttributeString("isPermaLink", "false"); rss.WriteString(GetGuid(page.FullName + "-" + messages[i].ID, messages[i].DateTime)); rss.WriteEndElement(); // Complete the item element CompleteCurrentElement(rss); } // Complete the channel element CompleteCurrentElement(rss); // Complete the rss element CompleteCurrentElement(rss); // Finish off rss.Flush(); rss.Close(); } } } else { if (Request["Discuss"] == null) { // All page updates // Start an XML writer for the output stream using (XmlWriter rss = XmlWriter.Create(Response.OutputStream)) { // Build an RSS header BuildRssHeader(rss); bool useCat = false; string cat = ""; if (Request["Category"] != null) { useCat = true; cat = Request["Category"]; } // Build the channel element BuildChannelHead(rss, Settings.WikiTitle + " - " + Properties.Messages.PageUpdates, Settings.MainUrl, Settings.MainUrl + UrlTools.BuildUrl("RSS.aspx", (useCat ? ("?Category=" + cat) : "")), Properties.Messages.RecentPageUpdates); RecentChange[] ch = RecentChanges.GetAllChanges(); Array.Reverse(ch); for (int i = 0; i < ch.Length; i++) { // Suppress this entry if we've already reported this page (so we don't create duplicate entries in the feed page) bool duplicateFound = false; for (int j = 0; j < i; j++) { if (ch[j].Page == ch[i].Page) { duplicateFound = true; break; } } if (duplicateFound) { continue; } // Skip message-related entries if (!IsPageChange(ch[i].Change)) { continue; } PageInfo p = Pages.FindPage(ch[i].Page); if (p != null) { // Check permissions for every page bool canReadThisPage = AuthChecker.CheckActionForPage(p, Actions.ForPages.ReadPage, currentUsername, currentGroups); if (!canReadThisPage) { continue; } if (useCat) { CategoryInfo[] infos = Pages.GetCategoriesForPage(p); if (infos.Length == 0 && cat != "-") { continue; } if (infos.Length != 0) { bool found = false; for (int k = 0; k < infos.Length; k++) { if (infos[k].FullName == cat) { found = true; break; } } if (!found) { continue; } } } } // Check namespace if (p != null && NameTools.GetNamespace(p.FullName) != currentNamespace) { continue; } // Skip deleted pages as their category binding is unknown if (p == null && useCat) { continue; } // Write the item element rss.WriteStartElement("item"); rss.WriteStartElement("title"); rss.WriteCData(Formatter.StripHtml(FormattingPipeline.PrepareTitle(ch[i].Title, false, FormattingContext.PageContent, p))); rss.WriteEndElement(); if (ch[i].Change != Change.PageDeleted && p != null) { rss.WriteElementString("link", Settings.MainUrl + ch[i].Page + Settings.PageExtension); } else { rss.WriteElementString("link", Settings.MainUrl); } UserInfo user = Users.FindUser(ch[i].User); string username = user != null?Users.GetDisplayName(user) : ch[i].User; rss.WriteElementString("author", username); // Create the description tag StringBuilder sb = new StringBuilder(); if (rssFeedsMode == RssFeedsMode.Summary || p == null) { switch (ch[i].Change) { case Change.PageUpdated: sb.Append(Properties.Messages.ThePageHasBeenUpdatedBy); break; case Change.PageDeleted: sb.Append(Properties.Messages.ThePageHasBeenDeletedBy); break; case Change.PageRenamed: sb.Append(Properties.Messages.ThePageHasBeenRenamedBy); break; case Change.PageRolledBack: sb.Append(Properties.Messages.ThePageHasBeenRolledBackBy); break; } sb.Append(" " + username + (ch[i].Description.Length > 0 ? ".<br />" + ch[i].Description : ".")); } else { // p != null sb.Append(Content.GetFormattedPageContent(p, false)); } rss.WriteStartElement("description"); rss.WriteCData(sb.ToString()); rss.WriteEndElement(); // Write the remaining elements rss.WriteElementString("pubDate", ch[i].DateTime.ToUniversalTime().ToString("R")); rss.WriteStartElement("guid"); rss.WriteAttributeString("isPermaLink", "false"); rss.WriteString(GetGuid(ch[i].Page, ch[i].DateTime)); rss.WriteEndElement(); // Complete the item element rss.WriteEndElement(); } // Complete the channel element CompleteCurrentElement(rss); // Complete the rss element CompleteCurrentElement(rss); // Finish off rss.Flush(); rss.Close(); } } else { // All discussion updates // Start an XML writer for the output stream using (XmlWriter rss = XmlWriter.Create(Response.OutputStream)) { // Build an RSS header BuildRssHeader(rss); bool useCat = false; string cat = ""; if (Request["Category"] != null) { useCat = true; cat = Request["Category"]; } // Build the channel element BuildChannelHead(rss, Settings.WikiTitle + " - " + Properties.Messages.DiscussionUpdates, Settings.MainUrl, Settings.MainUrl + UrlTools.BuildUrl("RSS.aspx", (useCat ? ("?Category=" + cat) : "")), Properties.Messages.RecentDiscussionUpdates); RecentChange[] ch = RecentChanges.GetAllChanges(); Array.Reverse(ch); for (int i = 0; i < ch.Length; i++) { // Skip page-related entries if (!IsMessageChange(ch[i].Change)) { continue; } PageInfo p = Pages.FindPage(ch[i].Page); if (p != null) { // Check permissions for every page bool canReadThisPageDiscussion = AuthChecker.CheckActionForPage(p, Actions.ForPages.ReadDiscussion, currentUsername, currentGroups); if (!canReadThisPageDiscussion) { continue; } if (useCat) { CategoryInfo[] infos = Pages.GetCategoriesForPage(p); if (infos.Length == 0 && cat != "-") { continue; } if (infos.Length != 0) { bool found = false; for (int k = 0; k < infos.Length; k++) { if (infos[k].FullName == cat) { found = true; break; } } if (!found) { continue; } } } // Check namespace if (NameTools.GetNamespace(p.FullName) != currentNamespace) { continue; } // Write the item element rss.WriteStartElement("item"); rss.WriteStartElement("title"); rss.WriteCData(Properties.Messages.Discussion + ": " + Formatter.StripHtml(FormattingPipeline.PrepareTitle(ch[i].Title, false, FormattingContext.PageContent, p))); rss.WriteEndElement(); string id = Tools.GetMessageIdForAnchor(ch[i].DateTime); if (ch[i].Change != Change.MessageDeleted) { rss.WriteElementString("link", Settings.MainUrl + ch[i].Page + Settings.PageExtension + "?Discuss=1#" + id); } else { rss.WriteElementString("link", Settings.MainUrl + ch[i].Page + Settings.PageExtension + "?Discuss=1"); } string messageContent = FindMessageContent(ch[i].Page, id); UserInfo user = Users.FindUser(ch[i].User); string username = user != null?Users.GetDisplayName(user) : ch[i].User; // Create the description tag StringBuilder sb = new StringBuilder(); if (rssFeedsMode == RssFeedsMode.Summary || messageContent == null) { switch (ch[i].Change) { case Change.MessagePosted: sb.Append(Properties.Messages.AMessageHasBeenPostedBy.Replace("##SUBJECT##", ch[i].MessageSubject)); break; case Change.MessageEdited: sb.Append(Properties.Messages.AMessageHasBeenEditedBy.Replace("##SUBJECT##", ch[i].MessageSubject)); break; case Change.MessageDeleted: sb.Append(Properties.Messages.AMessageHasBeenDeletedBy.Replace("##SUBJECT##", ch[i].MessageSubject)); break; } sb.Append(" " + username + (ch[i].Description.Length > 0 ? ".<br />" + ch[i].Description : ".")); } else { sb.Append(FormattingPipeline.FormatWithPhase3(FormattingPipeline.FormatWithPhase1And2(messageContent, false, FormattingContext.MessageBody, null), FormattingContext.MessageBody, null)); } rss.WriteStartElement("description"); rss.WriteCData(sb.ToString()); rss.WriteEndElement(); // Write the remaining elements rss.WriteElementString("author", username); rss.WriteElementString("pubDate", ch[i].DateTime.ToUniversalTime().ToString("R")); rss.WriteStartElement("guid"); rss.WriteAttributeString("isPermaLink", "false"); rss.WriteString(GetGuid(ch[i].Page, ch[i].DateTime)); rss.WriteEndElement(); // Complete the item element rss.WriteEndElement(); } } // Complete the channel element CompleteCurrentElement(rss); // Complete the rss element CompleteCurrentElement(rss); // Finish off rss.Flush(); rss.Close(); } } } }
/// <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(); }