CheckActionForPage() публичный статический Метод

Checks whether an action is allowed for a page.
public static CheckActionForPage ( System.PageInfo page, string action, string currentUser, string groups ) : bool
page System.PageInfo The current page.
action string The action the user is attempting to perform.
currentUser string The current user.
groups string The groups the user is member of.
Результат bool
Пример #1
0
        /// <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();
        }
Пример #2
0
        /// <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);
            }
        }
Пример #3
0
        protected void rptPages_DataBinding(object sender, EventArgs e)
        {
            NamespaceInfo nspace = Pages.FindNamespace(currentWiki, lstNamespace.SelectedValue);

            if (currentPages == null)
            {
                currentPages = GetPages(nspace);
            }

            List <PageRow> result = new List <PageRow>(PageSize);

            string currentUser = SessionFacade.GetCurrentUsername();

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

            AuthChecker authChecker       = new AuthChecker(Collectors.CollectorsBox.GetSettingsProvider(currentWiki));
            bool        canSetPermissions = AdminMaster.CanManagePermissions(currentUser, currentGroups);
            bool        canDeletePages    = authChecker.CheckActionForNamespace(nspace, Actions.ForNamespaces.DeletePages, currentUser, currentGroups);

            var orphanPages = new List <string>(Pages.GetOrphanedPages(currentWiki, nspace));

            for (int i = rangeBegin; i <= rangeEnd; i++)
            {
                PageContent page = currentPages[i];

                // The page can be selected if the user can either manage or delete the page or manage the discussion
                // Repeat checks for enabling/disabling sections when a page is selected
                bool canEdit             = authChecker.CheckActionForPage(page.FullName, Actions.ForPages.ModifyPage, currentUser, currentGroups);
                bool canManagePage       = false;
                bool canManageDiscussion = false;
                if (!canDeletePages)
                {
                    canManagePage = authChecker.CheckActionForPage(page.FullName, Actions.ForPages.ManagePage, currentUser, currentGroups);
                }
                if (!canDeletePages && !canManagePage)
                {
                    canManageDiscussion = authChecker.CheckActionForPage(page.FullName, Actions.ForPages.ManageDiscussion, currentUser, currentGroups);
                }
                bool canSelect = canManagePage | canDeletePages | canManageDiscussion;

                PageContent firstContent = null;
                List <int>  baks         = Pages.GetBackups(page);
                if (baks.Count == 0)
                {
                    firstContent = page;
                }
                else
                {
                    firstContent = Pages.GetBackupContent(page, baks[0]);
                }

                result.Add(new PageRow(page, firstContent,
                                       Pages.GetMessageCount(page), baks.Count, orphanPages.Contains(page.FullName),
                                       canEdit, canSelect, canSetPermissions, txtCurrentPage.Value == page.FullName));
            }

            rptPages.DataSource = result;
        }
Пример #4
0
        protected void Page_Load(object sender, EventArgs e)
        {
            string currentWiki = Tools.DetectCurrentWiki();

            Response.ClearContent();
            Response.ContentType     = "text/xml;charset=UTF-8";
            Response.ContentEncoding = System.Text.UTF8Encoding.UTF8;

            string mainUrl     = Settings.GetMainUrl(currentWiki);
            string rootDefault = Settings.GetDefaultPage(currentWiki).ToLowerInvariant();

            using (XmlWriter writer = XmlWriter.Create(Response.OutputStream)) {
                writer.WriteStartDocument();

                writer.WriteStartElement("urlset", "http://www.sitemaps.org/schemas/sitemap/0.9");
                writer.WriteAttributeString("xmlns", "xsi", null, "http://www.w3.org/2001/XMLSchema-instance");
                writer.WriteAttributeString("xsi", "schemaLocation", null, "http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/09/sitemap.xsd");

                string   user   = SessionFacade.GetCurrentUsername();
                string[] groups = SessionFacade.GetCurrentGroupNames(currentWiki);


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

                foreach (PageContent page in Pages.GetPages(currentWiki, null))
                {
                    if (authChecker.CheckActionForPage(page.FullName, Actions.ForPages.ReadPage, user, groups))
                    {
                        WritePage(mainUrl, page.FullName, page.FullName.ToLowerInvariant() == rootDefault, writer);
                    }
                }
                foreach (NamespaceInfo nspace in Pages.GetNamespaces(currentWiki))
                {
                    string nspaceDefault = nspace.DefaultPageFullName.ToLowerInvariant();

                    foreach (PageContent page in Pages.GetPages(currentWiki, nspace))
                    {
                        if (authChecker.CheckActionForPage(page.FullName, Actions.ForPages.ReadPage, user, groups))
                        {
                            WritePage(mainUrl, page.FullName, page.FullName.ToLowerInvariant() == nspaceDefault, writer);
                        }
                    }
                }

                writer.WriteEndElement();
                writer.WriteEndDocument();
            }
        }
Пример #5
0
        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);

            Page.Title = FormattingPipeline.PrepareTitle(content.Title, false, FormattingContext.PageContent, page) + " - " + Settings.WikiTitle;

            PrintContent();
        }
Пример #6
0
        protected void Page_Load(object sender, EventArgs e)
        {
            this.Page.Title = Properties.Messages.PageIncomingLinks + " - " + Settings.WikiTitle;

            var page = Pages.FindPage(Request["Page"]);

            PageContent content;

            if (page != null)
            {
                content = Content.GetPageContent(page, true);

                lblTitle.Text = Properties.Messages.PageIncomingLinks + ": " + FormattingPipeline.PrepareTitle(content.Title, false, FormattingContext.PageContent, page);

                if (!AuthChecker.CheckActionForPage(page, Actions.ForPages.ReadPage, SessionFacade.GetCurrentUsername(), SessionFacade.GetCurrentGroupNames()))
                {
                    UrlTools.Redirect("AccessDenied.aspx");
                    return;
                }
            }

            var incomingLinks = Pages.GetPageIncomingLinks(page);

            foreach (var link in incomingLinks)
            {
                var linkPage        = Pages.FindPage(link);
                var linkPageContent = linkPage.Provider.GetContent(linkPage);
                ulItems.InnerHtml += string.Format("<li><a href=\"{0}\">{1}</a></li>", UrlTools.BuildUrl(Tools.UrlEncode(link), Settings.PageExtension), linkPageContent.Title);
            }
        }
Пример #7
0
        protected void btnRollback_Click(object sender, EventArgs e)
        {
            PageInfo page = Pages.FindPage(txtCurrentPage.Value);

            if (!AuthChecker.CheckActionForPage(page, Actions.ForPages.ManagePage, SessionFacade.GetCurrentUsername(), SessionFacade.GetCurrentGroupNames()))
            {
                return;
            }

            int targetRevision = -1;

            // This should never occur
            if (!int.TryParse(lstRevision.SelectedValue, out targetRevision))
            {
                return;
            }

            Log.LogEntry("Page rollback requested for " + txtCurrentPage.Value + " to rev. " + targetRevision.ToString(), EntryType.General, Log.SystemUsername);

            bool done = Pages.Rollback(page, targetRevision);

            if (done)
            {
                RefreshList();
                lblRollbackResult.CssClass = "resultok";
                lblRollbackResult.Text     = Properties.Messages.PageRolledBack;
                ReturnToList();
            }
            else
            {
                lblRollbackResult.CssClass = "resulterror";
                lblRollbackResult.Text     = Properties.Messages.CouldNotRollbackPage;
            }
        }
Пример #8
0
        protected void Page_Load(object sender, EventArgs e)
        {
            Page.Title = Properties.Messages.HistoryTitle + " - " + Settings.WikiTitle;

            page = Pages.FindPage(Request["Page"]);

            if (page != null)
            {
                canRollback = AuthChecker.CheckActionForPage(page, Actions.ForPages.ManagePage,
                                                             SessionFacade.GetCurrentUsername(), SessionFacade.GetCurrentGroupNames());

                content       = Content.GetPageContent(page, true);
                lblTitle.Text = Properties.Messages.PageHistory + ": " + FormattingPipeline.PrepareTitle(content.Title, false, FormattingContext.PageContent, page);

                bool canView = AuthChecker.CheckActionForPage(page, Actions.ForPages.ReadPage,
                                                              SessionFacade.GetCurrentUsername(), SessionFacade.GetCurrentGroupNames());
                if (!canView)
                {
                    UrlTools.Redirect("AccessDenied.aspx");
                }
            }
            else
            {
                lblTitle.Text = Properties.Messages.PageNotFound;
                return;
            }

            if (!Page.IsPostBack && page != null)
            {
                List <int> revisions = Pages.GetBackups(page);
                revisions.Reverse();
                // Populate dropdown lists
                lstRev1.Items.Clear();
                lstRev2.Items.Clear();
                lstRev2.Items.Add(new ListItem(Properties.Messages.Current, "Current"));
                if (Request["Rev2"] != null && Request["Rev2"].Equals(lstRev2.Items[0].Value))
                {
                    lstRev2.SelectedIndex = 0;
                }
                for (int i = 0; i < revisions.Count; i++)
                {
                    lstRev1.Items.Add(new ListItem(revisions[i].ToString(), revisions[i].ToString()));
                    lstRev2.Items.Add(new ListItem(revisions[i].ToString(), revisions[i].ToString()));
                    if (Request["Rev1"] != null && Request["Rev1"].Equals(lstRev1.Items[i].Value))
                    {
                        lstRev1.SelectedIndex = i;
                    }
                    if (Request["Rev2"] != null && Request["Rev2"].Equals(lstRev2.Items[i + 1].Value))
                    {
                        lstRev2.SelectedIndex = i + 1;
                    }
                }
                if (revisions.Count == 0)
                {
                    btnCompare.Enabled = false;
                }
            }

            PrintHistory();
        }
Пример #9
0
        protected void btnClearDiscussion_Click(object sender, EventArgs e)
        {
            PageInfo page = Pages.FindPage(txtCurrentPage.Value);

            if (!AuthChecker.CheckActionForPage(page, Actions.ForPages.ManageDiscussion, SessionFacade.GetCurrentUsername(), SessionFacade.GetCurrentGroupNames()))
            {
                return;
            }

            Log.LogEntry("Page discussion cleanup requested for " + txtCurrentPage.Value, EntryType.General, Log.SystemUsername);

            bool done = Pages.RemoveAllMessages(page);

            if (done)
            {
                RefreshList();
                lblDiscussionResult.CssClass = "resultok";
                lblDiscussionResult.Text     = Properties.Messages.AllMessagesDeleted;
                ReturnToList();
            }
            else
            {
                lblDiscussionResult.CssClass = "resulterror";
                lblDiscussionResult.Text     = Properties.Messages.CouldNotDeleteOneOrMoreMessages;
            }
        }
Пример #10
0
        protected void rptPages_DataBinding(object sender, EventArgs e)
        {
            if (currentPages == null)
            {
                currentPages = GetPages();
            }
            NamespaceInfo nspace = DetectNamespaceInfo();

            var result = new List <PageRow>(PageSize);

            var currentUser   = SessionFacade.GetCurrentUsername();
            var currentGroups = SessionFacade.GetCurrentGroupNames();

            var canSetPermissions = AdminMaster.CanManagePermissions(currentUser, currentGroups);
            var canDeletePages    = AuthChecker.CheckActionForNamespace(nspace, Actions.ForNamespaces.DeletePages, currentUser, currentGroups);

            var orphanPages = Pages.GetOrphanedPages(currentPages);

            for (var i = rangeBegin; i <= rangeEnd; i++)
            {
                PageInfo page = currentPages[i];

                PageContent currentContent = Content.GetPageContent(page, false);

                // The page can be selected if the user can either manage or delete the page or manage the discussion
                // Repeat checks for enabling/disabling sections when a page is selected
                var canEdit             = AuthChecker.CheckActionForPage(page, Actions.ForPages.ModifyPage, currentUser, currentGroups);
                var canManagePage       = false;
                var canManageDiscussion = false;
                if (!canDeletePages)
                {
                    canManagePage = AuthChecker.CheckActionForPage(page, Actions.ForPages.ManagePage, currentUser, currentGroups);
                }
                if (!canDeletePages && !canManagePage)
                {
                    canManageDiscussion = AuthChecker.CheckActionForPage(page, Actions.ForPages.ManageDiscussion, currentUser, currentGroups);
                }
                var canSelect = canManagePage | canDeletePages | canManageDiscussion;

                PageContent firstContent = null;
                List <int>  baks         = Pages.GetBackups(page);
                if (baks.Count == 0)
                {
                    firstContent = currentContent;
                }
                else
                {
                    firstContent = Pages.GetBackupContent(page, baks[0]);
                }

                result.Add(new PageRow(page, currentContent, firstContent,
                                       Pages.GetMessageCount(page), baks.Count, orphanPages.Contains(page.FullName),
                                       canEdit, canSelect, canSetPermissions, txtCurrentPage.Value == page.FullName));
            }

            rptPages.DataSource = result;
        }
Пример #11
0
        /// <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);
            }
        }
Пример #12
0
 /// <summary>
 /// Detects the permissions of the current user.
 /// </summary>
 private void DetectPermissions()
 {
     if (CurrentPage != null)
     {
         string      currentWiki   = Tools.DetectCurrentWiki();
         string      currentUser   = SessionFacade.GetCurrentUsername();
         string[]    currentGroups = SessionFacade.GetCurrentGroupNames(currentWiki);
         AuthChecker authChecker   = new AuthChecker(Collectors.CollectorsBox.GetSettingsProvider(currentWiki));
         canDownload = authChecker.CheckActionForPage(CurrentPage.FullName, Actions.ForPages.DownloadAttachments, currentUser, currentGroups);
         canUpload   = authChecker.CheckActionForPage(CurrentPage.FullName, Actions.ForPages.UploadAttachments, currentUser, currentGroups);
         canDelete   = authChecker.CheckActionForPage(CurrentPage.FullName, Actions.ForPages.DeleteAttachments, currentUser, currentGroups);
         isAdmin     = Array.Find(currentGroups, delegate(string g) { return(g == Settings.GetAdministratorsGroup(currentWiki)); }) != null;
     }
     else
     {
         canDownload = false;
         canUpload   = false;
         canDelete   = false;
         isAdmin     = false;
     }
     lstProviders.Visible = isAdmin;
 }
Пример #13
0
        protected void Page_Load(object sender, EventArgs e)
        {
            currentWiki = DetectWiki();

            page = Pages.FindPage(currentWiki, Request["Page"]);
            if (page == null)
            {
                UrlTools.RedirectHome(currentWiki);
            }

            // Check permissions
            bool        canView     = false;
            AuthChecker authChecker = new AuthChecker(Collectors.CollectorsBox.GetSettingsProvider(currentWiki));

            if (Request["Discuss"] == null)
            {
                canView = authChecker.CheckActionForPage(page.FullName, Actions.ForPages.ReadPage,
                                                         SessionFacade.GetCurrentUsername(), SessionFacade.GetCurrentGroupNames(currentWiki));
            }
            else
            {
                canView = authChecker.CheckActionForPage(page.FullName, Actions.ForPages.ReadDiscussion,
                                                         SessionFacade.GetCurrentUsername(), SessionFacade.GetCurrentGroupNames(currentWiki));
            }
            if (!canView)
            {
                UrlTools.Redirect("AccessDenied.aspx");
            }

            Page.Title = FormattingPipeline.PrepareTitle(currentWiki, page.Title, false, FormattingContext.PageContent, page.FullName) + " - " + Settings.GetWikiTitle(currentWiki);

            Literal canonical = new Literal();

            canonical.Text = Tools.GetCanonicalUrlTag(Request.Url.ToString(), page.FullName, Pages.FindNamespace(currentWiki, NameTools.GetNamespace(page.FullName)));
            Page.Header.Controls.Add(canonical);

            PrintContent();
        }
Пример #14
0
        protected void btnDeleteBackups_Click(object sender, EventArgs e)
        {
            PageContent page        = Pages.FindPage(currentWiki, txtCurrentPage.Value);
            AuthChecker authChecker = new AuthChecker(Collectors.CollectorsBox.GetSettingsProvider(currentWiki));

            if (!authChecker.CheckActionForPage(page.FullName, Actions.ForPages.ManagePage, SessionFacade.GetCurrentUsername(), SessionFacade.GetCurrentGroupNames(currentWiki)))
            {
                return;
            }

            int targetRevision = -1;

            // This should never occur
            if (!int.TryParse(lstBackup.SelectedValue, out targetRevision))
            {
                return;
            }

            Log.LogEntry("Page backup deletion requested for " + txtCurrentPage.Value, EntryType.General, Log.SystemUsername, currentWiki);

            bool done = false;

            if (rdoAllBackups.Checked)
            {
                done = Pages.DeleteBackups(page);
            }
            else
            {
                done = Pages.DeleteBackups(page, targetRevision);
            }

            if (done)
            {
                RefreshList();
                lblBackupResult.CssClass = "resultok";
                lblBackupResult.Text     = Properties.Messages.PageBackupsDeleted;
                ReturnToList();
            }
            else
            {
                lblBackupResult.CssClass = "resulterror";
                lblBackupResult.Text     = Properties.Messages.CouldNotDeletePageBackups;
            }
        }
Пример #15
0
        protected void Page_Load(object sender, EventArgs e)
        {
            Response.ClearContent();
            Response.ContentType     = "text/xml;charset=UTF-8";
            Response.ContentEncoding = System.Text.UTF8Encoding.UTF8;

            var mainUrl     = Settings.MainUrl;
            var rootDefault = Settings.DefaultPage.ToLowerInvariant();

            using (var writer = XmlWriter.Create(Response.OutputStream))
            {
                writer.WriteStartDocument();

                writer.WriteStartElement("urlset", "http://www.sitemaps.org/schemas/sitemap/0.9");
                writer.WriteAttributeString("xmlns", "xsi", null, "http://www.w3.org/2001/XMLSchema-instance");
                writer.WriteAttributeString("xsi", "schemaLocation", null, "http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/09/sitemap.xsd");

                var user   = SessionFacade.GetCurrentUsername();
                var groups = SessionFacade.GetCurrentGroupNames();

                foreach (PageInfo page in Pages.GetPages(null))
                {
                    if (AuthChecker.CheckActionForPage(page, Actions.ForPages.ReadPage, user, groups))
                    {
                        WritePage(mainUrl, page, page.FullName.ToLowerInvariant() == rootDefault, writer);
                    }
                }
                foreach (NamespaceInfo nspace in Pages.GetNamespaces())
                {
                    var nspaceDefault = nspace.DefaultPage.FullName.ToLowerInvariant();

                    foreach (PageInfo page in Pages.GetPages(nspace))
                    {
                        if (AuthChecker.CheckActionForPage(page, Actions.ForPages.ReadPage, user, groups))
                        {
                            WritePage(mainUrl, page, page.FullName.ToLowerInvariant() == nspaceDefault, writer);
                        }
                    }
                }

                writer.WriteEndElement();
                writer.WriteEndDocument();
            }
        }
 /// <summary>
 /// Detects the permissions of the current user.
 /// </summary>
 private void DetectPermissions()
 {
     if (CurrentPage != null)
     {
         var currentUser   = SessionFacade.GetCurrentUsername();
         var currentGroups = SessionFacade.GetCurrentGroupNames();
         canDownload = AuthChecker.CheckActionForPage(CurrentPage, Actions.ForPages.DownloadAttachments, currentUser, currentGroups);
         canUpload   = AuthChecker.CheckActionForPage(CurrentPage, Actions.ForPages.UploadAttachments, currentUser, currentGroups);
         canDelete   = AuthChecker.CheckActionForPage(CurrentPage, Actions.ForPages.DeleteAttachments, currentUser, currentGroups);
         isAdmin     = currentGroups.Contains(Settings.AdministratorsGroup);
     }
     else
     {
         canDownload = false;
         canUpload   = false;
         canDelete   = false;
         isAdmin     = false;
     }
     lstProviders.Visible = isAdmin;
 }
Пример #17
0
        /// <summary>
        /// Prepares the message deletion GUI.
        /// </summary>
        private void PrepareDeleteMessage()
        {
            string ms = Request["Message"];
            string pg = Request["Page"];

            if (ms == null || ms.Length == 0 || pg == null || pg.Length == 0)
            {
                UrlTools.RedirectHome();
            }

            PageInfo page = Pages.FindPage(pg);

            if (page == null)
            {
                UrlTools.RedirectHome();
            }

            if (page.Provider.ReadOnly)
            {
                UrlTools.Redirect(UrlTools.BuildUrl(page.FullName, Settings.PageExtension));
            }

            bool canManageDiscussion = AuthChecker.CheckActionForPage(page, Actions.ForPages.ManageDiscussion,
                                                                      SessionFacade.GetCurrentUsername(), SessionFacade.GetCurrentGroupNames());

            if (!canManageDiscussion)
            {
                UrlTools.Redirect("AccessDenied.aspx");
            }

            int id = -1;

            try {
                id = int.Parse(ms);
            }
            catch {
                UrlTools.RedirectHome();
            }

            Message message = Pages.FindMessage(Pages.GetPageMessages(page), id);

            if (message == null)
            {
                UrlTools.RedirectHome();
            }

            StringBuilder sb = new StringBuilder(500);

            sb.Append("<b>");
            sb.Append(FormattingPipeline.PrepareTitle(message.Subject, false, FormattingContext.MessageBody, page));
            sb.Append("</b><br /><small>");
            sb.Append(Properties.Messages.Posted);
            sb.Append(" ");
            sb.Append(Preferences.AlignWithTimezone(message.DateTime).ToString(Settings.DateTimeFormat));
            sb.Append(" ");
            sb.Append(Properties.Messages.By);
            sb.Append(" ");
            sb.Append(Users.UserLink(message.Username));
            sb.Append("</small><br /><br />");
            sb.Append(FormattingPipeline.FormatWithPhase3(FormattingPipeline.FormatWithPhase1And2(message.Body, false, FormattingContext.MessageBody, page),
                                                          FormattingContext.MessageBody, page));

            lblDeleteMessageContent.Text = sb.ToString();
        }
Пример #18
0
        public void PrintDiff()
        {
            if (Request["Page"] == null || Request["Rev1"] == null || Request["Rev2"] == null)
            {
                Redirect();
                return;
            }

            StringBuilder sb = new StringBuilder();

            PageInfo page = Pages.FindPage(Request["Page"]);

            if (page == null)
            {
                Redirect();
                return;
            }

            bool canView = AuthChecker.CheckActionForPage(page, Actions.ForPages.ReadPage,
                                                          SessionFacade.GetCurrentUsername(), SessionFacade.GetCurrentGroupNames());

            if (!canView)
            {
                UrlTools.Redirect("AccessDenied.aspx");
            }

            int    rev1     = -1;
            int    rev2     = -1;
            string rev1Text = "";
            string rev2Text = "";

            PageContent rev1Content = null;
            PageContent rev2Content = null;
            bool        draft       = false;

            // Load rev1 content
            if (int.TryParse(Request["Rev1"], out rev1))
            {
                rev1Content = Pages.GetBackupContent(page, rev1);
                rev1Text    = rev1.ToString();
                if (rev1 >= 0 && rev1Content == null && Pages.GetBackupContent(page, rev1 - 1) != null)
                {
                    rev1Content = Content.GetPageContent(page, false);
                }
                if (rev1Content == null)
                {
                    Redirect();
                }
            }
            else
            {
                // Look for current
                if (Request["Rev1"].ToLowerInvariant() == "current")
                {
                    rev1Content = Content.GetPageContent(page, false);
                    rev1Text    = Properties.Messages.Current;
                }
                else
                {
                    Redirect();
                }
            }

            if (int.TryParse(Request["Rev2"], out rev2))
            {
                rev2Content = Pages.GetBackupContent(page, rev2);
                rev2Text    = rev2.ToString();
                if (rev2 >= 0 && rev2Content == null && Pages.GetBackupContent(page, rev2 - 1) != null)
                {
                    rev2Content = Content.GetPageContent(page, false);
                }
                if (rev2Content == null)
                {
                    Redirect();
                }
            }
            else
            {
                // Look for current or draft
                if (Request["Rev2"].ToLowerInvariant() == "current")
                {
                    rev2Content = Content.GetPageContent(page, false);
                    rev2Text    = Properties.Messages.Current;
                }
                else if (Request["Rev2"].ToLowerInvariant() == "draft")
                {
                    rev2Content = Pages.GetDraft(page);
                    rev2Text    = Properties.Messages.Draft;
                    draft       = true;
                    if (rev2Content == null)
                    {
                        Redirect();
                    }
                }
                else
                {
                    Redirect();
                }
            }

            PageContent content = Content.GetPageContent(page, true);

            lblTitle.Text = Properties.Messages.DiffingPageTitle.Replace("##PAGETITLE##",
                                                                         FormattingPipeline.PrepareTitle(content.Title, false, FormattingContext.PageContent, page)).Replace("##REV1##", rev1Text).Replace("##REV2##", rev2Text);

            lblBack.Text = string.Format(@"<a href=""{0}"">&laquo; {1}</a>",
                                         UrlTools.BuildUrl("History.aspx?Page=", Tools.UrlEncode(Request["Page"]), "&amp;Rev1=", Request["Rev1"], "&amp;Rev2=", Request["Rev2"]),
                                         Properties.Messages.Back);
            lblBack.Visible = !draft;

            sb.Append(Properties.Messages.DiffColorKey);
            sb.Append("<br /><br />");

            string result = DiffTools.DiffRevisions(rev1Content.Content, rev2Content.Content);

            sb.Append(result);

            lblDiff.Text = sb.ToString();
        }
Пример #19
0
        /// <summary>
        /// Performs a search.
        /// </summary>
        /// <param name="query">The search query.</param>
        /// <param name="mode">The search mode.</param>
        /// <param name="selectedCategories">The selected categories.</param>
        /// <param name="searchUncategorized">A value indicating whether to search uncategorized pages.</param>
        /// <param name="searchInAllNamespacesAndCategories">A value indicating whether to search in all namespaces and categories.</param>
        /// <param name="searchFilesAndAttachments">A value indicating whether to search files and attachments.</param>
        private void PerformSearch(string query, SearchOptions mode, List <string> selectedCategories, bool searchUncategorized, bool searchInAllNamespacesAndCategories, bool searchFilesAndAttachments)
        {
            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);
        }
Пример #20
0
        /// <summary>
        /// Performs a search.
        /// </summary>
        /// <param name="query">The search query.</param>
        /// <param name="mode">The search mode.</param>
        /// <param name="selectedCategories">The selected categories.</param>
        /// <param name="searchUncategorized">A value indicating whether to search uncategorized pages.</param>
        /// <param name="searchInAllNamespacesAndCategories">A value indicating whether to search in all namespaces and categories.</param>
        /// <param name="searchFilesAndAttachments">A value indicating whether to search files and attachments.</param>
        private void PerformSearch(string query, SearchOptions mode, List <string> selectedCategories, bool searchUncategorized, bool searchInAllNamespacesAndCategories, bool searchFilesAndAttachments)
        {
            List <SearchResult> results = null;
            DateTime            begin   = DateTime.Now;

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

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

            string currentUser = SessionFacade.GetCurrentUsername();

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

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

            CategoryInfo[] pageCategories;
            int            count = 0;

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

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

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

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

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

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

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

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

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

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

            rptResults.DataSource = rows;
            rptResults.DataBind();
        }
Пример #21
0
        protected void Page_Load(object sender, EventArgs e)
        {
            string filename = Request["File"];

            if (filename == null)
            {
                Response.StatusCode = 404;
                Response.Write(Properties.Messages.FileNotFound);
                return;
            }

            string currentWiki = Tools.DetectCurrentWiki();

            // Remove ".." sequences that might be a security issue
            filename = filename.Replace("..", "");

            bool        isPageAttachment = !string.IsNullOrEmpty(Request["Page"]);
            PageContent pageContent      = isPageAttachment ? Pages.FindPage(currentWiki, Request["Page"]) : null;

            if (isPageAttachment && pageContent == null)
            {
                Response.StatusCode = 404;
                Response.Write(Properties.Messages.FileNotFound);
                return;
            }

            IFilesStorageProviderV40 provider;

            if (!string.IsNullOrEmpty(Request["Provider"]))
            {
                provider = Collectors.CollectorsBox.FilesProviderCollector.GetProvider(Request["Provider"], currentWiki);
            }
            else
            {
                if (isPageAttachment)
                {
                    provider = FilesAndAttachments.FindPageAttachmentProvider(currentWiki, pageContent.FullName, filename);
                }
                else
                {
                    provider = FilesAndAttachments.FindFileProvider(currentWiki, filename);
                }
            }

            if (provider == null)
            {
                Response.StatusCode = 404;
                Response.Write("File not found.");
                return;
            }

            // Use canonical path format (leading with /)
            if (!isPageAttachment)
            {
                if (!filename.StartsWith("/"))
                {
                    filename = "/" + filename;
                }
                filename = filename.Replace("\\", "/");
            }

            // Verify permissions
            bool canDownload = false;

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

            if (isPageAttachment)
            {
                canDownload = authChecker.CheckActionForPage(pageContent.FullName, Actions.ForPages.DownloadAttachments,
                                                             SessionFacade.GetCurrentUsername(), SessionFacade.GetCurrentGroupNames(currentWiki));
            }
            else
            {
                string dir = Tools.GetDirectoryName(filename);
                canDownload = authChecker.CheckActionForDirectory(provider, dir,
                                                                  Actions.ForDirectories.DownloadFiles, SessionFacade.GetCurrentUsername(),
                                                                  SessionFacade.GetCurrentGroupNames(currentWiki));
            }
            if (!canDownload)
            {
                Response.StatusCode = 401;
                return;
            }

            long size = -1;

            FileDetails details = null;

            if (isPageAttachment)
            {
                details = provider.GetPageAttachmentDetails(pageContent.FullName, filename);
            }
            else
            {
                details = provider.GetFileDetails(filename);
            }

            if (details != null)
            {
                size = details.Size;
            }
            else
            {
                Log.LogEntry("Attempted to download an inexistent file/attachment (" + (pageContent != null ? pageContent.FullName + "/" : "") + filename + ")", EntryType.Warning, Log.SystemUsername, currentWiki);
                Response.StatusCode = 404;
                Response.Write("File not found.");
                return;
            }

            string mime = "";

            try {
                string ext = Path.GetExtension(filename);
                if (ext.StartsWith("."))
                {
                    ext = ext.Substring(1).ToLowerInvariant();                                     // Remove trailing dot
                }
                mime = GetMimeType(ext);
            }
            catch {
                // ext is null -> no mime type -> abort
                Response.Write(filename + "<br />");
                Response.StatusCode = 404;
                Response.Write("File not found.");
                //mime = "application/octet-stream";
                return;
            }

            // Prepare response
            Response.Clear();
            Response.AddHeader("content-type", mime);
            if (Request["AsStreamAttachment"] != null)
            {
                Response.AddHeader("content-disposition", "attachment;filename=\"" + Path.GetFileName(filename) + "\"");
            }
            else
            {
                Response.AddHeader("content-disposition", "inline;filename=\"" + Path.GetFileName(filename) + "\"");
            }
            Response.AddHeader("content-length", size.ToString());

            bool retrieved = false;

            if (isPageAttachment)
            {
                try {
                    retrieved = provider.RetrievePageAttachment(pageContent.FullName, filename, Response.OutputStream);
                }
                catch (ArgumentException ex) {
                    Log.LogEntry("Attempted to download an inexistent attachment (" + pageContent.FullName + "/" + filename + ")\n" + ex.ToString(), EntryType.Warning, Log.SystemUsername, currentWiki);
                }
            }
            else
            {
                try {
                    retrieved = provider.RetrieveFile(filename, Response.OutputStream);
                }
                catch (ArgumentException ex) {
                    Log.LogEntry("Attempted to download an inexistent file/attachment (" + filename + ")\n" + ex.ToString(), EntryType.Warning, Log.SystemUsername, currentWiki);
                }
            }

            if (!retrieved)
            {
                Response.StatusCode = 404;
                Response.Write("File not found.");
                return;
            }

            // Set the cache duration accordingly to the file date/time
            //Response.AddFileDependency(filename);
            //Response.Cache.SetETagFromFileDependencies();
            //Response.Cache.SetLastModifiedFromFileDependencies();
            Response.Cache.SetETag(filename.GetHashCode().ToString() + "-" + size.ToString());
            Response.Cache.SetCacheability(HttpCacheability.Public);
            Response.Cache.SetSlidingExpiration(true);
            Response.Cache.SetValidUntilExpires(true);
            Response.Cache.VaryByParams["File"]             = true;
            Response.Cache.VaryByParams["Provider"]         = true;
            Response.Cache.VaryByParams["Page"]             = true;
            Response.Cache.VaryByParams["IsPageAttachment"] = true;
        }
Пример #22
0
        protected void Page_Load(object sender, EventArgs e)
        {
            Page.Title = Properties.Messages.PostTitle + " - " + Settings.WikiTitle;

            if (Request["Page"] == null)
            {
                UrlTools.RedirectHome();
            }
            page = Pages.FindPage(Request["Page"]);
            if (page == null)
            {
                UrlTools.RedirectHome();
            }
            editor.CurrentPage = page;

            if (page.Provider.ReadOnly)
            {
                UrlTools.Redirect(UrlTools.BuildUrl(page.FullName, Settings.PageExtension));
            }

            content = Content.GetPageContent(page, true);
            if (!Page.IsPostBack)
            {
                lblTitle.Text += " - " + FormattingPipeline.PrepareTitle(content.Title, false, FormattingContext.MessageBody, page);
            }

            // Verify permissions and setup captcha
            bool canPostMessage = AuthChecker.CheckActionForPage(page, Actions.ForPages.PostDiscussion,
                                                                 SessionFacade.GetCurrentUsername(), SessionFacade.GetCurrentGroupNames());

            if (!canPostMessage)
            {
                UrlTools.Redirect(UrlTools.BuildUrl(Tools.UrlEncode(page.FullName), Settings.PageExtension));
            }
            captcha.Visible = SessionFacade.LoginKey == null && !Settings.DisableCaptchaControl;

            if (Page.IsPostBack)
            {
                return;
            }

            editor.SetContent("", Settings.UseVisualEditorAsDefault);

            string username = Request.UserHostAddress;

            if (SessionFacade.LoginKey != null)
            {
                username = SessionFacade.CurrentUsername;
            }

            bool edit = Request["Edit"] != null;

            if (!edit)
            {
                if (Request["Parent"] != null)
                {
                    try
                    {
                        int.Parse(Request["Parent"]);
                    }
                    catch
                    {
                        UrlTools.RedirectHome();
                    }
                    var     messages = Pages.GetPageMessages(page);
                    Message parent   = Pages.FindMessage(messages, int.Parse(Request["Parent"]));

                    if (parent != null)
                    {
                        txtSubject.Text = (!parent.Subject.ToLowerInvariant().StartsWith("re:") ? "Re: " : "") + parent.Subject;
                    }
                }
            }
            else
            {
                try
                {
                    int.Parse(Request["Edit"]);
                }
                catch
                {
                    UrlTools.RedirectHome();
                }
                var     messages = Pages.GetPageMessages(page);
                Message msg      = Pages.FindMessage(messages, int.Parse(Request["Edit"]));

                if (msg != null)
                {
                    txtSubject.Text = msg.Subject;
                    editor.SetContent(msg.Body, Settings.UseVisualEditorAsDefault);
                }
                else
                {
                    throw new Exception("Message not found (" + page.FullName + "." + Request["Edit"] + ").");
                }
            }
        }
Пример #23
0
        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();
                    }
                }
            }
        }
Пример #24
0
        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(Request.Url.ToString()));
                }
                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);
        }
Пример #25
0
        protected void Page_Load(object sender, EventArgs e)
        {
            string filename = Request["File"];

            if (string.IsNullOrEmpty(filename))
            {
                Response.Write("No file specified.");
                return;
            }

            // Remove ".." sequences that might be a security issue
            filename = filename.Replace("..", "");

            string   page             = Request["Page"];
            PageInfo pageInfo         = Pages.FindPage(page);
            bool     isPageAttachment = !string.IsNullOrEmpty(page);

            if (isPageAttachment && pageInfo == null)
            {
                Response.StatusCode = 404;
                Response.Write("File not found.");
                return;
            }

            IFilesStorageProviderV30 provider = null;

            if (!string.IsNullOrEmpty(Request["Provider"]))
            {
                provider = Collectors.FilesProviderCollector.GetProvider(Request["Provider"]);
            }
            else
            {
                if (isPageAttachment)
                {
                    provider = FilesAndAttachments.FindPageAttachmentProvider(pageInfo, filename);
                }
                else
                {
                    provider = FilesAndAttachments.FindFileProvider(filename);
                }
            }

            if (provider == null)
            {
                Response.StatusCode = 404;
                Response.Write("File not found.");
                return;
            }

            string size = Request["Size"];

            if (string.IsNullOrEmpty(size))
            {
                size = "small";
            }
            size = size.ToLowerInvariant();

            // Verify permissions
            bool canDownload = false;

            if (pageInfo != null)
            {
                canDownload = AuthChecker.CheckActionForPage(pageInfo, Actions.ForPages.DownloadAttachments,
                                                             SessionFacade.GetCurrentUsername(), SessionFacade.GetCurrentGroupNames());
            }
            else
            {
                string dir = Tools.GetDirectoryName(filename);
                canDownload = AuthChecker.CheckActionForDirectory(provider, dir,
                                                                  Actions.ForDirectories.DownloadFiles, SessionFacade.GetCurrentUsername(),
                                                                  SessionFacade.GetCurrentGroupNames());
            }
            if (!canDownload)
            {
                Response.StatusCode = 401;
            }

            // Contains the image bytes
            MemoryStream ms       = new MemoryStream(1048576);
            long         fileSize = 0;

            // Load from provider
            if (string.IsNullOrEmpty(page))
            {
                bool retrieved = false;
                try {
                    retrieved = provider.RetrieveFile(filename, ms, false);
                }
                catch (ArgumentException ex) {
                    Log.LogEntry("Attempted to create thumb of inexistent file (" + filename + ")\n" + ex, EntryType.Warning, Log.SystemUsername);
                }

                if (!retrieved)
                {
                    Response.StatusCode = 404;
                    Response.Write("File not found.");
                    return;
                }

                fileSize = provider.GetFileDetails(filename).Size;
            }
            else
            {
                if (pageInfo == null)
                {
                    Response.StatusCode = 404;
                    Response.Write("Page not found.");
                    return;
                }

                bool retrieved = false;
                try {
                    retrieved = provider.RetrievePageAttachment(pageInfo, filename, ms, false);
                }
                catch (ArgumentException ex) {
                    Log.LogEntry("Attempted to create thumb of inexistent attachment (" + page + "/" + filename + ")\n" + ex, EntryType.Warning, Log.SystemUsername);
                }

                if (!retrieved)
                {
                    Response.StatusCode = 404;
                    Response.Write("File not found.");
                    return;
                }

                fileSize = provider.GetPageAttachmentDetails(pageInfo, filename).Size;
            }

            ms.Seek(0, SeekOrigin.Begin);

            int rotation = 0;

            int.TryParse(Request["Rot"], out rotation);

            // Load the source image
            System.Drawing.Image source = System.Drawing.Image.FromStream(ms);

            // Destination bitmap
            Bitmap result = null;

            System.Drawing.Imaging.PixelFormat pixelFormat = System.Drawing.Imaging.PixelFormat.Format32bppArgb;

            if (size == "big")
            {
                // Big thumb (outer size 200x200)
                result = new Bitmap(200, 200, pixelFormat);
            }
            else if (size == "imgeditprev")
            {
                // Image Editor Preview thumb (outer size from Request["dim"], if null 200x200)
                if (!string.IsNullOrEmpty(Request["Width"]) && !string.IsNullOrEmpty(Request["Height"]))
                {
                    try {
                        result = new Bitmap(
                            rotation != 90 && rotation != 270 ? int.Parse(Request["Width"]) : int.Parse(Request["Height"]),
                            rotation != 90 && rotation != 270 ? int.Parse(Request["Height"]) : int.Parse(Request["Width"]),
                            pixelFormat);
                    }
                    catch (FormatException) {
                        result = new Bitmap(200, 200, pixelFormat);
                    }
                }
                else
                {
                    result = new Bitmap(200, 200, pixelFormat);
                }
            }
            else
            {
                // Small thumb (outer size 48x48)
                result = new Bitmap(48, 48, pixelFormat);
            }

            // Get Graphics object for destination bitmap
            Graphics g = Graphics.FromImage(result);

            if (source.PixelFormat == System.Drawing.Imaging.PixelFormat.Format32bppArgb)
            {
                g.Clear(Color.Transparent);
            }
            else
            {
                g.Clear(Color.White);
            }

            g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
            g.SmoothingMode     = SmoothingMode.HighQuality;
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBilinear;

            g.TranslateTransform(result.Width / 2, result.Height / 2);
            g.RotateTransform(rotation);
            g.TranslateTransform(-result.Width / 2, -result.Height / 2);

            // Draw bitmap
            g.DrawImage(source, GetImageRectangle(result.Width, result.Height,
                                                  rotation != 90 && rotation != 270 ? source.Width : source.Height,
                                                  rotation != 90 && rotation != 270 ? source.Height : source.Width,
                                                  rotation == 90 || rotation == 270));

            if (!string.IsNullOrEmpty(Request["Info"]) && size == "big")
            {
                // Draw image information
                RectangleF   r = new RectangleF(0, 0, result.Width, 20);
                StringFormat f = new StringFormat();
                f.Alignment = StringAlignment.Center;
                //f.LineAlignment = StringAlignment.Center;
                GraphicsPath path = new GraphicsPath();
                path.AddString(string.Format("{0}x{1} - {2}", source.Width, source.Height,
                                             Tools.BytesToString(fileSize)),
                               new FontFamily("Verdana"), 0, 12, new Point(result.Width / 2, 2), f);
                Pen pen = new Pen(Brushes.Black, 2F);
                g.DrawPath(pen, path);
                g.FillPath(Brushes.White, path);
            }

            // Write result in output stream in JPEG or PNG format
            if (source.PixelFormat == System.Drawing.Imaging.PixelFormat.Format32bppArgb)
            {
                Response.ContentType = "image/png";
            }
            else
            {
                Response.ContentType = "image/jpeg";
            }

            // This invariably throws an exception (A generic error occurred in GDI+) - an intermediate buffer is needed
            // The possible cause is that PNG format requires to read from the output stream, and Response.OutputStream does not support reading
            //result.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Png);

            MemoryStream tempStream = new MemoryStream(65536);             // 32 KB

            if (source.PixelFormat == System.Drawing.Imaging.PixelFormat.Format32bppArgb)
            {
                result.Save(tempStream, System.Drawing.Imaging.ImageFormat.Png);
            }
            else
            {
                result.Save(tempStream, System.Drawing.Imaging.ImageFormat.Jpeg);
            }
            Response.OutputStream.Write(tempStream.ToArray(), 0, (int)tempStream.Length);
            tempStream.Dispose();

            ms.Dispose();

            source.Dispose();
            g.Dispose();
            result.Dispose();
        }