protected void Page_Load(object sender, EventArgs e)
        {
            currentWiki = Tools.DetectCurrentWiki();

            object t = ViewState["ProviderType"];

            if (t != null)
            {
                providerType = (ProviderType)t;
            }
            t = ViewState["ExcludeReadOnly"];
            if (t != null)
            {
                excludeReadOnly = (bool)t;
            }
            t = ViewState["UsersProviderIntendedUse"];
            if (t != null)
            {
                usersProviderIntendedUse = (UsersProviderIntendedUse)t;
            }
            if (!Page.IsPostBack)
            {
                Reload();
                FillThemes(SelectedProvider);
            }
        }
Esempio n. 2
0
        protected void rptItems_DataBinding(object sender, EventArgs e)
        {
            if (pageFullName == null)
            {
                return;
            }

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

            table.Columns.Add("Name");
            table.Columns.Add("Size");
            table.Columns.Add("Link");

            string currentWiki = Tools.DetectCurrentWiki();

            foreach (IFilesStorageProviderV40 provider in Collectors.CollectorsBox.FilesProviderCollector.GetAllProviders(currentWiki))
            {
                string[] attachments = provider.ListPageAttachments(pageFullName);
                foreach (string s in attachments)
                {
                    DataRow row = table.NewRow();
                    row["Name"] = s;
                    row["Size"] = Tools.BytesToString(provider.GetPageAttachmentDetails(pageFullName, s).Size);
                    row["Link"] = "GetFile.aspx?File=" + Tools.UrlEncode(s).Replace("'", "'") + "&AsStreamAttachment=1&Provider=" +
                                  provider.GetType().FullName + "&IsPageAttachment=1&Page=" + Tools.UrlEncode(pageFullName);
                    table.Rows.Add(row);
                }
            }

            rptItems.DataSource = table;
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            string currentWiki = Tools.DetectCurrentWiki();

            if (!Page.IsPostBack)
            {
                // Localized strings for JavaScript
                StringBuilder sb = new StringBuilder();
                sb.Append(@"<script type=""text/javascript"">" + "\r\n<!--\n");
                sb.Append("var ConfirmMessage = '");
                sb.Append(Properties.Messages.ConfirmOperation);
                sb.Append("';\r\n");
                sb.AppendFormat("var UploadControl = '{0}';\r\n", fileUpload.ClientID);
                //sb.AppendFormat("var RefreshCommandParameter = '{0}';\r\n", btnRefresh.UniqueID);
                sb.AppendFormat("var OverwriteControl = '{0}';\r\n", chkOverwrite.ClientID);
                sb.Append("// -->\n</script>\n");
                lblStrings.Text = sb.ToString();

                // Setup upload information (max file size, allowed file types)
                lblUploadFilesInfo.Text = lblUploadFilesInfo.Text.Replace("$1", Tools.BytesToString(GlobalSettings.MaxFileSize * 1024));
                sb = new StringBuilder();
                string[] aft = Settings.GetAllowedFileTypes(currentWiki);
                for (int i = 0; i < aft.Length; i++)
                {
                    sb.Append(aft[i].ToUpper());
                    if (i != aft.Length - 1)
                    {
                        sb.Append(", ");
                    }
                }
                lblUploadFilesInfo.Text = lblUploadFilesInfo.Text.Replace("$2", sb.ToString());

                // Load Providers
                foreach (IFilesStorageProviderV40 prov in Collectors.CollectorsBox.FilesProviderCollector.GetAllProviders(currentWiki))
                {
                    ListItem item = new ListItem(prov.Information.Name, prov.GetType().FullName);
                    if (item.Value == GlobalSettings.DefaultFilesProvider)
                    {
                        item.Selected = true;
                    }
                    lstProviders.Items.Add(item);
                }

                if (CurrentPage == null)
                {
                    btnUpload.Enabled = false;
                }
            }

            // Set provider
            provider = Collectors.CollectorsBox.FilesProviderCollector.GetProvider(lstProviders.SelectedValue, currentWiki);

            if (!Page.IsPostBack)
            {
                rptItems.DataBind();
            }

            DetectPermissions();
            SetupControls();
        }
Esempio n. 4
0
 protected void Application_AcquireRequestState(object sender, EventArgs e)
 {
     if (HttpContext.Current.Session != null)
     {
         // Try to automatically login the user through the cookie
         ScrewTurn.Wiki.LoginTools.TryAutoLogin(Tools.DetectCurrentWiki());
     }
 }
Esempio n. 5
0
 /// <summary>
 /// Initializes a new instance of the <see cref="T:ExtendedPageInfo" /> class.
 /// </summary>
 /// <param name="pageContent">The <see cref="T:PageContent" /> object.</param>
 /// <param name="creator">The creator.</param>
 /// <param name="lastAuthor">The last author.</param>
 public ExtendedPageInfo(PageContent pageContent, string creator, string lastAuthor)
 {
     this.pageContent  = pageContent;
     this.title        = FormattingPipeline.PrepareTitle(Tools.DetectCurrentWiki(), pageContent.Title, false, FormattingContext.PageContent, pageContent.FullName);
     this.creator      = creator;
     this.lastAuthor   = lastAuthor;
     this.messageCount = Pages.GetMessageCount(pageContent);
 }
Esempio n. 6
0
 protected void Page_Load(object sender, EventArgs e)
 {
     currentWiki = Tools.DetectCurrentWiki();
     if (!Page.IsPostBack)
     {
         CurrentProvider = GlobalSettings.DefaultPagesProvider;
     }
 }
Esempio n. 7
0
 protected void cvCaptcha_ServerValidate(object source, ServerValidateEventArgs args)
 {
     if (!Settings.GetDisableCaptchaControl(Tools.DetectCurrentWiki()))
     {
         args.IsValid = txtCaptcha.Text == SessionFacade.GetCaptcha();
     }
     else
     {
         args.IsValid = true;
     }
 }
Esempio n. 8
0
        protected void Page_Load(object sender, EventArgs e)
        {
            string currentWiki = Tools.DetectCurrentWiki();

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

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

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

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

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


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

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

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

                writer.WriteEndElement();
                writer.WriteEndDocument();
            }
        }
Esempio n. 9
0
        protected void Page_Load(object sender, EventArgs e)
        {
            // Try to detect current namespace and page
            currentNamespace    = Tools.DetectCurrentNamespace();
            currentPageFullName = Tools.DetectCurrentPage(true);
            currentWiki         = Tools.DetectCurrentWiki();

            lblStrings.Text = string.Format("<script type=\"text/javascript\">\r\n<!--\r\n__BaseName = \"{0}\";\r\n__ConfirmMessage = \"{1}\";\r\n// -->\r\n</script>",
                                            CphMaster.ClientID + "_", Properties.Messages.ConfirmOperation);

            PrintHtmlHead();
            PrintHeader();
            PrintSidebar();
            PrintFooter();
            PrintPageHeaderAndFooter();
        }
Esempio n. 10
0
        /// <summary>
        /// Notifies an error to the email addresses set in the configuration, swallowing all exceptions.
        /// </summary>
        /// <param name="ex">The exception to notify.</param>
        /// <param name="url">The URL that caused the error, if any.</param>
        public static void NotifyError(Exception ex, string url)
        {
            try {
                string[] recipients = GlobalSettings.ErrorsEmails;

                if (recipients.Length > 0)
                {
                    AsyncSendMassEmail(recipients, GlobalSettings.SenderEmail, "Error Notification", "An error occurred on " +
                                       DateTime.Now.ToString("yyyy'/'MM'/'dd' 'HH':'mm':'ss") + " (server time) in the wiki hosted at " +
                                       Settings.GetMainUrl(Tools.DetectCurrentWiki()) + " - server stack trace follows.\r\n\r\n" +
                                       (!string.IsNullOrEmpty(url) ? url + "\r\n\r\n" : "") +
                                       ex.ToString(), false);
                }
            }
            catch { }
        }
Esempio n. 11
0
        /// <summary>
        /// Creates a new instance of the <see cref="T:SearchResultRow" /> class.
        /// </summary>
        /// <param name="result">The result to use.</param>
        /// <returns>The instance.</returns>
        public static SearchResultRow CreateInstance(SearchResult result)
        {
            //string queryStringKeywords = "HL=" + GetKeywordsForQueryString(result.Matches);
            string queryStringKeywords = "HL=";

            if (result.DocumentType == DocumentType.Page)
            {
                PageDocument doc = result.Document as PageDocument;
                return(new SearchResultRow(doc.PageFullName + GlobalSettings.PageExtension + "?" + queryStringKeywords, Page,
                                           FormattingPipeline.PrepareTitle(Tools.DetectCurrentWiki(), doc.Title, false, FormattingContext.PageContent, doc.PageFullName),
                                           string.IsNullOrEmpty(doc.HighlightedContent) ? doc.Content : doc.HighlightedContent));
            }
            else if (result.DocumentType == DocumentType.Message)
            {
                MessageDocument doc     = result.Document as MessageDocument;
                PageContent     content = Pages.FindPage(doc.Wiki, doc.PageFullName);

                return(new SearchResultRow(content.FullName + GlobalSettings.PageExtension + "?" + queryStringKeywords + "&amp;Discuss=1#" + Tools.GetMessageIdForAnchor(doc.DateTime), Message,
                                           FormattingPipeline.PrepareTitle(Tools.DetectCurrentWiki(), doc.Subject, false, FormattingContext.MessageBody, content.FullName) + " (" +
                                           FormattingPipeline.PrepareTitle(Tools.DetectCurrentWiki(), content.Title, false, FormattingContext.MessageBody, content.FullName) +
                                           ")", doc.HighlightedBody));
            }
            else if (result.DocumentType == DocumentType.File)
            {
                FileDocument fileDoc = result.Document as FileDocument;

                string[] fileParts = fileDoc.FileName.Split(new char[] { '|' });

                return(new SearchResultRow("GetFile.aspx?File=" + Tools.UrlEncode(fileDoc.FileName.Substring(fileParts[0].Length + 1)) +
                                           "&amp;Provider=" + Tools.UrlEncode(fileParts[0]),
                                           File, fileParts[1], fileDoc.HighlightedFileContent));
            }
            else if (result.DocumentType == DocumentType.Attachment)
            {
                PageAttachmentDocument attnDoc = result.Document as PageAttachmentDocument;
                PageContent            content = Pages.FindPage(attnDoc.Wiki, attnDoc.PageFullName);

                return(new SearchResultRow(content.FullName + GlobalSettings.PageExtension, Attachment,
                                           attnDoc.FileName + " (" +
                                           FormattingPipeline.PrepareTitle(Tools.DetectCurrentWiki(), content.Title, false, FormattingContext.PageContent, content.FullName) +
                                           ")", attnDoc.HighlightedFileContent));
            }
            else
            {
                throw new NotSupportedException();
            }
        }
Esempio n. 12
0
        protected void Page_Load(object sender, EventArgs e)
        {
            string        currentWiki = Tools.DetectCurrentWiki();
            StringBuilder sb          = new StringBuilder(100);

            sb.Append("<script type=\"text/javascript\">\r\n<!--\r\n");
            sb.AppendFormat("\tvar ConfirmMessage = \"{0}\";\r\n", Properties.Messages.ConfirmOperation);
            sb.Append("// -->\r\n</script>");
            lblStrings.Text = sb.ToString();

            Page.Title = Properties.Messages.AdminTitle + " - " + Settings.GetWikiTitle(currentWiki);

            lblJS.Text = Tools.GetJavaScriptIncludes();

            SetupButtons();

            SetupButtonsVisibility(currentWiki);
        }
Esempio n. 13
0
        protected void Page_Load(object sender, EventArgs e)
        {
            currentWiki = Tools.DetectCurrentWiki();

            if (!Page.IsPostBack)
            {
                NamespaceInfo currentNamespace     = Tools.DetectCurrentNamespaceInfo();
                string        currentNamespaceName = currentNamespace != null ? currentNamespace.Name + "." : "";
                StringBuilder sb = new StringBuilder(200);
                sb.Append("<script type=\"text/javascript\">\r\n<!--\r\n");
                sb.AppendFormat("\tvar MarkupControl = \"{0}\";\r\n", txtMarkup.ClientID);
                sb.AppendFormat("\tvar VisualControl = \"{0}\";\r\n", lblWYSIWYG.ClientID);
                sb.AppendFormat("\tvar CurrentPage = \"{0}\";\r\n", (currentPage != null ? Tools.UrlEncode(currentPage.FullName) : ""));
                sb.AppendFormat("\tvar CurrentNamespace = \"{0}\";\r\n", Tools.UrlEncode(currentNamespaceName));
                sb.Append("// -->\r\n</script>");
                lblStrings.Text = sb.ToString();

                if (ViewState["ToolbarVisible"] == null)
                {
                    ViewState["ToolbarVisible"] = true;
                }

                InitToolbar();
            }

            if (mlvEditor.ActiveViewIndex == 1)
            {
                inWYSIWYG = true;
            }
            else
            {
                inWYSIWYG = false;
            }

            //SelectTab(0);
            if (ViewState["Tab"] != null)
            {
                SelectTab((int)ViewState["Tab"]);
            }

            LoadSnippets();

            PrintCustomSpecialTags();
        }
Esempio n. 14
0
        /// <summary>
        /// Determines whether a user can manage pages in at least one namespace.
        /// </summary>
        /// <param name="username">The username.</param>
        /// <param name="groups">The groups.</param>
        /// <returns><c>true</c> if the the user can manage pages in at least one namespace, <c>false</c> otherwise.</returns>
        public static bool CanManagePages(string username, string[] groups)
        {
            AuthChecker authChecker = new AuthChecker(Collectors.CollectorsBox.GetSettingsProvider(Tools.DetectCurrentWiki()));

            if (authChecker.CheckActionForNamespace(null, Actions.ForNamespaces.ManagePages, username, groups))
            {
                return(true);
            }

            foreach (NamespaceInfo ns in Pages.GetNamespaces(Tools.DetectCurrentWiki()))
            {
                if (authChecker.CheckActionForNamespace(ns, Actions.ForNamespaces.ManagePages, username, groups))
                {
                    return(true);
                }
            }

            return(false);
        }
Esempio n. 15
0
        /// <summary>
        /// Initializes a new instance of the <see cref="T:RevisionRow" /> class.
        /// </summary>
        /// <param name="revision">The revision (<b>-1</b> for current).</param>
        /// <param name="content">The original page content.</param>
        /// <param name="canRollback">A value indicating whether the current user can rollback the page.</param>
        public RevisionRow(int revision, PageContent content, bool canRollback)
        {
            string currentWiki = Tools.DetectCurrentWiki();

            this.wiki = currentWiki;
            this.page = content.FullName;
            if (revision == -1)
            {
                this.revision = Properties.Messages.Current;
            }
            else
            {
                this.revision = revision.ToString();
            }
            title            = FormattingPipeline.PrepareTitle(currentWiki, content.Title, false, FormattingContext.PageContent, content.FullName);
            savedOn          = Preferences.AlignWithTimezone(currentWiki, content.LastModified).ToString(Settings.GetDateTimeFormat(currentWiki));
            savedBy          = Users.UserLink(currentWiki, content.User);
            comment          = content.Comment;
            this.canRollback = canRollback;
        }
Esempio n. 16
0
        /// <summary>
        /// Initializes a new instance of the <see cref="T:PageRow" /> class.
        /// </summary>
        /// <param name="nspace">The namespace.</param>
        /// <param name="nspacePrefix">The namespace prefix.</param>
        /// <param name="name">The full name.</param>
        /// <param name="linkingPages">The pages that link the wanted page.</param>
        public WantedPageRow(string nspace, string nspacePrefix, string name, List <string> linkingPages)
        {
            this.nspace       = nspace;
            this.nspacePrefix = nspacePrefix;
            this.name         = name;

            string currentWiki = Tools.DetectCurrentWiki();

            StringBuilder sb = new StringBuilder(100);

            for (int i = 0; i < linkingPages.Count; i++)
            {
                PageContent page = Pages.FindPage(currentWiki, linkingPages[i]);
                if (page != null)
                {
                    sb.AppendFormat(@"<a href=""{0}{1}"" title=""{2}"" target=""_blank"">{2}</a>, ", page.FullName, GlobalSettings.PageExtension,
                                    FormattingPipeline.PrepareTitle(currentWiki, page.Title, false, FormattingContext.Other, page.FullName));
                }
            }
            this.linkingPages = sb.ToString().TrimEnd(' ', ',');
        }
Esempio n. 17
0
        protected void Page_Load(object sender, EventArgs e)
        {
            // Try to detect current namespace
            currentNamespace = Tools.DetectCurrentNamespace();
            currentWiki      = Tools.DetectCurrentWiki();

            lblStrings.Text = string.Format("<script type=\"text/javascript\">\r\n<!--\r\n__BaseName = \"{0}\";\r\n__ConfirmMessage = \"{1}\";\r\n// -->\r\n</script>",
                                            CphMasterSA.ClientID + "_", Properties.Messages.ConfirmOperation);

            string nspace = currentNamespace;

            if (string.IsNullOrEmpty(nspace))
            {
                nspace = "";
            }
            else
            {
                nspace += ".";
            }
            lnkMainPage.NavigateUrl = nspace + "Default.aspx";

            if (!Page.IsPostBack)
            {
                string referrer = Request.UrlReferrer != null?Request.UrlReferrer.FixHost().ToString() : "";

                if (!string.IsNullOrEmpty(referrer))
                {
                    lnkPreviousPage.Visible     = true;
                    lnkPreviousPage.NavigateUrl = referrer;
                }
                else
                {
                    lnkPreviousPage.Visible = false;
                }
            }

            PrintHtmlHead();
            PrintHeader();
            PrintFooter();
        }
Esempio n. 18
0
        /// <summary>
        /// Initializes a new instance of the <see cref="T:PageRow" /> class.
        /// </summary>
        /// <param name="page">The page content.</param>
        /// <param name="firstContent">The first revision content.</param>
        /// <param name="discussionCount">The number of messages in the discussion.</param>
        /// <param name="revisionCount">The number of revisions.</param>
        /// <param name="isOrphan">A value indicating whether the page is orphan.</param>
        /// <param name="canEdit">A value indicating whether the current user can edit the page.</param>
        /// <param name="canSelect">A value indicating whether the current user can select the page.</param>
        /// <param name="canSetPermissions">A value indicating whether the current user can set permissions for the page.</param>
        /// <param name="selected">A value indicating whether the page is selected.</param>
        public PageRow(PageContent page, PageContent firstContent, int discussionCount, int revisionCount,
                       bool isOrphan, bool canEdit, bool canSelect, bool canSetPermissions, bool selected)
        {
            string currentWiki = Tools.DetectCurrentWiki();

            fullName       = page.FullName;
            title          = FormattingPipeline.PrepareTitle(currentWiki, page.Title, false, FormattingContext.Other, page.FullName);
            createdBy      = firstContent.User;
            createdOn      = Preferences.AlignWithTimezone(currentWiki, page.CreationDateTime).ToString(Settings.GetDateTimeFormat(currentWiki));
            lastModifiedBy = page.User;
            lastModifiedOn = Preferences.AlignWithTimezone(currentWiki, page.LastModified).ToString(Settings.GetDateTimeFormat(currentWiki));
            discussion     = discussionCount.ToString();
            revisions      = revisionCount.ToString();
            provider       = page.Provider.Information.Name;

            this.isOrphan = isOrphan;

            this.canEdit           = canEdit;
            this.canSelect         = canSelect;
            this.canSetPermissions = canSetPermissions;
            additionalClass        = selected ? " selected" : "";
        }
Esempio n. 19
0
 /// <summary>
 /// Detects the permissions of the current user.
 /// </summary>
 private void DetectPermissions()
 {
     if (CurrentPage != null)
     {
         string      currentWiki   = Tools.DetectCurrentWiki();
         string      currentUser   = SessionFacade.GetCurrentUsername();
         string[]    currentGroups = SessionFacade.GetCurrentGroupNames(currentWiki);
         AuthChecker authChecker   = new AuthChecker(Collectors.CollectorsBox.GetSettingsProvider(currentWiki));
         canDownload = authChecker.CheckActionForPage(CurrentPage.FullName, Actions.ForPages.DownloadAttachments, currentUser, currentGroups);
         canUpload   = authChecker.CheckActionForPage(CurrentPage.FullName, Actions.ForPages.UploadAttachments, currentUser, currentGroups);
         canDelete   = authChecker.CheckActionForPage(CurrentPage.FullName, Actions.ForPages.DeleteAttachments, currentUser, currentGroups);
         isAdmin     = Array.Find(currentGroups, delegate(string g) { return(g == Settings.GetAdministratorsGroup(currentWiki)); }) != null;
     }
     else
     {
         canDownload = false;
         canUpload   = false;
         canDelete   = false;
         isAdmin     = false;
     }
     lstProviders.Visible = isAdmin;
 }
Esempio n. 20
0
        /// <summary>
        /// Initializes a new instance of the <see cref="T:UserRow" /> class.
        /// </summary>
        /// <param name="user">The original user.</param>
        /// <param name="groups">The groups the user is member of.</param>
        /// <param name="selected">A value indicating whether the user is selected.</param>
        public UserRow(UserInfo user, List <UserGroup> groups, bool selected)
        {
            username    = user.Username;
            displayName = Users.GetDisplayName(user);
            email       = user.Email;

            StringBuilder sb = new StringBuilder(50);

            for (int i = 0; i < groups.Count; i++)
            {
                sb.Append(groups[i].Name);
                if (i != groups.Count - 1)
                {
                    sb.Append(", ");
                }
            }
            memberOf = sb.ToString();

            regDateTime     = user.DateTime.ToString(Settings.GetDateTimeFormat(Tools.DetectCurrentWiki()));
            provider        = user.Provider.Information.Name;
            additionalClass = (selected ? " selected" : "") + (!user.Active ? " inactive" : "");
        }
Esempio n. 21
0
        /// <summary>
        /// Initializes a new instance of the <see cref="T:LogEntryRow" /> class.
        /// </summary>
        /// <param name="entry">The original log entry.</param>
        public LogEntryRow(LogEntry entry)
        {
            string currentWiki = Tools.DetectCurrentWiki();

            imageTag = entry.EntryType.ToString();
            dateTime = Preferences.AlignWithTimezone(currentWiki, entry.DateTime).ToString(Settings.GetDateTimeFormat(currentWiki)).Replace(" ", "&nbsp;");
            user     = entry.User.Replace(" ", "&nbsp;");
            wiki     = string.IsNullOrEmpty(entry.Wiki) ? "" : entry.Wiki.Replace(" ", "&nbsp;");
            message  = entry.Message.Replace("&", "&amp;");

            if (entry.EntryType == EntryType.Error)
            {
                additionalClass = " error";
            }
            else if (entry.EntryType == EntryType.Warning)
            {
                additionalClass = " warning";
            }
            else
            {
                additionalClass = "";
            }
        }
Esempio n. 22
0
        protected void Page_Load(object sender, EventArgs e)
        {
            // Try to detect current namespace
            currentNamespaces = Tools.DetectCurrentNamespace();
            currentWiki       = Tools.DetectCurrentWiki();

            lblStringsClean.Text = string.Format("<script type=\"text/javascript\">\r\n<!--\r\n__BaseName = \"{0}\";\r\n__ConfirmMessage = \"{1}\";\r\n// -->\r\n</script>",
                                                 CphMasterClean.ClientID + "_", Properties.Messages.ConfirmOperation);

            string nspace = currentNamespaces;

            if (string.IsNullOrEmpty(nspace))
            {
                nspace = "";
            }
            else
            {
                nspace += ".";
            }

            PrintHtmlHead();
            PrintHeader();
            PrintFooter();
        }
Esempio n. 23
0
 protected void Page_Load(object sender, EventArgs e)
 {
     currentWiki = Tools.DetectCurrentWiki();
 }
Esempio n. 24
0
        protected void rptItems_DataBinding(object sender, EventArgs e)
        {
            provider = Collectors.CollectorsBox.FilesProviderCollector.GetProvider(lstProviders.SelectedValue, Tools.DetectCurrentWiki());

            if (provider == null || CurrentPage == null)
            {
                return;
            }

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

            table.Columns.Add("Name");
            table.Columns.Add("Size");
            table.Columns.Add("Editable", typeof(bool));
            table.Columns.Add("Page");
            table.Columns.Add("Link");
            table.Columns.Add("CanDelete", typeof(bool));
            table.Columns.Add("CanDownload", typeof(bool));

            string[] attachments = provider.ListPageAttachments(CurrentPage.FullName);
            foreach (string s in attachments)
            {
                FileDetails details = provider.GetPageAttachmentDetails(CurrentPage.FullName, s);

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

            rptItems.DataSource = table;
        }
Esempio n. 25
0
        protected void Page_Load(object sender, EventArgs e)
        {
            string filename = Request["File"];

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

            string currentWiki = Tools.DetectCurrentWiki();

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

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

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

            IFilesStorageProviderV40 provider;

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

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

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

            // Verify permissions
            bool canDownload = false;

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

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

            long size = -1;

            FileDetails details = null;

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

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

            string mime = "";

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

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

            bool retrieved = false;

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

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

            // Set the cache duration accordingly to the file date/time
            //Response.AddFileDependency(filename);
            //Response.Cache.SetETagFromFileDependencies();
            //Response.Cache.SetLastModifiedFromFileDependencies();
            Response.Cache.SetETag(filename.GetHashCode().ToString() + "-" + size.ToString());
            Response.Cache.SetCacheability(HttpCacheability.Public);
            Response.Cache.SetSlidingExpiration(true);
            Response.Cache.SetValidUntilExpires(true);
            Response.Cache.VaryByParams["File"]             = true;
            Response.Cache.VaryByParams["Provider"]         = true;
            Response.Cache.VaryByParams["Page"]             = true;
            Response.Cache.VaryByParams["IsPageAttachment"] = true;
        }
Esempio n. 26
0
        /// <summary>
        /// Properly routes the current virtual request to a physical ASP.NET page.
        /// </summary>
        public static void RouteCurrentRequest()
        {
            string physicalPath = null;

            try {
                physicalPath = HttpContext.Current.Request.PhysicalPath;
            }
            catch (ArgumentException) {
                // Illegal characters in path
                HttpContext.Current.Response.Redirect("~/PageNotFound");
                return;
            }

            // Extract the physical page name, e.g. MainPage, Edit or Category
            string pageName = Path.GetFileNameWithoutExtension(physicalPath);
            // Exctract the extension, e.g. .ashx or .aspx
            string ext = (Path.GetExtension(HttpContext.Current.Request.PhysicalPath) + "").ToLowerInvariant();

            // Remove trailing dot, .ashx -> ashx
            if (ext.Length > 0)
            {
                ext = ext.Substring(1);
            }

            // IIS7+Integrated Pipeline handles all requests through the ASP.NET engine
            // All non-interesting files are not processed, such as GIF, CSS, etc.
            if (ext.Length > 0 && ext != "ashx" && ext != "aspx")
            {
                return;
            }

            // Extract the current namespace, if any
            string nspace = GetCurrentNamespace() + "";

            if (!string.IsNullOrEmpty(nspace))
            {
                // Verify that namespace exists
                if (Pages.FindNamespace(Tools.DetectCurrentWiki(), nspace) == null)
                {
                    HttpContext.Current.Response.Redirect("~/PageNotFound?Page=" + pageName);
                }
            }
            // Trim Namespace. from pageName
            if (!string.IsNullOrEmpty(nspace))
            {
                pageName = pageName.Substring(nspace.Length + 1);
            }

            string queryString = "";             // Empty or begins with ampersand, not question mark

            try {
                // This might throw exceptions if 3rd-party modules interfer with the request pipeline
                queryString = HttpContext.Current.Request.Url.Query.Replace("?", "&");                 // Host not used
            }
            catch { }

            if (ext.Equals("ashx"))
            {
                // Content page requested, process it via Default.aspx
                if (!queryString.Contains("NS="))
                {
                    HttpContext.Current.RewritePath("~/Default.aspx?Page=" + Tools.UrlEncode(pageName) + "&NS=" + Tools.UrlEncode(nspace) + queryString);
                }
                else
                {
                    HttpContext.Current.RewritePath("~/Default.aspx?Page=" + Tools.UrlEncode(pageName) + queryString);
                }
            }
            else if (ext.Equals("aspx"))
            {
                // System page requested, redirect to the root of the application
                // For example: http://www.server.com/Namespace.Edit.aspx?Page=MainPage -> http://www.server.com/Edit.aspx?Page=MainPage&NS=Namespace
                if (!string.IsNullOrEmpty(nspace))
                {
                    if (!queryString.Contains("NS="))
                    {
                        HttpContext.Current.RewritePath("~/" + Tools.UrlEncode(pageName) + "." + ext + "?NS=" + Tools.UrlEncode(nspace) + queryString);
                    }
                    else
                    {
                        if (queryString.Length > 1)
                        {
                            queryString = "?" + queryString.Substring(1);
                        }
                        HttpContext.Current.RewritePath("~/" + Tools.UrlEncode(pageName) + "." + ext + queryString);
                    }
                }
            }
            // else nothing to do
        }
Esempio n. 27
0
        protected void btnUpload_Click(object sender, EventArgs e)
        {
            if (canUpload)
            {
                lblUploadResult.Text = "";
                if (fileUpload.HasFile)
                {
                    if (fileUpload.FileBytes.Length > GlobalSettings.MaxFileSize * 1024)
                    {
                        lblUploadResult.Text     = Properties.Messages.FileTooBig;
                        lblUploadResult.CssClass = "resulterror";
                    }
                    else
                    {
                        // Check file extension
                        string[] aft     = Settings.GetAllowedFileTypes(Tools.DetectCurrentWiki());
                        bool     allowed = false;

                        if (aft.Length > 0 && aft[0] == "*")
                        {
                            allowed = true;
                        }
                        else
                        {
                            string ext = Path.GetExtension(fileUpload.FileName);
                            if (ext == null)
                            {
                                ext = "";
                            }
                            if (ext.StartsWith("."))
                            {
                                ext = ext.Substring(1).ToLowerInvariant();
                            }
                            foreach (string ft in aft)
                            {
                                if (ft == ext)
                                {
                                    allowed = true;
                                    break;
                                }
                            }
                        }

                        if (!allowed)
                        {
                            lblUploadResult.Text     = Properties.Messages.InvalidFileType;
                            lblUploadResult.CssClass = "resulterror";
                        }
                        else
                        {
                            bool done = FilesAndAttachments.StorePageAttachment(provider, CurrentPage.FullName, fileUpload.FileName, fileUpload.FileContent, chkOverwrite.Checked);

                            if (!done)
                            {
                                lblUploadResult.Text     = Properties.Messages.CannotStoreFile;
                                lblUploadResult.CssClass = "resulterror";
                            }
                            rptItems.DataBind();
                        }
                    }
                }
                else
                {
                    lblUploadResult.Text     = Properties.Messages.FileVoid;
                    lblUploadResult.CssClass = "resulterror";
                }
            }
        }
Esempio n. 28
0
 protected void lstProviders_SelectedIndexChanged(object sender, EventArgs e)
 {
     provider = Collectors.CollectorsBox.FilesProviderCollector.GetProvider(lstProviders.SelectedValue, Tools.DetectCurrentWiki());
     rptItems.DataBind();
 }
Esempio n. 29
0
        /// <summary>
        /// Prints a message.
        /// </summary>
        /// <param name="message">The message to print.</param>
        /// <param name="parent">The parent message, or <c>null</c>.</param>
        /// <param name="sb">The output <see cref="T:StringBuilder" />.</param>
        private void PrintMessage(Message message, Message parent, StringBuilder sb)
        {
            string currentWiki = Tools.DetectCurrentWiki();

            // Print header
            sb.Append(@"<div class=""messageheader"">");
            //sb.AppendFormat(@"<a id=""MSG_{0}""></a>", message.ID);

            if (!currentPage.Provider.ReadOnly)
            {
                // Print reply/edit/delete buttons only if provider is not read-only
                sb.Append(@"<div class=""reply"">");

                if (canPostMessages)
                {
                    sb.Append(@"<a class=""reply"" href=""");
                    sb.Append(UrlTools.BuildUrl(currentWiki, "Post.aspx?Page=", Tools.UrlEncode(currentPage.FullName), "&amp;Parent=", message.ID.ToString()));

                    sb.Append(@""">");
                    sb.Append(Properties.Messages.Reply);
                    sb.Append("</a>");
                }

                // If current user is the author of the message or is an admin, print the edit hyperLink
                // A message can be edited only if the user is authenticated - anonymous users cannot edit their messages
                if (SessionFacade.LoginKey != null && ((message.Username == SessionFacade.CurrentUsername && canPostMessages) || canManageDiscussion))
                {
                    sb.Append(@" <a class=""edit"" href=""");
                    sb.Append(UrlTools.BuildUrl(currentWiki, "Post.aspx?Page=", Tools.UrlEncode(currentPage.FullName), "&amp;Edit=", message.ID.ToString()));

                    sb.Append(@""">");
                    sb.Append(Properties.Messages.Edit);
                    sb.Append("</a>");
                }

                // If the current user is an admin, print the delete hyperLink
                if (SessionFacade.LoginKey != null && canManageDiscussion)
                {
                    sb.Append(@" <a class=""delete"" href=""");
                    sb.Append(UrlTools.BuildUrl(currentWiki, "Operation.aspx?Operation=DeleteMessage&amp;Message=", message.ID.ToString(),
                                                "&amp;Page=", Tools.UrlEncode(currentPage.FullName)));

                    sb.Append(@""">");
                    sb.Append(Properties.Messages.Delete);
                    sb.Append("</a>");
                }
                sb.Append("</div>");
            }

            sb.Append(@"<div>");
            sb.AppendFormat(@"<a id=""{0}"" href=""#{0}"" title=""Permalink"">&#0182;</a> ", Tools.GetMessageIdForAnchor(message.DateTime));

            // Print subject
            if (message.Subject.Length > 0)
            {
                sb.Append(@"<span class=""messagesubject"">");
                sb.Append(FormattingPipeline.PrepareTitle(currentWiki, message.Subject, false, FormattingContext.MessageBody, currentPage.FullName));
                sb.Append("</span>");
            }

            // Print message date/time
            sb.Append(@"<span class=""messagedatetime"">");
            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("</span>");

            sb.Append("</div>");

            sb.Append("</div>");

            // Print body
            sb.Append(@"<div class=""messagebody"">");
            sb.Append(FormattingPipeline.FormatWithPhase3(currentWiki, FormattingPipeline.FormatWithPhase1And2(currentWiki, message.Body, false, FormattingContext.MessageBody, currentPage.FullName),
                                                          FormattingContext.MessageBody, currentPage.FullName));
            sb.Append("</div>");
        }
Esempio n. 30
0
        protected void Page_Load(object sender, EventArgs e)
        {
            currentWiki = Tools.DetectCurrentWiki();

            if (!Page.IsPostBack)
            {
                permissionsManager.CurrentResourceName = "/";

                // Localized strings for JavaScript
                StringBuilder sb = new StringBuilder();
                sb.Append(@"<script type=""text/javascript"">" + "\n<!--\n");
                sb.Append("var ConfirmMessage = '");
                sb.Append(Properties.Messages.ConfirmOperation);
                sb.Append("';\r\n");
                sb.AppendFormat("var CurrentNamespace = \"{0}\";\r\n", Tools.DetectCurrentNamespace());
                sb.Append("// -->\n</script>\n");
                lblStrings.Text = sb.ToString();

                // Setup upload information (max file size, allowed file types)
                lblUploadFilesInfo.Text = lblUploadFilesInfo.Text.Replace("$1", Tools.BytesToString(GlobalSettings.MaxFileSize * 1024));
                sb = new StringBuilder();
                string[] aft = Settings.GetAllowedFileTypes(currentWiki);
                for (int i = 0; i < aft.Length; i++)
                {
                    sb.Append(aft[i].ToUpper());
                    if (i != aft.Length - 1)
                    {
                        sb.Append(", ");
                    }
                }
                lblUploadFilesInfo.Text = lblUploadFilesInfo.Text.Replace("$2", sb.ToString());

                LoadProviders();

                permissionsManager.CurrentFilesProvider = lstProviders.SelectedValue;

                // See if a dir is specified in query string
                if (Request["Dir"] != null)
                {
                    string currDir = Request["Dir"];
                    if (!currDir.StartsWith("/"))
                    {
                        currDir = "/" + currDir;
                    }
                    if (!currDir.EndsWith("/"))
                    {
                        currDir += "/";
                    }
                    CurrentDirectory = currDir;
                }
            }

            // Set provider
            provider = Collectors.CollectorsBox.FilesProviderCollector.GetProvider(lstProviders.SelectedValue, currentWiki);

            // The following actions are verified ***FOR THE CURRENT DIRECTORY***:
            // - List contents
            // - Download files
            // - Upload files
            // - Create directories
            // - Delete/Rename files -> hide/show buttons in repeater
            // - Delete/Rename directories --> hide/show buttons in repeater
            // - Manage Permissions -> avoid setting permissionsManager.CurrentResourceName/CurrentFilesProvider if not authorized
            // - Member of Administrators -> hide/show provider selection
            // ---> recheck everywhere an action is performed

            DetectPermissions();

            if (!Page.IsPostBack)
            {
                rptItems.DataBind();
            }

            PopulateBreadcrumb();

            SetupControlsForPermissions();
        }