Exposes in a strongly-typed fashion the Session variables.
Пример #1
0
        /// <summary>
        /// Enters a sub-directory of the current directory.
        /// </summary>
        /// <param name="name">The name of the current directory.</param>
        private void EnterDirectory(string name)
        {
            string newDirectory      = CurrentDirectory + name + "/";
            bool   canListThisSubDir = AuthChecker.CheckActionForDirectory(provider, newDirectory, Actions.ForDirectories.List,
                                                                           SessionFacade.GetCurrentUsername(), SessionFacade.GetCurrentGroupNames());

            if (!canListThisSubDir)
            {
                return;
            }

            CurrentDirectory += name + "/";

            DetectPermissions();
            SetupControlsForPermissions();

            rptItems.DataBind();
            PopulateBreadcrumb();
        }
Пример #2
0
        /// <summary>
        /// Prepares the title of an item for display.
        /// </summary>
        /// <param name="title">The input title.</param>
        /// <param name="forIndexing">A value indicating whether the formatting is being done for content indexing.</param>
        /// <param name="context">The context information.</param>
        /// <param name="current">The current page, if any.</param>
        /// <returns>The prepared title, properly sanitized.</returns>
        public static string PrepareTitle(string title, bool forIndexing, FormattingContext context, PageInfo current)
        {
            string             temp = title;
            ContextInformation info = new ContextInformation(forIndexing, false, context, current, System.Threading.Thread.CurrentThread.CurrentCulture.Name,
                                                             HttpContext.Current, SessionFacade.GetCurrentUsername( ), SessionFacade.GetCurrentGroupNames( ));

            foreach (IFormatterProviderV30 prov in GetSortedFormatters( ))
            {
                temp = prov.PrepareTitle(temp, info);
            }

            return(PrepareItemTitle(temp));
        }
Пример #3
0
        protected void Page_Load(object sender, EventArgs e)
        {
            AdminMaster.RedirectToLoginIfNeeded();

            if (!AdminMaster.CanManageConfiguration(SessionFacade.GetCurrentUsername(), SessionFacade.GetCurrentGroupNames()))
            {
                UrlTools.Redirect("AccessDenied.aspx");
            }

            if (!Page.IsPostBack)
            {
                // Load log entries
                rptLog.DataBind();
            }
        }
Пример #4
0
        protected void btnDeleteMessage_Click(object sender, EventArgs e)
        {
            int      id   = int.Parse(Request["Message"]);
            PageInfo page = Pages.FindPage(Request["Page"]);

            Log.LogEntry("Message deletion requested for " + page.FullName + "." + id, EntryType.General, SessionFacade.GetCurrentUsername());
            bool done = Pages.RemoveMessage(page, id, chkDeleteMessageReplies.Checked);

            UrlTools.Redirect(UrlTools.BuildUrl(Request["Page"], Settings.PageExtension + "?Discuss=1"));
        }
Пример #5
0
        protected void rptHistory_ItemCommand(object sender, CommandEventArgs e)
        {
            if (e.CommandName == "Rollback")
            {
                if (!canRollback)
                {
                    return;
                }
                int rev = int.Parse(e.CommandArgument as string);

                Log.LogEntry("Page rollback requested for " + page.FullName + " to rev. " + rev.ToString(), EntryType.General, SessionFacade.GetCurrentUsername());
                Pages.Rollback(page, rev);

                PrintHistory();
            }
        }
Пример #6
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();
                    }
                    Message[] 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();
                }
                Message[] 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"] + ").");
                }
            }
        }
Пример #7
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(Tools.GetCurrentUrlFixed()));
                }
                else
                {
                    UrlTools.Redirect(UrlTools.BuildUrl("AccessDenied.aspx"));
                }
            }
            attachmentViewer.Visible = canDownloadAttachments;

            attachmentViewer.PageInfo = currentPage;
            currentContent            = Content.GetPageContent(currentPage, true);

            pnlPageInfo.Visible = Settings.EnablePageInfoDiv;

            SetupTitles();

            SetupToolbarLinks(canEdit || canEditWithApproval, canViewDiscussion, canPostDiscussion, canDownloadAttachments, canAdmin, canAdmin, canSetPerms);

            SetupLabels();
            SetupPrintAndRssLinks();
            SetupMetaInformation();
            VerifyAndPerformPageRedirection();
            SetupRedirectionSource();
            SetupNavigationPaths();
            SetupAdjacentPages();

            SessionFacade.Breadcrumbs.AddPage(currentPage);
            SetupBreadcrumbsTrail();

            SetupDoubleClickHandler();

            SetupEmailNotification();

            SetupPageContent(canPostDiscussion, canManageDiscussion);

            if (currentPage != null)
            {
                Literal canonical = new Literal();
                canonical.Text = Tools.GetCanonicalUrlTag(Request.Url.ToString(), currentPage, Pages.FindNamespace(NameTools.GetNamespace(currentPage.FullName)));
                Page.Header.Controls.Add(canonical);
            }
        }
Пример #8
0
        protected void Page_Load(object sender, EventArgs e)
        {
            Page.Title = Properties.Messages.ErrorTitle + " - " + Settings.WikiTitle;

            Exception ex = Session["LastError"] as Exception;

            if (ex != null && SessionFacade.LoginKey != null &&
                AdminMaster.CanManageConfiguration(SessionFacade.GetCurrentUsername(), SessionFacade.GetCurrentGroupNames()))
            {
                lblException.Text = ex.ToString();
            }
            else
            {
                pnlException.Visible = false;
            }
            Session["LastError"] = null;

            // Workaround for ASP.NET vulnerability
            // http://weblogs.asp.net/scottgu/archive/2010/09/18/important-asp-net-security-vulnerability.aspx
            byte[] delay = new byte[1];
            RandomNumberGenerator prng = new RNGCryptoServiceProvider();

            prng.GetBytes(delay);
            Thread.Sleep((int)delay[0]);

            IDisposable disposable = prng as IDisposable;

            if (disposable != null)
            {
                disposable.Dispose();
            }
        }
Пример #9
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;
            }

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

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

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

            IFilesStorageProviderV30 provider;

            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;
            }

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

                filename = filename.Replace("\\", "/");
            }

            bool countHit = CountHit(filename);

            // Verify permissions
            bool canDownload = false;

            if (isPageAttachment)
            {
                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;
                return;
            }

            long size = -1;

            FileDetails details = null;

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

            if (details != null)
            {
                size = details.Size;
            }
            else
            {
                Log.LogEntry("Attempted to download an inexistent file/attachment (" + (pageInfo != null ? pageInfo.FullName + "/" : "") + filename + ")", EntryType.Warning, Log.SystemUsername);
                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(pageInfo, filename, Response.OutputStream, countHit);
                }
                catch (ArgumentException ex) {
                    Log.LogEntry("Attempted to download an inexistent attachment (" + pageInfo.FullName + "/" + filename + ")\n" + ex.ToString(), EntryType.Warning, Log.SystemUsername);
                }
            }
            else
            {
                try {
                    retrieved = provider.RetrieveFile(filename, Response.OutputStream, countHit);
                }
                catch (ArgumentException ex) {
                    Log.LogEntry("Attempted to download an inexistent file/attachment (" + filename + ")\n" + ex.ToString(), EntryType.Warning, Log.SystemUsername);
                }
            }

            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;
        }
Пример #10
0
        /// <summary>
        /// Gets a value indicating whether the current user can manage pages in the selected namespace.
        /// </summary>
        /// <returns><c>true</c> if the user can manage pages, <c>false</c> otherwise.</returns>
        private bool CanManagePagesInCurrentNamespace()
        {
            NamespaceInfo nspace         = Pages.FindNamespace(lstNamespace.SelectedValue);
            bool          canManagePages = AuthChecker.CheckActionForNamespace(nspace, Actions.ForNamespaces.ManagePages,
                                                                               SessionFacade.GetCurrentUsername(), SessionFacade.GetCurrentGroupNames());

            return(canManagePages);
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            currentWiki = DetectWiki();

            AdminMaster.RedirectToLoginIfNeeded();

            if (!AdminMaster.CanManageGlobalConfiguration(SessionFacade.GetCurrentUsername(), SessionFacade.GetCurrentGroupNames(currentWiki)))
            {
                UrlTools.Redirect("AccessDenied.aspx");
            }

            if (!Page.IsPostBack)
            {
                LoadDlls();

                // Load providers and related data
                rptProviders.DataBind();
            }
        }
Пример #12
0
        protected void rptIndex_ItemCommand(object sender, CommandEventArgs e)
        {
            Log.LogEntry("Index rebuild requested for " + e.CommandArgument as string, EntryType.General, SessionFacade.GetCurrentUsername());

            IPagesStorageProviderV30 provider = Collectors.PagesProviderCollector.GetProvider(e.CommandArgument as string);

            provider.RebuildIndex();

            Log.LogEntry("Index rebuild completed for " + e.CommandArgument as string, EntryType.General, Log.SystemUsername);

            rptIndex.DataBind();
        }
Пример #13
0
        protected void Page_Load(object sender, EventArgs e)
        {
            AdminMaster.RedirectToLoginIfNeeded();

            if (!AdminMaster.CanManageConfiguration(SessionFacade.GetCurrentUsername(), SessionFacade.GetCurrentGroupNames()))
            {
                UrlTools.Redirect("AccessDenied.aspx");
            }

            PrintSystemStatus();

            if (!Page.IsPostBack)
            {
                rptPages.DataBind();
                rptIndex.DataBind();

                DisplayOrphansCount();

                string anon = Settings.AnonymousGroup;
                foreach (UserGroup group in Users.GetUserGroups())
                {
                    if (group.Name != anon)
                    {
                        ListItem item = new ListItem(group.Name, group.Name);
                        item.Selected = true;
                        lstGroups.Items.Add(item);
                    }
                }
            }
        }
Пример #14
0
        protected void Page_Load(object sender, EventArgs e)
        {
            AdminMaster.RedirectToLoginIfNeeded();

            if (!AdminMaster.CanManageSnippetsAndTemplates(SessionFacade.GetCurrentUsername(), SessionFacade.GetCurrentGroupNames()))
            {
                UrlTools.Redirect("AccessDenied.aspx");
            }

            if (!Page.IsPostBack)
            {
                // Load snippets
                rptSnippetsTemplates.DataBind();
            }
        }
Пример #15
0
        protected void cvOldPassword_ServerValidate(object source, ServerValidateEventArgs args)
        {
            UserInfo user = SessionFacade.GetCurrentUser();

            args.IsValid = user.Provider.TestAccount(user, txtOldPassword.Text);
        }
Пример #16
0
        protected void rptNamespaces_DataBinding(object sender, EventArgs e)
        {
            string currentWiki = DetectWiki();

            List <NamespaceInfo> namespaces = Pages.GetNamespaces(currentWiki);

            List <NamespaceRow> result = new List <NamespaceRow>(namespaces.Count);

            bool canSetPermissions = AdminMaster.CanManagePermissions(SessionFacade.GetCurrentUsername(), SessionFacade.GetCurrentGroupNames(currentWiki));

            PageContent defaultPage = Pages.FindPage(currentWiki, Settings.GetDefaultPage(currentWiki));

            // Inject the root namespace as first entry, retrieving the default page in Settings
            result.Add(new NamespaceRow(new NamespaceInfo(RootName, defaultPage.Provider, defaultPage.FullName),
                                        Settings.GetTheme(currentWiki, null),
                                        Pages.GetPages(currentWiki, null).Count, Pages.GetCategories(currentWiki, null).Count,
                                        canSetPermissions, txtCurrentNamespace.Value == RootName));

            foreach (NamespaceInfo ns in namespaces)
            {
                result.Add(new NamespaceRow(ns, Settings.GetTheme(currentWiki, ns.Name),
                                            Pages.GetPages(currentWiki, ns).Count, Pages.GetCategories(currentWiki, ns).Count,
                                            canSetPermissions, txtCurrentNamespace.Value == ns.Name));
            }

            rptNamespaces.DataSource = result;
        }
Пример #17
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();
        }
Пример #18
0
        protected void rptNamespaces_ItemCommand(object sender, RepeaterCommandEventArgs e)
        {
            txtCurrentNamespace.Value = e.CommandArgument as string;

            string currentWiki = DetectWiki();

            NamespaceInfo nspace = txtCurrentNamespace.Value != RootName?
                                   Pages.FindNamespace(currentWiki, txtCurrentNamespace.Value) : null;

            if (e.CommandName == "Select")
            {
                // rptNamespaces.DataBind(); Not needed because the list is hidden on select

                txtName.Enabled = false;
                txtName.Text    = nspace != null ? nspace.Name : RootNameUnescaped;
                txtNewName.Text = "";
                cvName.Enabled  = false;
                cvName2.Enabled = false;
                LoadDefaultPages();

                btnCreate.Visible = false;
                btnSave.Visible   = true;
                btnDelete.Visible = true;
                // Cannot delete root namespace
                btnDelete.Enabled = nspace != null;
                // Cannot rename root namespace
                btnRename.Enabled = nspace != null;

                pnlList.Visible          = false;
                pnlEditNamespace.Visible = true;

                lblResult.Text     = "";
                lblResult.CssClass = "";

                string[] theme = Settings.GetTheme(currentWiki, nspace != null ? nspace.Name : null).Split(new char[] { '|' });

                providerThSelector.SelectedProvider = theme[0];
                providerThSelector.SelectedThemes   = theme[1];
            }
            else if (e.CommandName == "Perms")
            {
                if (!AdminMaster.CanManagePermissions(SessionFacade.GetCurrentUsername(), SessionFacade.GetCurrentGroupNames(currentWiki)))
                {
                    return;
                }

                permissionsManager.CurrentResourceName = nspace != null ? nspace.Name : null;

                lblNamespaceName.Text = nspace != null ? nspace.Name : RootName;

                pnlList.Visible        = false;
                pnlPermissions.Visible = true;

                lblResult.Text     = "";
                lblResult.CssClass = "";
            }
        }
Пример #19
0
        protected void Page_Load(object sender, EventArgs e)
        {
            AdminMaster.RedirectToLoginIfNeeded();

            if (!AdminMaster.CanManageConfiguration(SessionFacade.GetCurrentUsername(), SessionFacade.GetCurrentGroupNames()))
            {
                UrlTools.Redirect("AccessDenied.aspx");
            }

            if (!Page.IsPostBack)
            {
                // Load namespaces

                // Add root namespace
                lstNamespace.Items.Add(new ListItem("<root>", ""));
                List <NamespaceInfo> namespaces = Pages.GetNamespaces();
                foreach (NamespaceInfo ns in namespaces)
                {
                    lstNamespace.Items.Add(new ListItem(ns.Name, ns.Name));
                }
            }
        }
Пример #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)
        {
            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.ToString(), EntryType.Warning, SessionFacade.CurrentUsername);
                results = new SearchResultCollection();
            }

            DateTime end = DateTime.Now;

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

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

            IList <CategoryInfo> pageCategories;
            var 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
                    var 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
                    var 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
                    var canDownloadAttn = AuthChecker.CheckActionForPage(currentPage,
                                                                         Actions.ForPages.DownloadAttachments, currentUser, currentGroups);
                    if (!canDownloadAttn)
                    {
                        continue;                   // Skip
                    }
                }
                else if (res.Document.TypeTag == FileDocument.StandardTypeTag)
                {
                    var fields = ((FileDocument)res.Document).Name.Split('|');
                    IFilesStorageProviderV30 provider = Collectors.FilesProviderCollector.GetProvider(fields[0]);
                    var directory = Tools.GetDirectoryName(fields[1]);

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

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

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

                    if (searchInAllNamespacesAndCategories || pageCategories.Any(c => selectedCategories.Contains(c.FullName)) || pageCategories.Count == 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);
        }
Пример #21
0
        protected void Page_Load(object sender, EventArgs e)
        {
            AdminMaster.RedirectToLoginIfNeeded();

            if (!AdminMaster.CanManageConfiguration(SessionFacade.GetCurrentUsername(), SessionFacade.GetCurrentGroupNames()))
            {
                UrlTools.Redirect("AccessDenied.aspx");
            }

            StringBuilder sb = new StringBuilder(200);

            sb.Append("<script type=\"text/javascript\">\r\n<!--\r\n");
            sb.AppendFormat("\tvar __DateTimeFormatTextBox = '{0}';\r\n", txtDateTimeFormat.ClientID);
            sb.Append("// -->\r\n</script>");
            lblStrings.Text = sb.ToString();

            if (!Page.IsPostBack)
            {
                // Setup validation regular expressions
                revMainUrl.ValidationExpression      = Settings.MainUrlRegex;
                revWikiTitle.ValidationExpression    = Settings.WikiTitleRegex;
                revContactEmail.ValidationExpression = Settings.EmailRegex;
                revSenderEmail.ValidationExpression  = Settings.EmailRegex;
                revSmtpServer.ValidationExpression   = Settings.SmtpServerRegex;

                // Load current values
                LoadGeneralConfig();
                LoadContentConfig();
                LoadSecurityConfig();
                LoadAdvancedConfig();
            }
        }
Пример #22
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();
        }
Пример #23
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();
        }
Пример #24
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.ToString(), 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;
                                    }
                                    else 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;
                                    }
                                    else 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();
                    }
                }
            }
        }
Пример #25
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();
        }
Пример #26
0
        /// <summary>
        /// Returns a value indicating whether the current user can manage categories in the selected namespace.
        /// </summary>
        /// <returns><c>true</c> if the user can manage categories, <c>false</c> otherwise.</returns>
        private bool CanManageCategoriesInCurrentNamespace()
        {
            string        currentWiki         = DetectWiki();
            NamespaceInfo nspace              = Pages.FindNamespace(currentWiki, lstNamespace.SelectedValue);
            AuthChecker   authChecker         = new AuthChecker(Collectors.CollectorsBox.GetSettingsProvider(currentWiki));
            bool          canManageCategories = authChecker.CheckActionForNamespace(nspace, Actions.ForNamespaces.ManageCategories,
                                                                                    SessionFacade.GetCurrentUsername(), SessionFacade.GetCurrentGroupNames(currentWiki));

            return(canManageCategories);
        }
Пример #27
0
        public void PrintDiff()
        {
            if (Request["Page"] == null || Request["Rev1"] == null || Request["Rev2"] == null)
            {
                Redirect();
                return;
            }

            StringBuilder sb = new StringBuilder();

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

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

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

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

            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 = page;
                }
                if (rev1Content == null)
                {
                    Redirect();
                }
            }
            else
            {
                // Look for current
                if (Request["Rev1"].ToLowerInvariant() == "current")
                {
                    rev1Content = page;
                    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 = page;
                }
                if (rev2Content == null)
                {
                    Redirect();
                }
            }
            else
            {
                // Look for current or draft
                if (Request["Rev2"].ToLowerInvariant() == "current")
                {
                    rev2Content = page;
                    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();
                }
            }

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

            lblBack.Text = string.Format(@"<a href=""{0}"">&laquo; {1}</a>",
                                         UrlTools.BuildUrl(currentWiki, "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();
        }
Пример #28
0
        protected void Page_Load(object sender, EventArgs e)
        {
            currentWiki = DetectWiki();
            AdminMaster.RedirectToLoginIfNeeded();

            bool canManageCategories = AdminMaster.CanManageCategories(SessionFacade.GetCurrentUsername(), SessionFacade.GetCurrentGroupNames(currentWiki));

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

            if (!Page.IsPostBack)
            {
                // Load namespaces

                // Add root namespace
                lstNamespace.Items.Add(new ListItem("<root>", ""));

                List <NamespaceInfo> namespaces = Pages.GetNamespaces(currentWiki);

                foreach (NamespaceInfo ns in namespaces)
                {
                    lstNamespace.Items.Add(new ListItem(ns.Name, ns.Name));
                }

                // Load pages
                rptCategories.DataBind();
            }

            btnNewCategory.Enabled = CanManageCategoriesInCurrentNamespace();
            btnBulkManage.Enabled  = btnNewCategory.Enabled;
        }
Пример #29
0
        protected void Page_Load(object sender, EventArgs e)
        {
            string currentWiki = Tools.DetectCurrentWiki();

            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"];
            PageContent pageContent      = Pages.FindPage(currentWiki, page);
            bool        isPageAttachment = !string.IsNullOrEmpty(page);

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

            IFilesStorageProviderV40 provider = null;

            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;
            }

            string size = Request["Size"];

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

            // Verify permissions
            bool canDownload = false;

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

            if (pageContent != null)
            {
                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;
            }

            // 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);
                }
                catch (ArgumentException ex) {
                    Log.LogEntry("Attempted to create thumb of inexistent file (" + filename + ")\n" + ex.ToString(), EntryType.Warning, Log.SystemUsername, currentWiki);
                }

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

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

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

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

                fileSize = provider.GetPageAttachmentDetails(pageContent.FullName, 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();
        }
Пример #30
0
        /// <summary>
        /// Tries to enter a directory.
        /// </summary>
        /// <param name="provider">The provider.</param>
        /// <param name="directory">The full path of the directory.</param>
        public void TryEnterDirectory(string provider, string directory)
        {
            if (string.IsNullOrEmpty(directory) || string.IsNullOrEmpty(provider))
            {
                return;
            }

            if (!directory.StartsWith("/"))
            {
                directory = "/" + directory;
            }

            if (!directory.EndsWith("/"))
            {
                directory += "/";
            }

            LoadProviders();

            IFilesStorageProviderV30 realProvider = Collectors.FilesProviderCollector.GetProvider(provider);

            if (realProvider == null)
            {
                return;
            }

            this.provider = realProvider;

            // Detect existence
            try {
                realProvider.ListDirectories(directory);
            }
            catch (ArgumentException) {
                return;
            }

            bool canListThisSubDir = AuthChecker.CheckActionForDirectory(realProvider, directory, Actions.ForDirectories.List,
                                                                         SessionFacade.GetCurrentUsername(), SessionFacade.GetCurrentGroupNames());

            if (!canListThisSubDir)
            {
                return;
            }

            lstProviders.SelectedIndex = -1;
            foreach (ListItem item in lstProviders.Items)
            {
                if (item.Value == provider)
                {
                    item.Selected = true;
                    break;
                }
            }
            //lstProviders_SelectedIndexChanged(this, null);

            string parent           = "/";
            string trimmedDirectory = directory.TrimEnd('/');

            if (trimmedDirectory.Length > 0)
            {
                int lastSlash = trimmedDirectory.LastIndexOf("/");
                if (lastSlash != -1)
                {
                    parent = "/" + trimmedDirectory.Substring(0, lastSlash) + "/";
                }
            }

            if (parent != directory)
            {
                CurrentDirectory = parent;
                EnterDirectory(Tools.ExtractDirectoryName(directory));
            }
        }