Utility class for checking permissions and authorizations.
All the methods in this class implement a security bypass for the admin user.
Пример #1
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 += "/";
            }
            directory = directory.Replace("//", "/");

            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));
            }
        }
Пример #2
0
        protected void Page_Load(object sender, EventArgs e)
        {
            string filename = Request["File"];

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

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

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

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

            IFilesStorageProviderV30 provider = null;

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

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

            string size = Request["Size"];

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

            size = size.ToLowerInvariant();

            // Verify permissions
            bool canDownload = false;

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

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

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

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

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

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

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

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

            ms.Seek(0, SeekOrigin.Begin);

            int rotation = 0;

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

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

            // Destination bitmap
            Bitmap result = null;

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

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

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

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

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

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

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

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

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

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

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

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

            ms.Dispose();

            source.Dispose();
            g.Dispose();
            result.Dispose();
        }
Пример #3
0
        protected void rptItems_DataBinding(object sender, EventArgs e)
        {
            permissionsManager.CurrentResourceName  = CurrentDirectory;
            permissionsManager.CurrentFilesProvider = lstProviders.SelectedValue;

            // Build a DataTable containing the proper information
            DataTable table = new DataTable("Items");

            table.Columns.Add("Type");
            table.Columns.Add("Name");
            table.Columns.Add("Size");
            table.Columns.Add("WikiMarkupLink");
            table.Columns.Add("Link");
            table.Columns.Add("Editable", typeof(bool));
            table.Columns.Add("FullPath");
            table.Columns.Add("Downloads");
            table.Columns.Add("CanDelete", typeof(bool));
            table.Columns.Add("CanDownload", typeof(bool));

            if (!canList)
            {
                lblNoList.Visible   = true;
                rptItems.DataSource = table;                 // This is empty
                return;
            }
            lblNoList.Visible = false;

            string currDir = CurrentDirectory;

            string[] dirs = provider.ListDirectories(currDir);

            string currentUser = SessionFacade.GetCurrentUsername();

            string[] currentGroups = SessionFacade.GetCurrentGroupNames();

            foreach (string s in dirs)
            {
                bool canListThisSubDir = AuthChecker.CheckActionForDirectory(provider, s, Actions.ForDirectories.List, currentUser, currentGroups);

                DataRow row = table.NewRow();
                row["Type"]           = "D";
                row["Name"]           = GetItemName(s) /* + "/"*/;
                row["Size"]           = "(" + ((int)(provider.ListFiles(s).Length + provider.ListDirectories(s).Length)) + ")";
                row["WikiMarkupLink"] = "&nbsp;";
                row["Link"]           = "";
                row["Editable"]       = false;
                row["FullPath"]       = s;
                row["Downloads"]      = "&nbsp;";
                row["CanDelete"]      = canDeleteDirs;
                row["CanDownload"]    = canListThisSubDir;
                table.Rows.Add(row);
            }

            string[] files = provider.ListFiles(currDir);
            foreach (string s in files)
            {
                FileDetails details = provider.GetFileDetails(s);

                DataRow row = table.NewRow();
                string  ext = Path.GetExtension(s).ToLowerInvariant();
                row["Type"]           = "F";
                row["Name"]           = GetItemName(s);
                row["Size"]           = Tools.BytesToString(details.Size);
                row["WikiMarkupLink"] = "{UP}" + s;
                if (canDownload)
                {
                    row["Link"] = "GetFile.aspx?File=" + Tools.UrlEncode(s).Replace("'", "&#39;") + "&amp;AsStreamAttachment=1&amp;Provider=" +
                                  provider.GetType().FullName + "&amp;NoHit=1";
                }
                else
                {
                    row["Link"] = "";
                }
                row["Editable"]    = canUpload && canDeleteFiles && (ext == ".jpg" || ext == ".jpeg" || ext == ".png");
                row["FullPath"]    = s;
                row["Downloads"]   = details.RetrievalCount.ToString();
                row["CanDelete"]   = canDeleteFiles;
                row["CanDownload"] = canDownload;
                table.Rows.Add(row);
            }

            rptItems.DataSource = table;
        }
Пример #4
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(currentWiki);
            }

            PageContent page = Pages.FindPage(currentWiki, pg);

            if (page == null)
            {
                UrlTools.RedirectHome(currentWiki);
            }
            if (page.Provider.ReadOnly)
            {
                UrlTools.Redirect(UrlTools.BuildUrl(currentWiki, page.FullName, GlobalSettings.PageExtension));
            }

            AuthChecker authChecker         = new AuthChecker(Collectors.CollectorsBox.GetSettingsProvider(currentWiki));
            bool        canManageDiscussion = authChecker.CheckActionForPage(page.FullName, Actions.ForPages.ManageDiscussion,
                                                                             SessionFacade.GetCurrentUsername(), SessionFacade.GetCurrentGroupNames(currentWiki));

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

            int id = -1;

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

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

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

            StringBuilder sb = new StringBuilder(500);

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

            lblDeleteMessageContent.Text = sb.ToString();
        }
Пример #5
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;
        }
Пример #6
0
        /// <summary>
        /// Determines whether a user can manage snippets and templates.
        /// </summary>
        /// <param name="username">The username.</param>
        /// <param name="groups">The groups.</param>
        /// <returns><c>true</c> if the user can manage snippets and templates, <c>false</c> otherwise.</returns>
        public static bool CanManageSnippetsAndTemplates(string username, string[] groups)
        {
            bool canManageSnippets = AuthChecker.CheckActionForGlobals(Actions.ForGlobals.ManageSnippetsAndTemplates, username, groups);

            return(canManageSnippets);
        }
Пример #7
0
        /// <summary>
        /// Determines whether a user can manager user accounts.
        /// </summary>
        /// <param name="username">The username.</param>
        /// <param name="groups">The groups.</param>
        /// <returns><c>true</c> if the user can manage user accounts, <c>false</c> otherwise.</returns>
        public static bool CanManageUsers(string username, string[] groups)
        {
            bool canManageUsers = AuthChecker.CheckActionForGlobals(Actions.ForGlobals.ManageAccounts, username, groups);

            return(canManageUsers);
        }
Пример #8
0
        /// <summary>
        /// Determines whether a user can manage the configuration.
        /// </summary>
        /// <param name="username">The username.</param>
        /// <param name="groups">The groups.</param>
        /// <returns><c>true</c> if the user can manage the configuration, <c>false</c> otherwise.</returns>
        public static bool CanManageConfiguration(string username, string[] groups)
        {
            bool canManageConfiguration = AuthChecker.CheckActionForGlobals(Actions.ForGlobals.ManageConfiguration, username, groups);

            return(canManageConfiguration);
        }
Пример #9
0
        /// <summary>
        /// Determines whether a user can manage namespaces.
        /// </summary>
        /// <param name="username">The username.</param>
        /// <param name="groups">The groups.</param>
        /// <returns><c>true</c> if the user can manage namespace, <c>false</c> otherwise.</returns>
        public static bool CanManageNamespaces(string username, string[] groups)
        {
            bool canManageNamespaces = AuthChecker.CheckActionForGlobals(Actions.ForGlobals.ManageNamespaces, username, groups);

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

            StringBuilder sb = new StringBuilder();

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

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

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

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

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

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

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

                if (rev1Content == null)
                {
                    Redirect();
                }
            }
            else
            {
                // Look for current
                if (Request["Rev1"].ToLowerInvariant() == "current")
                {
                    rev1Content = Content.GetPageContent(page, false);
                    rev1Text    = Properties.Messages.Current;
                }
                else
                {
                    Redirect();
                }
            }

            if (int.TryParse(Request["Rev2"], out rev2))
            {
                rev2Content = Pages.GetBackupContent(page, rev2);
                rev2Text    = rev2.ToString();
                if (rev2 >= 0 && rev2Content == null && Pages.GetBackupContent(page, rev2 - 1) != null)
                {
                    rev2Content = Content.GetPageContent(page, false);
                }

                if (rev2Content == null)
                {
                    Redirect();
                }
            }
            else
            {
                // Look for current or draft
                if (Request["Rev2"].ToLowerInvariant() == "current")
                {
                    rev2Content = Content.GetPageContent(page, false);
                    rev2Text    = Properties.Messages.Current;
                }
                else if (Request["Rev2"].ToLowerInvariant() == "draft")
                {
                    rev2Content = Pages.GetDraft(page);
                    rev2Text    = Properties.Messages.Draft;
                    draft       = true;
                    if (rev2Content == null)
                    {
                        Redirect();
                    }
                }
                else
                {
                    Redirect();
                }
            }

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

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

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

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

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

            sb.Append(result);

            lblDiff.Text = sb.ToString();
        }
Пример #11
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();
            var    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);

                        var ch = RecentChanges.GetAllChanges().ToArray();

                        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)
                                {
                                    var infos = Pages.GetCategoriesForPage(p);
                                    if (infos.Count == 0 && cat != "-")
                                    {
                                        continue;
                                    }
                                    else if (infos.Count != 0)
                                    {
                                        bool found = false;
                                        for (int k = 0; k < infos.Count; 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().ToArray();
                        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)
                                {
                                    var infos = Pages.GetCategoriesForPage(p);
                                    if (infos.Count == 0 && cat != "-")
                                    {
                                        continue;
                                    }
                                    else if (infos.Count != 0)
                                    {
                                        bool found = false;
                                        for (int k = 0; k < infos.Count; 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();
                    }
                }
            }
        }
Пример #12
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"] + ").");
			}

		}
Пример #13
0
        /// <summary>
        /// Performs a search.
        /// </summary>
        /// <param name="query">The search query.</param>
        /// <param name="mode">The search mode.</param>
        /// <param name="selectedCategories">The selected categories.</param>
        /// <param name="searchUncategorized">A value indicating whether to search uncategorized pages.</param>
        /// <param name="searchInAllNamespacesAndCategories">A value indicating whether to search in all namespaces and categories.</param>
        /// <param name="searchFilesAndAttachments">A value indicating whether to search files and attachments.</param>
        private void PerformSearch(string query, SearchOptions mode, List <string> selectedCategories, bool searchUncategorized, bool searchInAllNamespacesAndCategories, bool searchFilesAndAttachments)
        {
            SearchResultCollection results = null;
            DateTime begin = DateTime.Now;

            try {
                results = SearchTools.Search(query, true, searchFilesAndAttachments, mode);
            }
            catch (ArgumentException ex) {
                Log.LogEntry("Search threw an exception\n" + ex, EntryType.Warning, SessionFacade.CurrentUsername);
                results = new SearchResultCollection();
            }
            DateTime end = DateTime.Now;

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

            string currentUser = SessionFacade.GetCurrentUsername();

            string[] currentGroups = SessionFacade.GetCurrentGroupNames();

            CategoryInfo[] pageCategories;
            int            count = 0;

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

                if (res.Document.TypeTag == PageDocument.StandardTypeTag)
                {
                    currentPage    = (res.Document as PageDocument).PageInfo;
                    pageCategories = Pages.GetCategoriesForPage(currentPage);

                    // Verify permissions
                    bool canReadPage = AuthChecker.CheckActionForPage(currentPage,
                                                                      Actions.ForPages.ReadPage, currentUser, currentGroups);
                    if (!canReadPage)
                    {
                        continue;                                  // Skip
                    }
                }
                else if (res.Document.TypeTag == MessageDocument.StandardTypeTag)
                {
                    currentPage    = (res.Document as MessageDocument).PageInfo;
                    pageCategories = Pages.GetCategoriesForPage(currentPage);

                    // Verify permissions
                    bool canReadDiscussion = AuthChecker.CheckActionForPage(currentPage,
                                                                            Actions.ForPages.ReadDiscussion, currentUser, currentGroups);
                    if (!canReadDiscussion)
                    {
                        continue;                                        // Skip
                    }
                }
                else if (res.Document.TypeTag == PageAttachmentDocument.StandardTypeTag)
                {
                    currentPage    = (res.Document as PageAttachmentDocument).Page;
                    pageCategories = Pages.GetCategoriesForPage(currentPage);

                    // Verify permissions
                    bool canDownloadAttn = AuthChecker.CheckActionForPage(currentPage,
                                                                          Actions.ForPages.DownloadAttachments, currentUser, currentGroups);
                    if (!canDownloadAttn)
                    {
                        continue;                                      // Skip
                    }
                }
                else if (res.Document.TypeTag == FileDocument.StandardTypeTag)
                {
                    string[] fields = ((FileDocument)res.Document).Name.Split('|');
                    IFilesStorageProviderV30 provider = Collectors.FilesProviderCollector.GetProvider(fields[0]);
                    string directory = Tools.GetDirectoryName(fields[1]);

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

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

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

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

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

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

            PrintStats(end - begin, rows.Count);
        }
Пример #14
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);
            }
        }
Пример #15
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();
        }
Пример #16
0
        /// <summary>
        /// Determines whether a user can manage providers.
        /// </summary>
        /// <param name="username">The username.</param>
        /// <param name="groups">The groups.</param>
        /// <returns><c>true</c> if the user can manage providers, <c>false</c> otherwise.</returns>
        public static bool CanManageProviders(string username, IEnumerable <string> groups)
        {
            bool canManageProviders = AuthChecker.CheckActionForGlobals(Actions.ForGlobals.ManageProviders, username, groups);

            return(canManageProviders);
        }